Skip to content

Commit 2b133a3

Browse files
Merge branch 'master' into odd-even-sort-comparable
2 parents e07503b + f56e349 commit 2b133a3

38 files changed

Lines changed: 955 additions & 185 deletions

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ Comments which are not on the same line as code should appear ___before___ the c
196196
return a + b
197197
```
198198

199-
[Install ty](https://docs.astral.sh/ty/installation/) and then pslease use the command `ty check` to test all files or `ty check path/to/file.py` to test a specific file.
199+
[Install ty](https://docs.astral.sh/ty/installation/) and then please use the command `ty check` to test all files or `ty check path/to/file.py` to test a specific file.
200200

201201
- [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain.
202202

‎backtracking/crossword_puzzle_solver.py‎

Lines changed: 66 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,28 @@ def is_valid(
66
) -> bool:
77
"""
88
Check if a word can be placed at the given position.
9+
A cell is valid if it is empty or already contains the correct letter
10+
(enabling crossing/intersection between words).
911
10-
>>> puzzle = [
11-
... ['', '', '', ''],
12-
... ['', '', '', ''],
13-
... ['', '', '', ''],
14-
... ['', '', '', '']
15-
... ]
12+
>>> puzzle = [['', '', '', ''], ['', '', '', ''],
13+
... ['', '', '', ''], ['', '', '', '']]
1614
>>> is_valid(puzzle, 'word', 0, 0, True)
1715
True
18-
>>> puzzle = [
19-
... ['', '', '', ''],
20-
... ['', '', '', ''],
21-
... ['', '', '', ''],
22-
... ['', '', '', '']
23-
... ]
2416
>>> is_valid(puzzle, 'word', 0, 0, False)
2517
True
18+
>>> puzzle2 = [['w', '', ''], ['o', '', ''], ['r', '', ''], ['d', '', '']]
19+
>>> is_valid(puzzle2, 'word', 0, 0, True)
20+
True
21+
>>> is_valid(puzzle2, 'cat', 0, 0, True)
22+
False
2623
"""
27-
for i in range(len(word)):
28-
if vertical:
29-
if row + i >= len(puzzle) or puzzle[row + i][col] != "":
30-
return False
31-
elif col + i >= len(puzzle[0]) or puzzle[row][col + i] != "":
24+
rows, cols = len(puzzle), len(puzzle[0])
25+
for i, ch in enumerate(word):
26+
r, c = (row + i, col) if vertical else (row, col + i)
27+
if r >= rows or c >= cols:
28+
return False
29+
cell = puzzle[r][c]
30+
if cell not in ("", ch):
3231
return False
3332
return True
3433

@@ -37,95 +36,87 @@ def place_word(
3736
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
3837
) -> None:
3938
"""
40-
Place a word at the given position.
41-
42-
>>> puzzle = [
43-
... ['', '', '', ''],
44-
... ['', '', '', ''],
45-
... ['', '', '', ''],
46-
... ['', '', '', '']
47-
... ]
39+
Place a word at the given position in the puzzle.
40+
41+
>>> puzzle = [['', '', '', ''], ['', '', '', ''],
42+
... ['', '', '', ''], ['', '', '', '']]
4843
>>> place_word(puzzle, 'word', 0, 0, True)
4944
>>> puzzle
5045
[['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']]
5146
"""
52-
for i, char in enumerate(word):
47+
for i, ch in enumerate(word):
5348
if vertical:
54-
puzzle[row + i][col] = char
49+
puzzle[row + i][col] = ch
5550
else:
56-
puzzle[row][col + i] = char
51+
puzzle[row][col + i] = ch
5752

5853

5954
def remove_word(
60-
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
55+
puzzle: list[list[str]],
56+
word: str,
57+
row: int,
58+
col: int,
59+
vertical: bool,
60+
snapshot: list[list[str]],
6161
) -> None:
6262
"""
63-
Remove a word from the given position.
64-
65-
>>> puzzle = [
66-
... ['w', '', '', ''],
67-
... ['o', '', '', ''],
68-
... ['r', '', '', ''],
69-
... ['d', '', '', '']
70-
... ]
71-
>>> remove_word(puzzle, 'word', 0, 0, True)
63+
Remove a word from the puzzle, restoring only cells that were empty
64+
before placement. Cells shared with crossing words are preserved.
65+
66+
>>> puzzle = [['w', 'o', 'r', 'd'], ['', '', '', ''],
67+
... ['', '', '', ''], ['', '', '', '']]
68+
>>> snap = [['', 'o', 'r', 'd'], ['', '', '', ''],
69+
... ['', '', '', ''], ['', '', '', '']]
70+
>>> remove_word(puzzle, 'word', 0, 0, False, snap)
7271
>>> puzzle
73-
[['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]
72+
[['', 'o', 'r', 'd'], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]
7473
"""
7574
for i in range(len(word)):
76-
if vertical:
77-
puzzle[row + i][col] = ""
78-
else:
79-
puzzle[row][col + i] = ""
75+
r, c = (row + i, col) if vertical else (row, col + i)
76+
if snapshot[r][c] == "":
77+
puzzle[r][c] = ""
8078

8179

8280
def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:
8381
"""
8482
Solve the crossword puzzle using backtracking.
83+
Words are tried longest-first to prune the search space early.
84+
Intersections between words (shared letters) are supported.
8585
86-
>>> puzzle = [
87-
... ['', '', '', ''],
88-
... ['', '', '', ''],
89-
... ['', '', '', ''],
90-
... ['', '', '', '']
91-
... ]
92-
93-
>>> words = ['word', 'four', 'more', 'last']
94-
>>> solve_crossword(puzzle, words)
86+
>>> puzzle = [['', '', '', ''], ['', '', '', ''],
87+
... ['', '', '', ''], ['', '', '', '']]
88+
>>> solve_crossword(puzzle, ['word', 'four', 'more', 'last'])
9589
True
96-
>>> puzzle = [
97-
... ['', '', '', ''],
98-
... ['', '', '', ''],
99-
... ['', '', '', ''],
100-
... ['', '', '', '']
101-
... ]
102-
>>> words = ['word', 'four', 'more', 'paragraphs']
103-
>>> solve_crossword(puzzle, words)
90+
>>> puzzle2 = [['', '', '', ''], ['', '', '', ''],
91+
... ['', '', '', ''], ['', '', '', '']]
92+
>>> solve_crossword(puzzle2, ['word', 'four', 'more', 'paragraphs'])
10493
False
10594
"""
95+
if not words:
96+
return True
97+
98+
remaining = sorted(words, key=len, reverse=True)
99+
word, rest = remaining[0], remaining[1:]
100+
106101
for row in range(len(puzzle)):
107102
for col in range(len(puzzle[0])):
108-
if puzzle[row][col] == "":
109-
for word in words:
110-
for vertical in [True, False]:
111-
if is_valid(puzzle, word, row, col, vertical):
112-
place_word(puzzle, word, row, col, vertical)
113-
words.remove(word)
114-
if solve_crossword(puzzle, words):
115-
return True
116-
words.append(word)
117-
remove_word(puzzle, word, row, col, vertical)
118-
return False
119-
return True
103+
for vertical in (True, False):
104+
if is_valid(puzzle, word, row, col, vertical):
105+
snapshot = [r[:] for r in puzzle]
106+
place_word(puzzle, word, row, col, vertical)
107+
if solve_crossword(puzzle, rest):
108+
return True
109+
remove_word(puzzle, word, row, col, vertical, snapshot)
110+
111+
return False
120112

121113

122114
if __name__ == "__main__":
123115
PUZZLE = [[""] * 3 for _ in range(3)]
124116
WORDS = ["cat", "dog", "car"]
125-
126117
if solve_crossword(PUZZLE, WORDS):
127118
print("Solution found:")
128119
for row in PUZZLE:
129-
print(" ".join(row))
120+
print(" ".join(cell or "." for cell in row))
130121
else:
131-
print("No solution found:")
122+
print("No solution found.")

‎bit_manipulation/count_number_of_one_bits.py‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,27 +64,76 @@ def get_set_bits_count_using_modulo_operator(number: int) -> int:
6464
return result
6565

6666

67+
def get_set_bits_count_using_lookup_table(number: int) -> int:
68+
"""
69+
Count the number of set bits in a 32-bit integer using a precomputed lookup table.
70+
71+
I see similar approach in GeeksforGeeks, but the implementation is different.
72+
Link to Code:
73+
https://www.geeksforgeeks.org/dsa/count-set-bits-integer-using-lookup-table/
74+
75+
>>> get_set_bits_count_using_lookup_table(25)
76+
3
77+
>>> get_set_bits_count_using_lookup_table(37)
78+
3
79+
>>> get_set_bits_count_using_lookup_table(21)
80+
3
81+
>>> get_set_bits_count_using_lookup_table(58)
82+
4
83+
>>> get_set_bits_count_using_lookup_table(0)
84+
0
85+
>>> get_set_bits_count_using_lookup_table(256)
86+
1
87+
>>> get_set_bits_count_using_lookup_table(-1)
88+
Traceback (most recent call last):
89+
...
90+
ValueError: the value of input must not be negative
91+
"""
92+
_lookup_table = [bin(i).count("1") for i in range(256)]
93+
94+
if number < 0:
95+
raise ValueError("the value of input must not be negative")
96+
97+
# Split 32-bit number into four 8-bit chunks and use lookup table
98+
return (
99+
_lookup_table[number & 0xFF]
100+
+ _lookup_table[(number >> 8) & 0xFF]
101+
+ _lookup_table[(number >> 16) & 0xFF]
102+
+ _lookup_table[(number >> 24) & 0xFF]
103+
)
104+
105+
67106
def benchmark() -> None:
68107
"""
69-
Benchmark code for comparing 2 functions, with different length int values.
70-
Brian Kernighan's algorithm is consistently faster than using modulo_operator.
108+
Benchmark code for comparing 3 functions, with different length int values.
109+
Brian Kernighan's algorithm is consistently faster than using modulo_operator,
110+
and the lookup table method is often the fastest for repeated calls.
71111
"""
72112

73113
def do_benchmark(number: int) -> None:
74114
setup = "import __main__ as z"
75115
print(f"Benchmark when {number = }:")
116+
76117
print(f"{get_set_bits_count_using_modulo_operator(number) = }")
77118
timing = timeit(
78119
f"z.get_set_bits_count_using_modulo_operator({number})", setup=setup
79120
)
80121
print(f"timeit() runs in {timing} seconds")
122+
81123
print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }")
82124
timing = timeit(
83125
f"z.get_set_bits_count_using_brian_kernighans_algorithm({number})",
84126
setup=setup,
85127
)
86128
print(f"timeit() runs in {timing} seconds")
87129

130+
print(f"{get_set_bits_count_using_lookup_table(number) = }")
131+
timing = timeit(
132+
f"z.get_set_bits_count_using_lookup_table({number})",
133+
setup=setup,
134+
)
135+
print(f"timeit() runs in {timing} seconds")
136+
88137
for number in (25, 37, 58, 0):
89138
do_benchmark(number)
90139
print()

‎blockchain/diophantine_equation.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,64 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
100100
return (d, x, y)
101101

102102

103+
def all_diophantine_solutions(
104+
a: int,
105+
b: int,
106+
c: int,
107+
n: int = 2,
108+
) -> list[tuple[int, int]]:
109+
"""
110+
Return up to `n` integer solutions (x, y) to the linear Diophantine equation
111+
a*x + b*y = c using the extended Euclidean algorithm.
112+
113+
Raises
114+
------
115+
ValueError
116+
If no integer solutions exist.
117+
118+
Time complexity
119+
---------------
120+
O(log(max(|a|, |b|))) to compute a base solution using extended_gcd;
121+
plus O(n) to enumerate `n` solutions.
122+
123+
Space complexity
124+
----------------
125+
O(1) beyond the returned list.
126+
127+
Examples
128+
--------
129+
>>> all_diophantine_solutions(10, 6, 14, n=2)
130+
[(-7, 14), (-4, 9)]
131+
>>> all_diophantine_solutions(10, 6, 14, n=4)
132+
[(-7, 14), (-4, 9), (-1, 4), (2, -1)]
133+
>>> all_diophantine_solutions(3, 6, 10, n=1)
134+
Traceback (most recent call last):
135+
...
136+
ValueError: No integer solutions exist for a=3, b=6, c=10
137+
"""
138+
if a == 0 and b == 0:
139+
if c == 0:
140+
# Infinite solutions; return one canonical solution.
141+
return [(0, 0)][: min(1, n)]
142+
raise ValueError("No integer solutions exist for a=0, b=0, c!=0")
143+
144+
g, xg, yg = extended_gcd(abs(a), abs(b))
145+
if c % g != 0:
146+
msg = f"No integer solutions exist for a={a}, b={b}, c={c}"
147+
raise ValueError(msg)
148+
149+
# Scale a particular solution to ax + by = c
150+
x0, y0 = xg * (c // g), yg * (c // g)
151+
if a < 0:
152+
x0 = -x0
153+
if b < 0:
154+
y0 = -y0
155+
156+
# General solution: x = x0 + t*(b/g), y = y0 - t*(a/g)
157+
dx, dy = b // g, a // g
158+
return [(x0 + t * dx, y0 - t * dy) for t in range(n)]
159+
160+
103161
if __name__ == "__main__":
104162
from doctest import testmod
105163

‎conversions/excel_title_to_column.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,24 @@ def excel_title_to_column(column_title: str) -> int:
1212
28
1313
>>> excel_title_to_column("Z")
1414
26
15+
>>> excel_title_to_column("a")
16+
1
17+
>>> excel_title_to_column("ab")
18+
28
19+
>>> excel_title_to_column("")
20+
Traceback (most recent call last):
21+
...
22+
ValueError: Column title must contain only alphabetic characters.
23+
>>> excel_title_to_column("A1")
24+
Traceback (most recent call last):
25+
...
26+
ValueError: Column title must contain only alphabetic characters.
1527
"""
16-
assert column_title.isupper()
28+
if not column_title or not column_title.isalpha():
29+
msg = "Column title must contain only alphabetic characters."
30+
raise ValueError(msg)
31+
32+
column_title = column_title.upper()
1733
answer = 0
1834
index = len(column_title) - 1
1935
power = 0

0 commit comments

Comments
 (0)