Skip to content

Commit e917ae7

Browse files
authored
Merge branch 'master' into add-gosper-curve
2 parents 318f4f3 + 9ea690e commit e917ae7

13 files changed

Lines changed: 66 additions & 48 deletions

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ We want your work to be readable by others; therefore, we encourage you to note
159159
starting_value = int(input("Please enter a starting value: ").strip())
160160
```
161161

162-
The use of [Python type hints](https://docs.python.org/3/library/typing.html) is encouraged for function parameters and return values. Our automated testing will run [mypy](http://mypy-lang.org) so run that locally before making your submission.
162+
The use of [Python type hints](https://docs.python.org/3/library/typing.html) is encouraged for function parameters and return values. Our automated testing will run [mypy](https://mypy-lang.org) so run that locally before making your submission.
163163

164164
```python
165165
def sum_ab(a: int, b: int) -> int:

backtracking/generate_parentheses_iterative.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
def generate_parentheses_iterative(length: int) -> list:
1+
def generate_parentheses_iterative(length: int) -> list[str]:
22
"""
33
Generate all valid combinations of parentheses (Iterative Approach).
44
55
The algorithm works as follows:
66
1. Initialize an empty list to store the combinations.
77
2. Initialize a stack to keep track of partial combinations.
8-
3. Start with empty string and push it onstack along with the counts of '(' and ')'.
8+
3. Start with empty string and push it on stack along with
9+
the counts of '(' and ')'.
910
4. While the stack is not empty:
1011
a. Pop a partial combination and its open and close counts from the stack.
1112
b. If the combination length is equal to 2*length, add it to the result.
@@ -34,8 +35,11 @@ def generate_parentheses_iterative(length: int) -> list:
3435
>>> generate_parentheses_iterative(0)
3536
['']
3637
"""
37-
result = []
38-
stack = []
38+
if length == 0:
39+
return [""]
40+
41+
result: list[str] = []
42+
stack: list[tuple[str, int, int]] = []
3943

4044
# Each element in stack is a tuple (current_combination, open_count, close_count)
4145
stack.append(("", 0, 0))
@@ -45,6 +49,7 @@ def generate_parentheses_iterative(length: int) -> list:
4549

4650
if len(current_combination) == 2 * length:
4751
result.append(current_combination)
52+
continue
4853

4954
if open_count < length:
5055
stack.append((current_combination + "(", open_count + 1, close_count))

maths/fibonacci.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,15 @@ def fib_iterative(n: int) -> list[int]:
9191
def fib_recursive(n: int) -> list[int]:
9292
"""
9393
Calculates the first n (0-indexed) Fibonacci numbers using recursion
94-
>>> fib_iterative(0)
94+
>>> fib_recursive(0)
9595
[0]
96-
>>> fib_iterative(1)
96+
>>> fib_recursive(1)
9797
[0, 1]
98-
>>> fib_iterative(5)
98+
>>> fib_recursive(5)
9999
[0, 1, 1, 2, 3, 5]
100-
>>> fib_iterative(10)
100+
>>> fib_recursive(10)
101101
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
102-
>>> fib_iterative(-1)
102+
>>> fib_recursive(-1)
103103
Traceback (most recent call last):
104104
...
105105
ValueError: n is negative
@@ -119,7 +119,7 @@ def fib_recursive_term(i: int) -> int:
119119
>>> fib_recursive_term(-1)
120120
Traceback (most recent call last):
121121
...
122-
Exception: n is negative
122+
ValueError: n is negative
123123
"""
124124
if i < 0:
125125
raise ValueError("n is negative")
@@ -135,15 +135,15 @@ def fib_recursive_term(i: int) -> int:
135135
def fib_recursive_cached(n: int) -> list[int]:
136136
"""
137137
Calculates the first n (0-indexed) Fibonacci numbers using recursion
138-
>>> fib_iterative(0)
138+
>>> fib_recursive_cached(0)
139139
[0]
140-
>>> fib_iterative(1)
140+
>>> fib_recursive_cached(1)
141141
[0, 1]
142-
>>> fib_iterative(5)
142+
>>> fib_recursive_cached(5)
143143
[0, 1, 1, 2, 3, 5]
144-
>>> fib_iterative(10)
144+
>>> fib_recursive_cached(10)
145145
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
146-
>>> fib_iterative(-1)
146+
>>> fib_recursive_cached(-1)
147147
Traceback (most recent call last):
148148
...
149149
ValueError: n is negative
@@ -176,7 +176,7 @@ def fib_memoization(n: int) -> list[int]:
176176
[0, 1, 1, 2, 3, 5]
177177
>>> fib_memoization(10)
178178
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
179-
>>> fib_iterative(-1)
179+
>>> fib_memoization(-1)
180180
Traceback (most recent call last):
181181
...
182182
ValueError: n is negative

maths/greatest_common_divisor.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ def greatest_common_divisor(a: int, b: int) -> int:
3030
3
3131
>>> greatest_common_divisor(-3, -9)
3232
3
33+
>>> greatest_common_divisor(0, 0)
34+
0
3335
"""
3436
return abs(b) if a == 0 else greatest_common_divisor(b % a, a)
3537

@@ -50,6 +52,8 @@ def gcd_by_iterative(x: int, y: int) -> int:
5052
1
5153
>>> gcd_by_iterative(11, 37)
5254
1
55+
>>> gcd_by_iterative(0, 0)
56+
0
5357
"""
5458
while y: # --> when y=0 then loop will terminate and return x as final GCD.
5559
x, y = y, x % y

maths/matrix_exponentiation.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@
1111

1212

1313
class Matrix:
14-
def __init__(self, arg):
14+
def __init__(self, arg: list[list] | int) -> None:
1515
if isinstance(arg, list): # Initializes a matrix identical to the one provided.
1616
self.t = arg
1717
self.n = len(arg)
1818
else: # Initializes a square matrix of the given size and set values to zero.
1919
self.n = arg
2020
self.t = [[0 for _ in range(self.n)] for _ in range(self.n)]
2121

22-
def __mul__(self, b):
22+
def __mul__(self, b: Matrix) -> Matrix:
2323
matrix = Matrix(self.n)
2424
for i in range(self.n):
2525
for j in range(self.n):
@@ -28,7 +28,7 @@ def __mul__(self, b):
2828
return matrix
2929

3030

31-
def modular_exponentiation(a, b):
31+
def modular_exponentiation(a: Matrix, b: int) -> Matrix:
3232
matrix = Matrix([[1, 0], [0, 1]])
3333
while b > 0:
3434
if b & 1:
@@ -38,7 +38,7 @@ def modular_exponentiation(a, b):
3838
return matrix
3939

4040

41-
def fibonacci_with_matrix_exponentiation(n, f1, f2):
41+
def fibonacci_with_matrix_exponentiation(n: int, f1: int, f2: int) -> int:
4242
"""
4343
Returns the nth number of the Fibonacci sequence that
4444
starts with f1 and f2
@@ -64,7 +64,7 @@ def fibonacci_with_matrix_exponentiation(n, f1, f2):
6464
return f2 * matrix.t[0][0] + f1 * matrix.t[0][1]
6565

6666

67-
def simple_fibonacci(n, f1, f2):
67+
def simple_fibonacci(n: int, f1: int, f2: int) -> int:
6868
"""
6969
Returns the nth number of the Fibonacci sequence that
7070
starts with f1 and f2
@@ -95,7 +95,7 @@ def simple_fibonacci(n, f1, f2):
9595
return f2
9696

9797

98-
def matrix_exponentiation_time():
98+
def matrix_exponentiation_time() -> float:
9999
setup = """
100100
from random import randint
101101
from __main__ import fibonacci_with_matrix_exponentiation
@@ -106,7 +106,7 @@ def matrix_exponentiation_time():
106106
return exec_time
107107

108108

109-
def simple_fibonacci_time():
109+
def simple_fibonacci_time() -> float:
110110
setup = """
111111
from random import randint
112112
from __main__ import simple_fibonacci
@@ -119,7 +119,7 @@ def simple_fibonacci_time():
119119
return exec_time
120120

121121

122-
def main():
122+
def main() -> None:
123123
matrix_exponentiation_time()
124124
simple_fibonacci_time()
125125

maths/modular_division.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,13 @@ def modular_division(a: int, b: int, n: int) -> int:
2828
4
2929
3030
"""
31-
assert n > 1
32-
assert a > 0
33-
assert greatest_common_divisor(a, n) == 1
31+
if n <= 1:
32+
raise ValueError("Modulus n must be greater than 1")
33+
if a <= 0:
34+
raise ValueError("Divisor a must be a positive integer")
35+
if greatest_common_divisor(a, n) != 1:
36+
raise ValueError("a and n must be coprime (gcd(a, n) = 1)")
37+
3438
(_d, _t, s) = extended_gcd(n, a) # Implemented below
3539
x = (b * s) % n
3640
return x

searches/binary_search.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@
1010
python3 binary_search.py
1111
"""
1212

13-
from __future__ import annotations
14-
1513
import bisect
14+
from itertools import pairwise
1615

1716

1817
def bisect_left(
@@ -198,7 +197,7 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
198197
>>> binary_search([0, 5, 7, 10, 15], 6)
199198
-1
200199
"""
201-
if list(sorted_collection) != sorted(sorted_collection):
200+
if any(a > b for a, b in pairwise(sorted_collection)):
202201
raise ValueError("sorted_collection must be sorted in ascending order")
203202
left = 0
204203
right = len(sorted_collection) - 1

searches/linear_search.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
This is pure Python implementation of linear search algorithm
2+
This is a pure Python implementation of the linear search algorithm.
33
44
For doctests run following command:
55
python3 -m doctest -v linear_search.py
@@ -12,8 +12,8 @@
1212
def linear_search(sequence: list, target: int) -> int:
1313
"""A pure Python implementation of a linear search algorithm
1414
15-
:param sequence: a collection with comparable items (as sorted items not required
16-
in Linear Search)
15+
:param sequence: a collection with comparable items (sorting is not required for
16+
linear search)
1717
:param target: item value to search
1818
:return: index of found item or -1 if item is not found
1919

sorts/bogo_sort.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import random
1717

1818

19-
def bogo_sort(collection):
19+
def bogo_sort(collection: list) -> list:
2020
"""Pure implementation of the bogosort algorithm in Python
2121
:param collection: some mutable ordered collection with heterogeneous
2222
comparable items inside
@@ -30,7 +30,7 @@ def bogo_sort(collection):
3030
[-45, -5, -2]
3131
"""
3232

33-
def is_sorted(collection):
33+
def is_sorted(collection: list) -> bool:
3434
for i in range(len(collection) - 1):
3535
if collection[i] > collection[i + 1]:
3636
return False

sorts/bubble_sort.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
66
77
:param collection: some mutable ordered collection with heterogeneous
88
comparable items inside
9-
:return: the same collection ordered by ascending
9+
:return: the same collection ordered in ascending order
1010
1111
Examples:
1212
>>> bubble_sort_iterative([0, 5, 2, 3, 2])
@@ -17,6 +17,12 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
1717
[-45, -5, -2]
1818
>>> bubble_sort_iterative([-23, 0, 6, -4, 34])
1919
[-23, -4, 0, 6, 34]
20+
>>> bubble_sort_iterative([1, 2, 3, 4])
21+
[1, 2, 3, 4]
22+
>>> bubble_sort_iterative([3, 3, 3, 3])
23+
[3, 3, 3, 3]
24+
>>> bubble_sort_iterative([56])
25+
[56]
2026
>>> bubble_sort_iterative([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
2127
True
2228
>>> bubble_sort_iterative([]) == sorted([])

0 commit comments

Comments
 (0)