Skip to content

Commit 0b5b499

Browse files
committed
problem solution & test 0001
1 parent 3f20163 commit 0b5b499

File tree

8 files changed

+36
-11
lines changed

8 files changed

+36
-11
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,6 @@ My clean, typed, and tested solutions to LeetCode problems (Python 3.10+).
1313
## Problems
1414
| # | Title | Difficulty | Solution |
1515
|---|-------|------------|----------|
16-
| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [`0001_two_sum.py`](solutions/0001_two_sum.py) |
16+
| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [`0001_two_sum.py`](solutions/two_sum_0001.py) |
1717
| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium | [`0002_add_two_numbers.py`](solutions/0002_add_two_numbers.py) |
1818
<!-- END_TABLE -->

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ select = ["E", "W", "F", "I", "UP", "C4"]
99
testpaths = ["tests"]
1010
python_files = ["test_*.py"]
1111
python_classes = ["Test*"]
12-
python_functions = ["test_*"]
12+
python_functions = ["test_*"]
13+
pythonpath = ["."]

scripts/update_readme.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111

1212
def fetch_full_problems_cache():
13-
'''Забирает ВСЕ задачи с LeetCode постранично и сохраняет в кэш.'''
13+
"""Забирает ВСЕ задачи с LeetCode постранично и сохраняет в кэш."""
1414
print('Get all LeetCode problems...')
1515
all_questions = []
1616
skip = 0
@@ -62,20 +62,22 @@ def fetch_full_problems_cache():
6262

6363

6464
def load_problems_cache():
65-
'''Загружает кэш или создаёт новый (полный).'''
65+
"""Загружает кэш или создаёт новый (полный)."""
6666
if Path(CACHE_FILE).exists():
6767
with open(CACHE_FILE, 'r') as f:
6868
return json.load(f)
6969
return fetch_full_problems_cache()
7070

71-
7271
def extract_problem_number(file_name: str) -> int | None:
73-
'''Извлекает номер задачи из имени файла.'''
74-
if not file_name.endswith('.py'):
72+
"""Извлекает номер задачи из имени файла."""
73+
if not file_name.endswith('.py') or not file_name[:-3].replace('_', '').isdigit():
74+
return None
75+
parts = file_name[:-3].split('_')
76+
if not parts:
7577
return None
7678
try:
77-
return int(file_name.split('_')[0])
78-
except (ValueError, IndexError):
79+
return int(parts[-1])
80+
except ValueError:
7981
return None
8082

8183

solutions/0001_two_sum.py

Lines changed: 0 additions & 1 deletion
This file was deleted.

solutions/0002_add_two_numbers.py

Lines changed: 0 additions & 1 deletion
This file was deleted.

solutions/__init__.py

Whitespace-only changes.

solutions/two_sum_0001.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
class Solution:
4+
def twoSum(self, nums: List[int], target: int) -> List[int]:
5+
"""Возвращает индексы двух чисел из nums, сумма которых равна target.
6+
Работает за O(n): проходит по списку один раз, запоминая числа
7+
и их позиции в словаре. Для каждого элемента проверяет,
8+
было ли уже число (target - текущее). Если да — возвращает пару индексов.
9+
Гарантируется, что решение существует и уникально.
10+
"""
11+
seen = {}
12+
for index, num in enumerate(nums):
13+
complement = target - num
14+
if complement in seen:
15+
return [seen[complement], index]
16+
seen[num] = index
17+
raise ValueError('Нет решения')

tests/test_two_sum_0001.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from solutions.two_sum_0001 import Solution
2+
3+
def test_two_sum():
4+
sol = Solution()
5+
assert sol.twoSum([2, 7, 11, 15], 9) == [0, 1]
6+
assert sol.twoSum([3, 2, 4], 6) == [1, 2]
7+
assert sol.twoSum([3, 3], 6) == [0, 1]

0 commit comments

Comments
 (0)