repo_name
stringclasses 1
value | pr_number
int64 4.12k
11.2k
| pr_title
stringlengths 9
107
| pr_description
stringlengths 107
5.48k
| author
stringlengths 4
18
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 118
5.52k
| before_content
stringlengths 0
7.93M
| after_content
stringlengths 0
7.93M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
DIRECTIONS = [
[-1, 0], # left
[0, -1], # down
[1, 0], # right
[0, 1], # up
]
# function to search the path
def search(
grid: list[list[int]],
init: list[int],
goal: list[int],
cost: int,
heuristic: list[list[int]],
) -> tuple[list[list[int]], list[list[int]]]:
closed = [
[0 for col in range(len(grid[0]))] for row in range(len(grid))
] # the reference grid
closed[init[0]][init[1]] = 1
action = [
[0 for col in range(len(grid[0]))] for row in range(len(grid))
] # the action grid
x = init[0]
y = init[1]
g = 0
f = g + heuristic[x][y] # cost from starting cell to destination cell
cell = [[f, g, x, y]]
found = False # flag that is set when search is complete
resign = False # flag set if we can't find expand
while not found and not resign:
if len(cell) == 0:
raise ValueError("Algorithm is unable to find solution")
else: # to choose the least costliest action so as to move closer to the goal
cell.sort()
cell.reverse()
next = cell.pop()
x = next[2]
y = next[3]
g = next[1]
if x == goal[0] and y == goal[1]:
found = True
else:
for i in range(len(DIRECTIONS)): # to try out different valid actions
x2 = x + DIRECTIONS[i][0]
y2 = y + DIRECTIONS[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
f2 = g2 + heuristic[x2][y2]
cell.append([f2, g2, x2, y2])
closed[x2][y2] = 1
action[x2][y2] = i
invpath = []
x = goal[0]
y = goal[1]
invpath.append([x, y]) # we get the reverse path from here
while x != init[0] or y != init[1]:
x2 = x - DIRECTIONS[action[x][y]][0]
y2 = y - DIRECTIONS[action[x][y]][1]
x = x2
y = y2
invpath.append([x, y])
path = []
for i in range(len(invpath)):
path.append(invpath[len(invpath) - 1 - i])
return path, action
if __name__ == "__main__":
grid = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
]
init = [0, 0]
# all coordinates are given in format [y,x]
goal = [len(grid) - 1, len(grid[0]) - 1]
cost = 1
# the cost map which pushes the path closer to the goal
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
if grid[i][j] == 1:
# added extra penalty in the heuristic map
heuristic[i][j] = 99
path, action = search(grid, init, goal, cost, heuristic)
print("ACTION MAP")
for i in range(len(action)):
print(action[i])
for i in range(len(path)):
print(path[i])
| from __future__ import annotations
DIRECTIONS = [
[-1, 0], # left
[0, -1], # down
[1, 0], # right
[0, 1], # up
]
# function to search the path
def search(
grid: list[list[int]],
init: list[int],
goal: list[int],
cost: int,
heuristic: list[list[int]],
) -> tuple[list[list[int]], list[list[int]]]:
closed = [
[0 for col in range(len(grid[0]))] for row in range(len(grid))
] # the reference grid
closed[init[0]][init[1]] = 1
action = [
[0 for col in range(len(grid[0]))] for row in range(len(grid))
] # the action grid
x = init[0]
y = init[1]
g = 0
f = g + heuristic[x][y] # cost from starting cell to destination cell
cell = [[f, g, x, y]]
found = False # flag that is set when search is complete
resign = False # flag set if we can't find expand
while not found and not resign:
if len(cell) == 0:
raise ValueError("Algorithm is unable to find solution")
else: # to choose the least costliest action so as to move closer to the goal
cell.sort()
cell.reverse()
next = cell.pop()
x = next[2]
y = next[3]
g = next[1]
if x == goal[0] and y == goal[1]:
found = True
else:
for i in range(len(DIRECTIONS)): # to try out different valid actions
x2 = x + DIRECTIONS[i][0]
y2 = y + DIRECTIONS[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
f2 = g2 + heuristic[x2][y2]
cell.append([f2, g2, x2, y2])
closed[x2][y2] = 1
action[x2][y2] = i
invpath = []
x = goal[0]
y = goal[1]
invpath.append([x, y]) # we get the reverse path from here
while x != init[0] or y != init[1]:
x2 = x - DIRECTIONS[action[x][y]][0]
y2 = y - DIRECTIONS[action[x][y]][1]
x = x2
y = y2
invpath.append([x, y])
path = []
for i in range(len(invpath)):
path.append(invpath[len(invpath) - 1 - i])
return path, action
if __name__ == "__main__":
grid = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
]
init = [0, 0]
# all coordinates are given in format [y,x]
goal = [len(grid) - 1, len(grid[0]) - 1]
cost = 1
# the cost map which pushes the path closer to the goal
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
if grid[i][j] == 1:
# added extra penalty in the heuristic map
heuristic[i][j] = 99
path, action = search(grid, init, goal, cost, heuristic)
print("ACTION MAP")
for i in range(len(action)):
print(action[i])
for i in range(len(path)):
print(path[i])
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """ A naive recursive implementation of 0-1 Knapsack Problem
https://en.wikipedia.org/wiki/Knapsack_problem
"""
from __future__ import annotations
def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int:
"""
Returns the maximum value that can be put in a knapsack of a capacity cap,
whereby each weight w has a specific value val.
>>> cap = 50
>>> val = [60, 100, 120]
>>> w = [10, 20, 30]
>>> c = len(val)
>>> knapsack(cap, w, val, c)
220
The result is 220 cause the values of 100 and 120 got the weight of 50
which is the limit of the capacity.
"""
# Base Case
if counter == 0 or capacity == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity,
# then this item cannot be included in the optimal solution,
# else return the maximum of two cases:
# (1) nth item included
# (2) not included
if weights[counter - 1] > capacity:
return knapsack(capacity, weights, values, counter - 1)
else:
left_capacity = capacity - weights[counter - 1]
new_value_included = values[counter - 1] + knapsack(
left_capacity, weights, values, counter - 1
)
without_new_value = knapsack(capacity, weights, values, counter - 1)
return max(new_value_included, without_new_value)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """ A naive recursive implementation of 0-1 Knapsack Problem
https://en.wikipedia.org/wiki/Knapsack_problem
"""
from __future__ import annotations
def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int:
"""
Returns the maximum value that can be put in a knapsack of a capacity cap,
whereby each weight w has a specific value val.
>>> cap = 50
>>> val = [60, 100, 120]
>>> w = [10, 20, 30]
>>> c = len(val)
>>> knapsack(cap, w, val, c)
220
The result is 220 cause the values of 100 and 120 got the weight of 50
which is the limit of the capacity.
"""
# Base Case
if counter == 0 or capacity == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity,
# then this item cannot be included in the optimal solution,
# else return the maximum of two cases:
# (1) nth item included
# (2) not included
if weights[counter - 1] > capacity:
return knapsack(capacity, weights, values, counter - 1)
else:
left_capacity = capacity - weights[counter - 1]
new_value_included = values[counter - 1] + knapsack(
left_capacity, weights, values, counter - 1
)
without_new_value = knapsack(capacity, weights, values, counter - 1)
return max(new_value_included, without_new_value)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In the game of darts a player throws three darts at a target board which is
split into twenty equal sized sections numbered one to twenty.

The score of a dart is determined by the number of the region that the dart
lands in. A dart landing outside the red/green outer ring scores zero. The black
and cream regions inside this ring represent single scores. However, the red/green
outer ring and middle ring score double and treble scores respectively.
At the centre of the board are two concentric circles called the bull region, or
bulls-eye. The outer bull is worth 25 points and the inner bull is a double,
worth 50 points.
There are many variations of rules but in the most popular game the players will
begin with a score 301 or 501 and the first player to reduce their running total
to zero is a winner. However, it is normal to play a "doubles out" system, which
means that the player must land a double (including the double bulls-eye at the
centre of the board) on their final dart to win; any other dart that would reduce
their running total to one or lower means the score for that set of three darts
is "bust".
When a player is able to finish on their current score it is called a "checkout"
and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull).
There are exactly eleven distinct ways to checkout on a score of 6:
D3
D1 D2
S2 D2
D2 D1
S4 D1
S1 S1 D2
S1 T1 D1
S1 S3 D1
D1 D1 D1
D1 S2 D1
S2 S2 D1
Note that D1 D2 is considered different to D2 D1 as they finish on different
doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1.
In addition we shall not include misses in considering combinations; for example,
D3 is the same as 0 D3 and 0 0 D3.
Incredibly there are 42336 distinct ways of checking out in total.
How many distinct ways can a player checkout with a score less than 100?
Solution:
We first construct a list of the possible dart values, separated by type.
We then iterate through the doubles, followed by the possible 2 following throws.
If the total of these three darts is less than the given limit, we increment
the counter.
"""
from itertools import combinations_with_replacement
def solution(limit: int = 100) -> int:
"""
Count the number of distinct ways a player can checkout with a score
less than limit.
>>> solution(171)
42336
>>> solution(50)
12577
"""
singles: list[int] = [x for x in range(1, 21)] + [25]
doubles: list[int] = [2 * x for x in range(1, 21)] + [50]
triples: list[int] = [3 * x for x in range(1, 21)]
all_values: list[int] = singles + doubles + triples + [0]
num_checkouts: int = 0
double: int
throw1: int
throw2: int
checkout_total: int
for double in doubles:
for throw1, throw2 in combinations_with_replacement(all_values, 2):
checkout_total = double + throw1 + throw2
if checkout_total < limit:
num_checkouts += 1
return num_checkouts
if __name__ == "__main__":
print(f"{solution() = }")
| """
In the game of darts a player throws three darts at a target board which is
split into twenty equal sized sections numbered one to twenty.

The score of a dart is determined by the number of the region that the dart
lands in. A dart landing outside the red/green outer ring scores zero. The black
and cream regions inside this ring represent single scores. However, the red/green
outer ring and middle ring score double and treble scores respectively.
At the centre of the board are two concentric circles called the bull region, or
bulls-eye. The outer bull is worth 25 points and the inner bull is a double,
worth 50 points.
There are many variations of rules but in the most popular game the players will
begin with a score 301 or 501 and the first player to reduce their running total
to zero is a winner. However, it is normal to play a "doubles out" system, which
means that the player must land a double (including the double bulls-eye at the
centre of the board) on their final dart to win; any other dart that would reduce
their running total to one or lower means the score for that set of three darts
is "bust".
When a player is able to finish on their current score it is called a "checkout"
and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull).
There are exactly eleven distinct ways to checkout on a score of 6:
D3
D1 D2
S2 D2
D2 D1
S4 D1
S1 S1 D2
S1 T1 D1
S1 S3 D1
D1 D1 D1
D1 S2 D1
S2 S2 D1
Note that D1 D2 is considered different to D2 D1 as they finish on different
doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1.
In addition we shall not include misses in considering combinations; for example,
D3 is the same as 0 D3 and 0 0 D3.
Incredibly there are 42336 distinct ways of checking out in total.
How many distinct ways can a player checkout with a score less than 100?
Solution:
We first construct a list of the possible dart values, separated by type.
We then iterate through the doubles, followed by the possible 2 following throws.
If the total of these three darts is less than the given limit, we increment
the counter.
"""
from itertools import combinations_with_replacement
def solution(limit: int = 100) -> int:
"""
Count the number of distinct ways a player can checkout with a score
less than limit.
>>> solution(171)
42336
>>> solution(50)
12577
"""
singles: list[int] = [x for x in range(1, 21)] + [25]
doubles: list[int] = [2 * x for x in range(1, 21)] + [50]
triples: list[int] = [3 * x for x in range(1, 21)]
all_values: list[int] = singles + doubles + triples + [0]
num_checkouts: int = 0
double: int
throw1: int
throw2: int
checkout_total: int
for double in doubles:
for throw1, throw2 in combinations_with_replacement(all_values, 2):
checkout_total = double + throw1 + throw2
if checkout_total < limit:
num_checkouts += 1
return num_checkouts
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # flake8: noqa
"""
This is pure Python implementation of tree traversal algorithms
"""
from __future__ import annotations
import queue
class TreeNode:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def build_tree():
print("\n********Press N to stop entering at any point of time********\n")
check = input("Enter the value of the root node: ").strip().lower() or "n"
if check == "n":
return None
q: queue.Queue = queue.Queue()
tree_node = TreeNode(int(check))
q.put(tree_node)
while not q.empty():
node_found = q.get()
msg = "Enter the left node of %s: " % node_found.data
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
left_node = TreeNode(int(check))
node_found.left = left_node
q.put(left_node)
msg = "Enter the right node of %s: " % node_found.data
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
right_node = TreeNode(int(check))
node_found.right = right_node
q.put(right_node)
def pre_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order(root)
1,2,4,5,3,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
print(node.data, end=",")
pre_order(node.left)
pre_order(node.right)
def in_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order(root)
4,2,5,1,6,3,7,
"""
if not isinstance(node, TreeNode) or not node:
return
in_order(node.left)
print(node.data, end=",")
in_order(node.right)
def post_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order(root)
4,5,2,6,7,3,1,
"""
if not isinstance(node, TreeNode) or not node:
return
post_order(node.left)
post_order(node.right)
print(node.data, end=",")
def level_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order(root)
1,2,3,4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
q.put(node_dequeued.left)
if node_dequeued.right:
q.put(node_dequeued.right)
def level_order_actual(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order_actual(root)
1,
2,3,
4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
list = []
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
list.append(node_dequeued.left)
if node_dequeued.right:
list.append(node_dequeued.right)
print()
for node in list:
q.put(node)
# iteration version
def pre_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order_iter(root)
1,2,4,5,3,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n: # start from root node, find its left child
print(n.data, end=",")
stack.append(n)
n = n.left
# end of while means current node doesn't have left child
n = stack.pop()
# start to traverse its right child
n = n.right
def in_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order_iter(root)
4,2,5,1,6,3,7,
"""
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=",")
n = n.right
def post_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order_iter(root)
4,5,2,6,7,3,1,
"""
if not isinstance(node, TreeNode) or not node:
return
stack1, stack2 = [], []
n = node
stack1.append(n)
while stack1: # to find the reversed order of post order, store it in stack2
n = stack1.pop()
if n.left:
stack1.append(n.left)
if n.right:
stack1.append(n.right)
stack2.append(n)
while stack2: # pop up from stack2 will be the post order
print(stack2.pop().data, end=",")
def prompt(s: str = "", width=50, char="*") -> str:
if not s:
return "\n" + width * char
left, extra = divmod(width - len(s) - 2, 2)
return f"{left * char} {s} {(left + extra) * char}"
if __name__ == "__main__":
import doctest
doctest.testmod()
print(prompt("Binary Tree Traversals"))
node = build_tree()
print(prompt("Pre Order Traversal"))
pre_order(node)
print(prompt() + "\n")
print(prompt("In Order Traversal"))
in_order(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal"))
post_order(node)
print(prompt() + "\n")
print(prompt("Level Order Traversal"))
level_order(node)
print(prompt() + "\n")
print(prompt("Actual Level Order Traversal"))
level_order_actual(node)
print("*" * 50 + "\n")
print(prompt("Pre Order Traversal - Iteration Version"))
pre_order_iter(node)
print(prompt() + "\n")
print(prompt("In Order Traversal - Iteration Version"))
in_order_iter(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal - Iteration Version"))
post_order_iter(node)
print(prompt())
| # flake8: noqa
"""
This is pure Python implementation of tree traversal algorithms
"""
from __future__ import annotations
import queue
class TreeNode:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def build_tree():
print("\n********Press N to stop entering at any point of time********\n")
check = input("Enter the value of the root node: ").strip().lower() or "n"
if check == "n":
return None
q: queue.Queue = queue.Queue()
tree_node = TreeNode(int(check))
q.put(tree_node)
while not q.empty():
node_found = q.get()
msg = "Enter the left node of %s: " % node_found.data
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
left_node = TreeNode(int(check))
node_found.left = left_node
q.put(left_node)
msg = "Enter the right node of %s: " % node_found.data
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
right_node = TreeNode(int(check))
node_found.right = right_node
q.put(right_node)
def pre_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order(root)
1,2,4,5,3,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
print(node.data, end=",")
pre_order(node.left)
pre_order(node.right)
def in_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order(root)
4,2,5,1,6,3,7,
"""
if not isinstance(node, TreeNode) or not node:
return
in_order(node.left)
print(node.data, end=",")
in_order(node.right)
def post_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order(root)
4,5,2,6,7,3,1,
"""
if not isinstance(node, TreeNode) or not node:
return
post_order(node.left)
post_order(node.right)
print(node.data, end=",")
def level_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order(root)
1,2,3,4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
q.put(node_dequeued.left)
if node_dequeued.right:
q.put(node_dequeued.right)
def level_order_actual(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order_actual(root)
1,
2,3,
4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
list = []
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
list.append(node_dequeued.left)
if node_dequeued.right:
list.append(node_dequeued.right)
print()
for node in list:
q.put(node)
# iteration version
def pre_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order_iter(root)
1,2,4,5,3,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n: # start from root node, find its left child
print(n.data, end=",")
stack.append(n)
n = n.left
# end of while means current node doesn't have left child
n = stack.pop()
# start to traverse its right child
n = n.right
def in_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order_iter(root)
4,2,5,1,6,3,7,
"""
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=",")
n = n.right
def post_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order_iter(root)
4,5,2,6,7,3,1,
"""
if not isinstance(node, TreeNode) or not node:
return
stack1, stack2 = [], []
n = node
stack1.append(n)
while stack1: # to find the reversed order of post order, store it in stack2
n = stack1.pop()
if n.left:
stack1.append(n.left)
if n.right:
stack1.append(n.right)
stack2.append(n)
while stack2: # pop up from stack2 will be the post order
print(stack2.pop().data, end=",")
def prompt(s: str = "", width=50, char="*") -> str:
if not s:
return "\n" + width * char
left, extra = divmod(width - len(s) - 2, 2)
return f"{left * char} {s} {(left + extra) * char}"
if __name__ == "__main__":
import doctest
doctest.testmod()
print(prompt("Binary Tree Traversals"))
node = build_tree()
print(prompt("Pre Order Traversal"))
pre_order(node)
print(prompt() + "\n")
print(prompt("In Order Traversal"))
in_order(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal"))
post_order(node)
print(prompt() + "\n")
print(prompt("Level Order Traversal"))
level_order(node)
print(prompt() + "\n")
print(prompt("Actual Level Order Traversal"))
level_order_actual(node)
print("*" * 50 + "\n")
print(prompt("Pre Order Traversal - Iteration Version"))
pre_order_iter(node)
print(prompt() + "\n")
print(prompt("In Order Traversal - Iteration Version"))
in_order_iter(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal - Iteration Version"))
post_order_iter(node)
print(prompt())
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # This theorem states that the number of prime factors of n
# will be approximately log(log(n)) for most natural numbers n
import math
def exactPrimeFactorCount(n):
"""
>>> exactPrimeFactorCount(51242183)
3
"""
count = 0
if n % 2 == 0:
count += 1
while n % 2 == 0:
n = int(n / 2)
# the n input value must be odd so that
# we can skip one element (ie i += 2)
i = 3
while i <= int(math.sqrt(n)):
if n % i == 0:
count += 1
while n % i == 0:
n = int(n / i)
i = i + 2
# this condition checks the prime
# number n is greater than 2
if n > 2:
count += 1
return count
if __name__ == "__main__":
n = 51242183
print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}")
print(f"The value of log(log(n)) is {math.log(math.log(n)):.4f}")
"""
The number of distinct prime factors is/are 3
The value of log(log(n)) is 2.8765
"""
| # This theorem states that the number of prime factors of n
# will be approximately log(log(n)) for most natural numbers n
import math
def exactPrimeFactorCount(n):
"""
>>> exactPrimeFactorCount(51242183)
3
"""
count = 0
if n % 2 == 0:
count += 1
while n % 2 == 0:
n = int(n / 2)
# the n input value must be odd so that
# we can skip one element (ie i += 2)
i = 3
while i <= int(math.sqrt(n)):
if n % i == 0:
count += 1
while n % i == 0:
n = int(n / i)
i = i + 2
# this condition checks the prime
# number n is greater than 2
if n > 2:
count += 1
return count
if __name__ == "__main__":
n = 51242183
print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}")
print(f"The value of log(log(n)) is {math.log(math.log(n)):.4f}")
"""
The number of distinct prime factors is/are 3
The value of log(log(n)) is 2.8765
"""
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import math
from itertools import takewhile
from typing import Iterator
def is_prime(number: int) -> bool:
"""
Returns boolean representing primality of given number num.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
"""
if number % 2 == 0 and number > 2:
return False
return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2))
def prime_generator() -> Iterator[int]:
"""
Generate a list sequence of prime numbers
"""
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
"""
return sum(takewhile(lambda x: x < n, prime_generator()))
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import math
from itertools import takewhile
from typing import Iterator
def is_prime(number: int) -> bool:
"""
Returns boolean representing primality of given number num.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
"""
if number % 2 == 0 and number > 2:
return False
return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2))
def prime_generator() -> Iterator[int]:
"""
Generate a list sequence of prime numbers
"""
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
"""
return sum(takewhile(lambda x: x < n, prime_generator()))
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected])
Requirements:
- numpy
- random
- time
- matplotlib
Python:
- 3.5
Usage:
- $python3 game_o_life <canvas_size:int>
Game-Of-Life Rules:
1.
Any live cell with fewer than two live neighbours
dies, as if caused by under-population.
2.
Any live cell with two or three live neighbours lives
on to the next generation.
3.
Any live cell with more than three live neighbours
dies, as if by over-population.
4.
Any dead cell with exactly three live neighbours be-
comes a live cell, as if by reproduction.
"""
import random
import sys
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
usage_doc = "Usage of script: script_nama <size_of_canvas:int>"
choice = [0] * 100 + [1] * 10
random.shuffle(choice)
def create_canvas(size: int) -> list[list[bool]]:
canvas = [[False for i in range(size)] for j in range(size)]
return canvas
def seed(canvas: list[list[bool]]) -> None:
for i, row in enumerate(canvas):
for j, _ in enumerate(row):
canvas[i][j] = bool(random.getrandbits(1))
def run(canvas: list[list[bool]]) -> list[list[bool]]:
"""This function runs the rules of game through all points, and changes their
status accordingly.(in the same canvas)
@Args:
--
canvas : canvas of population to run the rules on.
@returns:
--
None
"""
current_canvas = np.array(canvas)
next_gen_canvas = np.array(create_canvas(current_canvas.shape[0]))
for r, row in enumerate(current_canvas):
for c, pt in enumerate(row):
# print(r-1,r+2,c-1,c+2)
next_gen_canvas[r][c] = __judge_point(
pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2]
)
current_canvas = next_gen_canvas
del next_gen_canvas # cleaning memory as we move on.
return_canvas: list[list[bool]] = current_canvas.tolist()
return return_canvas
def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool:
dead = 0
alive = 0
# finding dead or alive neighbours count.
for i in neighbours:
for status in i:
if status:
alive += 1
else:
dead += 1
# handling duplicate entry for focus pt.
if pt:
alive -= 1
else:
dead -= 1
# running the rules of game here.
state = pt
if pt:
if alive < 2:
state = False
elif alive == 2 or alive == 3:
state = True
elif alive > 3:
state = False
else:
if alive == 3:
state = True
return state
if __name__ == "__main__":
if len(sys.argv) != 2:
raise Exception(usage_doc)
canvas_size = int(sys.argv[1])
# main working structure of this module.
c = create_canvas(canvas_size)
seed(c)
fig, ax = plt.subplots()
fig.show()
cmap = ListedColormap(["w", "k"])
try:
while True:
c = run(c)
ax.matshow(c, cmap=cmap)
fig.canvas.draw()
ax.cla()
except KeyboardInterrupt:
# do nothing.
pass
| """Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected])
Requirements:
- numpy
- random
- time
- matplotlib
Python:
- 3.5
Usage:
- $python3 game_o_life <canvas_size:int>
Game-Of-Life Rules:
1.
Any live cell with fewer than two live neighbours
dies, as if caused by under-population.
2.
Any live cell with two or three live neighbours lives
on to the next generation.
3.
Any live cell with more than three live neighbours
dies, as if by over-population.
4.
Any dead cell with exactly three live neighbours be-
comes a live cell, as if by reproduction.
"""
import random
import sys
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
usage_doc = "Usage of script: script_nama <size_of_canvas:int>"
choice = [0] * 100 + [1] * 10
random.shuffle(choice)
def create_canvas(size: int) -> list[list[bool]]:
canvas = [[False for i in range(size)] for j in range(size)]
return canvas
def seed(canvas: list[list[bool]]) -> None:
for i, row in enumerate(canvas):
for j, _ in enumerate(row):
canvas[i][j] = bool(random.getrandbits(1))
def run(canvas: list[list[bool]]) -> list[list[bool]]:
"""This function runs the rules of game through all points, and changes their
status accordingly.(in the same canvas)
@Args:
--
canvas : canvas of population to run the rules on.
@returns:
--
None
"""
current_canvas = np.array(canvas)
next_gen_canvas = np.array(create_canvas(current_canvas.shape[0]))
for r, row in enumerate(current_canvas):
for c, pt in enumerate(row):
# print(r-1,r+2,c-1,c+2)
next_gen_canvas[r][c] = __judge_point(
pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2]
)
current_canvas = next_gen_canvas
del next_gen_canvas # cleaning memory as we move on.
return_canvas: list[list[bool]] = current_canvas.tolist()
return return_canvas
def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool:
dead = 0
alive = 0
# finding dead or alive neighbours count.
for i in neighbours:
for status in i:
if status:
alive += 1
else:
dead += 1
# handling duplicate entry for focus pt.
if pt:
alive -= 1
else:
dead -= 1
# running the rules of game here.
state = pt
if pt:
if alive < 2:
state = False
elif alive == 2 or alive == 3:
state = True
elif alive > 3:
state = False
else:
if alive == 3:
state = True
return state
if __name__ == "__main__":
if len(sys.argv) != 2:
raise Exception(usage_doc)
canvas_size = int(sys.argv[1])
# main working structure of this module.
c = create_canvas(canvas_size)
seed(c)
fig, ax = plt.subplots()
fig.show()
cmap = ListedColormap(["w", "k"])
try:
while True:
c = run(c)
ax.matshow(c, cmap=cmap)
fig.canvas.draw()
ax.cla()
except KeyboardInterrupt:
# do nothing.
pass
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # https://en.wikipedia.org/wiki/Lowest_common_ancestor
# https://en.wikipedia.org/wiki/Breadth-first_search
from __future__ import annotations
import queue
def swap(a: int, b: int) -> tuple[int, int]:
"""
Return a tuple (b, a) when given two integers a and b
>>> swap(2,3)
(3, 2)
>>> swap(3,4)
(4, 3)
>>> swap(67, 12)
(12, 67)
"""
a ^= b
b ^= a
a ^= b
return a, b
def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
"""
creating sparse table which saves each nodes 2^i-th parent
"""
j = 1
while (1 << j) < max_node:
for i in range(1, max_node + 1):
parent[j][i] = parent[j - 1][parent[j - 1][i]]
j += 1
return parent
# returns lca of node u,v
def lowest_common_ancestor(
u: int, v: int, level: list[int], parent: list[list[int]]
) -> list[list[int]]:
# u must be deeper in the tree than v
if level[u] < level[v]:
u, v = swap(u, v)
# making depth of u same as depth of v
for i in range(18, -1, -1):
if level[u] - (1 << i) >= level[v]:
u = parent[i][u]
# at the same depth if u==v that mean lca is found
if u == v:
return u
# moving both nodes upwards till lca in found
for i in range(18, -1, -1):
if parent[i][u] != 0 and parent[i][u] != parent[i][v]:
u, v = parent[i][u], parent[i][v]
# returning longest common ancestor of u,v
return parent[0][u]
# runs a breadth first search from root node of the tree
def breadth_first_search(
level: list[int],
parent: list[list[int]],
max_node: int,
graph: dict[int, int],
root=1,
) -> tuple[list[int], list[list[int]]]:
"""
sets every nodes direct parent
parent of root node is set to 0
calculates depth of each node from root node
"""
level[root] = 0
q = queue.Queue(maxsize=max_node)
q.put(root)
while q.qsize() != 0:
u = q.get()
for v in graph[u]:
if level[v] == -1:
level[v] = level[u] + 1
q.put(v)
parent[0][v] = u
return level, parent
def main() -> None:
max_node = 13
# initializing with 0
parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]
# initializing with -1 which means every node is unvisited
level = [-1 for _ in range(max_node + 10)]
graph = {
1: [2, 3, 4],
2: [5],
3: [6, 7],
4: [8],
5: [9, 10],
6: [11],
7: [],
8: [12, 13],
9: [],
10: [],
11: [],
12: [],
13: [],
}
level, parent = breadth_first_search(level, parent, max_node, graph, 1)
parent = create_sparse(max_node, parent)
print("LCA of node 1 and 3 is: ", lowest_common_ancestor(1, 3, level, parent))
print("LCA of node 5 and 6 is: ", lowest_common_ancestor(5, 6, level, parent))
print("LCA of node 7 and 11 is: ", lowest_common_ancestor(7, 11, level, parent))
print("LCA of node 6 and 7 is: ", lowest_common_ancestor(6, 7, level, parent))
print("LCA of node 4 and 12 is: ", lowest_common_ancestor(4, 12, level, parent))
print("LCA of node 8 and 8 is: ", lowest_common_ancestor(8, 8, level, parent))
if __name__ == "__main__":
main()
| # https://en.wikipedia.org/wiki/Lowest_common_ancestor
# https://en.wikipedia.org/wiki/Breadth-first_search
from __future__ import annotations
import queue
def swap(a: int, b: int) -> tuple[int, int]:
"""
Return a tuple (b, a) when given two integers a and b
>>> swap(2,3)
(3, 2)
>>> swap(3,4)
(4, 3)
>>> swap(67, 12)
(12, 67)
"""
a ^= b
b ^= a
a ^= b
return a, b
def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
"""
creating sparse table which saves each nodes 2^i-th parent
"""
j = 1
while (1 << j) < max_node:
for i in range(1, max_node + 1):
parent[j][i] = parent[j - 1][parent[j - 1][i]]
j += 1
return parent
# returns lca of node u,v
def lowest_common_ancestor(
u: int, v: int, level: list[int], parent: list[list[int]]
) -> list[list[int]]:
# u must be deeper in the tree than v
if level[u] < level[v]:
u, v = swap(u, v)
# making depth of u same as depth of v
for i in range(18, -1, -1):
if level[u] - (1 << i) >= level[v]:
u = parent[i][u]
# at the same depth if u==v that mean lca is found
if u == v:
return u
# moving both nodes upwards till lca in found
for i in range(18, -1, -1):
if parent[i][u] != 0 and parent[i][u] != parent[i][v]:
u, v = parent[i][u], parent[i][v]
# returning longest common ancestor of u,v
return parent[0][u]
# runs a breadth first search from root node of the tree
def breadth_first_search(
level: list[int],
parent: list[list[int]],
max_node: int,
graph: dict[int, int],
root=1,
) -> tuple[list[int], list[list[int]]]:
"""
sets every nodes direct parent
parent of root node is set to 0
calculates depth of each node from root node
"""
level[root] = 0
q = queue.Queue(maxsize=max_node)
q.put(root)
while q.qsize() != 0:
u = q.get()
for v in graph[u]:
if level[v] == -1:
level[v] = level[u] + 1
q.put(v)
parent[0][v] = u
return level, parent
def main() -> None:
max_node = 13
# initializing with 0
parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]
# initializing with -1 which means every node is unvisited
level = [-1 for _ in range(max_node + 10)]
graph = {
1: [2, 3, 4],
2: [5],
3: [6, 7],
4: [8],
5: [9, 10],
6: [11],
7: [],
8: [12, 13],
9: [],
10: [],
11: [],
12: [],
13: [],
}
level, parent = breadth_first_search(level, parent, max_node, graph, 1)
parent = create_sparse(max_node, parent)
print("LCA of node 1 and 3 is: ", lowest_common_ancestor(1, 3, level, parent))
print("LCA of node 5 and 6 is: ", lowest_common_ancestor(5, 6, level, parent))
print("LCA of node 7 and 11 is: ", lowest_common_ancestor(7, 11, level, parent))
print("LCA of node 6 and 7 is: ", lowest_common_ancestor(6, 7, level, parent))
print("LCA of node 4 and 12 is: ", lowest_common_ancestor(4, 12, level, parent))
print("LCA of node 8 and 8 is: ", lowest_common_ancestor(8, 8, level, parent))
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 16: https://projecteuler.net/problem=16
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""
def solution(power: int = 1000) -> int:
"""Returns the sum of the digits of the number 2^power.
>>> solution(1000)
1366
>>> solution(50)
76
>>> solution(20)
31
>>> solution(15)
26
"""
num = 2 ** power
string_num = str(num)
list_num = list(string_num)
sum_of_num = 0
for i in list_num:
sum_of_num += int(i)
return sum_of_num
if __name__ == "__main__":
power = int(input("Enter the power of 2: ").strip())
print("2 ^ ", power, " = ", 2 ** power)
result = solution(power)
print("Sum of the digits is: ", result)
| """
Problem 16: https://projecteuler.net/problem=16
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""
def solution(power: int = 1000) -> int:
"""Returns the sum of the digits of the number 2^power.
>>> solution(1000)
1366
>>> solution(50)
76
>>> solution(20)
31
>>> solution(15)
26
"""
num = 2 ** power
string_num = str(num)
list_num = list(string_num)
sum_of_num = 0
for i in list_num:
sum_of_num += int(i)
return sum_of_num
if __name__ == "__main__":
power = int(input("Enter the power of 2: ").strip())
print("2 ^ ", power, " = ", 2 ** power)
result = solution(power)
print("Sum of the digits is: ", result)
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
def find_primitive(n: int) -> int | None:
for r in range(1, n):
li = []
for x in range(n - 1):
val = pow(r, x, n)
if val in li:
break
li.append(val)
else:
return r
return None
if __name__ == "__main__":
q = int(input("Enter a prime number q: "))
a = find_primitive(q)
if a is None:
print(f"Cannot find the primitive for the value: {a!r}")
else:
a_private = int(input("Enter private key of A: "))
a_public = pow(a, a_private, q)
b_private = int(input("Enter private key of B: "))
b_public = pow(a, b_private, q)
a_secret = pow(b_public, a_private, q)
b_secret = pow(a_public, b_private, q)
print("The key value generated by A is: ", a_secret)
print("The key value generated by B is: ", b_secret)
| from __future__ import annotations
def find_primitive(n: int) -> int | None:
for r in range(1, n):
li = []
for x in range(n - 1):
val = pow(r, x, n)
if val in li:
break
li.append(val)
else:
return r
return None
if __name__ == "__main__":
q = int(input("Enter a prime number q: "))
a = find_primitive(q)
if a is None:
print(f"Cannot find the primitive for the value: {a!r}")
else:
a_private = int(input("Enter private key of A: "))
a_public = pow(a, a_private, q)
b_private = int(input("Enter private key of B: "))
b_public = pow(a, b_private, q)
a_secret = pow(b_public, a_private, q)
b_secret = pow(a_public, b_private, q)
print("The key value generated by A is: ", a_secret)
print("The key value generated by B is: ", b_secret)
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import sys
"""
Dynamic Programming
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
"""
def MatrixChainOrder(array):
N = len(array)
Matrix = [[0 for x in range(N)] for x in range(N)]
Sol = [[0 for x in range(N)] for x in range(N)]
for ChainLength in range(2, N):
for a in range(1, N - ChainLength + 1):
b = a + ChainLength - 1
Matrix[a][b] = sys.maxsize
for c in range(a, b):
cost = (
Matrix[a][c] + Matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
if cost < Matrix[a][b]:
Matrix[a][b] = cost
Sol[a][b] = c
return Matrix, Sol
# Print order of matrix with Ai as Matrix
def PrintOptimalSolution(OptimalSolution, i, j):
if i == j:
print("A" + str(i), end=" ")
else:
print("(", end=" ")
PrintOptimalSolution(OptimalSolution, i, OptimalSolution[i][j])
PrintOptimalSolution(OptimalSolution, OptimalSolution[i][j] + 1, j)
print(")", end=" ")
def main():
array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
Matrix, OptimalSolution = MatrixChainOrder(array)
print("No. of Operation required: " + str(Matrix[1][n - 1]))
PrintOptimalSolution(OptimalSolution, 1, n - 1)
if __name__ == "__main__":
main()
| import sys
"""
Dynamic Programming
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
"""
def MatrixChainOrder(array):
N = len(array)
Matrix = [[0 for x in range(N)] for x in range(N)]
Sol = [[0 for x in range(N)] for x in range(N)]
for ChainLength in range(2, N):
for a in range(1, N - ChainLength + 1):
b = a + ChainLength - 1
Matrix[a][b] = sys.maxsize
for c in range(a, b):
cost = (
Matrix[a][c] + Matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
if cost < Matrix[a][b]:
Matrix[a][b] = cost
Sol[a][b] = c
return Matrix, Sol
# Print order of matrix with Ai as Matrix
def PrintOptimalSolution(OptimalSolution, i, j):
if i == j:
print("A" + str(i), end=" ")
else:
print("(", end=" ")
PrintOptimalSolution(OptimalSolution, i, OptimalSolution[i][j])
PrintOptimalSolution(OptimalSolution, OptimalSolution[i][j] + 1, j)
print(")", end=" ")
def main():
array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
Matrix, OptimalSolution = MatrixChainOrder(array)
print("No. of Operation required: " + str(Matrix[1][n - 1]))
PrintOptimalSolution(OptimalSolution, 1, n - 1)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
import os
from typing import Iterator
URL_BASE = "https://github.com/TheAlgorithms/Python/blob/master"
def good_file_paths(top_dir: str = ".") -> Iterator[str]:
for dir_path, dir_names, filenames in os.walk(top_dir):
dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(filename)[1] in (".py", ".ipynb"):
yield os.path.join(dir_path, filename).lstrip("./")
def md_prefix(i):
return f"{i * ' '}*" if i else "\n##"
def print_path(old_path: str, new_path: str) -> str:
old_parts = old_path.split(os.sep)
for i, new_part in enumerate(new_path.split(os.sep)):
if i + 1 > len(old_parts) or old_parts[i] != new_part:
if new_part:
print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
return new_path
def print_directory_md(top_dir: str = ".") -> None:
old_path = ""
for filepath in sorted(good_file_paths(top_dir)):
filepath, filename = os.path.split(filepath)
if filepath != old_path:
old_path = print_path(old_path, filepath)
indent = (filepath.count(os.sep) + 1) if filepath else 0
url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20")
filename = os.path.splitext(filename.replace("_", " ").title())[0]
print(f"{md_prefix(indent)} [{filename}]({url})")
if __name__ == "__main__":
print_directory_md(".")
| #!/usr/bin/env python3
import os
from typing import Iterator
URL_BASE = "https://github.com/TheAlgorithms/Python/blob/master"
def good_file_paths(top_dir: str = ".") -> Iterator[str]:
for dir_path, dir_names, filenames in os.walk(top_dir):
dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(filename)[1] in (".py", ".ipynb"):
yield os.path.join(dir_path, filename).lstrip("./")
def md_prefix(i):
return f"{i * ' '}*" if i else "\n##"
def print_path(old_path: str, new_path: str) -> str:
old_parts = old_path.split(os.sep)
for i, new_part in enumerate(new_path.split(os.sep)):
if i + 1 > len(old_parts) or old_parts[i] != new_part:
if new_part:
print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
return new_path
def print_directory_md(top_dir: str = ".") -> None:
old_path = ""
for filepath in sorted(good_file_paths(top_dir)):
filepath, filename = os.path.split(filepath)
if filepath != old_path:
old_path = print_path(old_path, filepath)
indent = (filepath.count(os.sep) + 1) if filepath else 0
url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20")
filename = os.path.splitext(filename.replace("_", " ").title())[0]
print(f"{md_prefix(indent)} [{filename}]({url})")
if __name__ == "__main__":
print_directory_md(".")
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Python program for Bitonic Sort.
Note that this program works only when size of input is a power of 2.
"""
from __future__ import annotations
def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:
"""Compare the value at given index1 and index2 of the array and swap them as per
the given direction.
The parameter direction indicates the sorting direction, ASCENDING(1) or
DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are
interchanged.
>>> arr = [12, 42, -21, 1]
>>> comp_and_swap(arr, 1, 2, 1)
>>> print(arr)
[12, -21, 42, 1]
>>> comp_and_swap(arr, 1, 2, 0)
>>> print(arr)
[12, 42, -21, 1]
>>> comp_and_swap(arr, 0, 3, 1)
>>> print(arr)
[1, 42, -21, 12]
>>> comp_and_swap(arr, 0, 3, 0)
>>> print(arr)
[12, 42, -21, 1]
"""
if (direction == 1 and array[index1] > array[index2]) or (
direction == 0 and array[index1] < array[index2]
):
array[index1], array[index2] = array[index2], array[index1]
def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:
"""
It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in
descending if direction = 0.
The sequence to be sorted starts at index position low, the parameter length is the
number of elements to be sorted.
>>> arr = [12, 42, -21, 1]
>>> bitonic_merge(arr, 0, 4, 1)
>>> print(arr)
[-21, 1, 12, 42]
>>> bitonic_merge(arr, 0, 4, 0)
>>> print(arr)
[42, 12, 1, -21]
"""
if length > 1:
middle = int(length / 2)
for i in range(low, low + middle):
comp_and_swap(array, i, i + middle, direction)
bitonic_merge(array, low, middle, direction)
bitonic_merge(array, low + middle, middle, direction)
def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:
"""
This function first produces a bitonic sequence by recursively sorting its two
halves in opposite sorting orders, and then calls bitonic_merge to make them in the
same order.
>>> arr = [12, 34, 92, -23, 0, -121, -167, 145]
>>> bitonic_sort(arr, 0, 8, 1)
>>> arr
[-167, -121, -23, 0, 12, 34, 92, 145]
>>> bitonic_sort(arr, 0, 8, 0)
>>> arr
[145, 92, 34, 12, 0, -23, -121, -167]
"""
if length > 1:
middle = int(length / 2)
bitonic_sort(array, low, middle, 1)
bitonic_sort(array, low + middle, middle, 0)
bitonic_merge(array, low, length, direction)
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
bitonic_sort(unsorted, 0, len(unsorted), 1)
print("\nSorted array in ascending order is: ", end="")
print(*unsorted, sep=", ")
bitonic_merge(unsorted, 0, len(unsorted), 0)
print("Sorted array in descending order is: ", end="")
print(*unsorted, sep=", ")
| """
Python program for Bitonic Sort.
Note that this program works only when size of input is a power of 2.
"""
from __future__ import annotations
def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:
"""Compare the value at given index1 and index2 of the array and swap them as per
the given direction.
The parameter direction indicates the sorting direction, ASCENDING(1) or
DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are
interchanged.
>>> arr = [12, 42, -21, 1]
>>> comp_and_swap(arr, 1, 2, 1)
>>> print(arr)
[12, -21, 42, 1]
>>> comp_and_swap(arr, 1, 2, 0)
>>> print(arr)
[12, 42, -21, 1]
>>> comp_and_swap(arr, 0, 3, 1)
>>> print(arr)
[1, 42, -21, 12]
>>> comp_and_swap(arr, 0, 3, 0)
>>> print(arr)
[12, 42, -21, 1]
"""
if (direction == 1 and array[index1] > array[index2]) or (
direction == 0 and array[index1] < array[index2]
):
array[index1], array[index2] = array[index2], array[index1]
def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:
"""
It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in
descending if direction = 0.
The sequence to be sorted starts at index position low, the parameter length is the
number of elements to be sorted.
>>> arr = [12, 42, -21, 1]
>>> bitonic_merge(arr, 0, 4, 1)
>>> print(arr)
[-21, 1, 12, 42]
>>> bitonic_merge(arr, 0, 4, 0)
>>> print(arr)
[42, 12, 1, -21]
"""
if length > 1:
middle = int(length / 2)
for i in range(low, low + middle):
comp_and_swap(array, i, i + middle, direction)
bitonic_merge(array, low, middle, direction)
bitonic_merge(array, low + middle, middle, direction)
def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:
"""
This function first produces a bitonic sequence by recursively sorting its two
halves in opposite sorting orders, and then calls bitonic_merge to make them in the
same order.
>>> arr = [12, 34, 92, -23, 0, -121, -167, 145]
>>> bitonic_sort(arr, 0, 8, 1)
>>> arr
[-167, -121, -23, 0, 12, 34, 92, 145]
>>> bitonic_sort(arr, 0, 8, 0)
>>> arr
[145, 92, 34, 12, 0, -23, -121, -167]
"""
if length > 1:
middle = int(length / 2)
bitonic_sort(array, low, middle, 1)
bitonic_sort(array, low + middle, middle, 0)
bitonic_merge(array, low, length, direction)
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
bitonic_sort(unsorted, 0, len(unsorted), 1)
print("\nSorted array in ascending order is: ", end="")
print(*unsorted, sep=", ")
bitonic_merge(unsorted, 0, len(unsorted), 0)
print("Sorted array in descending order is: ", end="")
print(*unsorted, sep=", ")
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import bs4
import requests
def get_movie_data_from_soup(soup: bs4.element.ResultSet) -> dict[str, str]:
return {
"name": soup.h3.a.text,
"genre": soup.find("span", class_="genre").text.strip(),
"rating": soup.strong.text,
"page_link": f"https://www.imdb.com{soup.a.get('href')}",
}
def get_imdb_top_movies(num_movies: int = 5) -> tuple:
"""Get the top num_movies most highly rated movies from IMDB and
return a tuple of dicts describing each movie's name, genre, rating, and URL.
Args:
num_movies: The number of movies to get. Defaults to 5.
Returns:
A list of tuples containing information about the top n movies.
>>> len(get_imdb_top_movies(5))
5
>>> len(get_imdb_top_movies(-3))
0
>>> len(get_imdb_top_movies(4.99999))
4
"""
num_movies = int(float(num_movies))
if num_movies < 1:
return ()
base_url = (
"https://www.imdb.com/search/title?title_type="
f"feature&sort=num_votes,desc&count={num_movies}"
)
source = bs4.BeautifulSoup(requests.get(base_url).content, "html.parser")
return tuple(
get_movie_data_from_soup(movie)
for movie in source.find_all("div", class_="lister-item mode-advanced")
)
if __name__ == "__main__":
import json
num_movies = int(input("How many movies would you like to see? "))
print(
", ".join(
json.dumps(movie, indent=4) for movie in get_imdb_top_movies(num_movies)
)
)
| import bs4
import requests
def get_movie_data_from_soup(soup: bs4.element.ResultSet) -> dict[str, str]:
return {
"name": soup.h3.a.text,
"genre": soup.find("span", class_="genre").text.strip(),
"rating": soup.strong.text,
"page_link": f"https://www.imdb.com{soup.a.get('href')}",
}
def get_imdb_top_movies(num_movies: int = 5) -> tuple:
"""Get the top num_movies most highly rated movies from IMDB and
return a tuple of dicts describing each movie's name, genre, rating, and URL.
Args:
num_movies: The number of movies to get. Defaults to 5.
Returns:
A list of tuples containing information about the top n movies.
>>> len(get_imdb_top_movies(5))
5
>>> len(get_imdb_top_movies(-3))
0
>>> len(get_imdb_top_movies(4.99999))
4
"""
num_movies = int(float(num_movies))
if num_movies < 1:
return ()
base_url = (
"https://www.imdb.com/search/title?title_type="
f"feature&sort=num_votes,desc&count={num_movies}"
)
source = bs4.BeautifulSoup(requests.get(base_url).content, "html.parser")
return tuple(
get_movie_data_from_soup(movie)
for movie in source.find_all("div", class_="lister-item mode-advanced")
)
if __name__ == "__main__":
import json
num_movies = int(input("How many movies would you like to see? "))
print(
", ".join(
json.dumps(movie, indent=4) for movie in get_imdb_top_movies(num_movies)
)
)
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a pure Python implementation of the bogosort algorithm,
also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
Bogosort generates random permutations until it guesses the correct one.
More info on: https://en.wikipedia.org/wiki/Bogosort
For doctests run following command:
python -m doctest -v bogo_sort.py
or
python3 -m doctest -v bogo_sort.py
For manual testing run:
python bogo_sort.py
"""
import random
def bogo_sort(collection):
"""Pure implementation of the bogosort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bogo_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bogo_sort([])
[]
>>> bogo_sort([-2, -5, -45])
[-45, -5, -2]
"""
def is_sorted(collection):
if len(collection) < 2:
return True
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
return False
return True
while not is_sorted(collection):
random.shuffle(collection)
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(bogo_sort(unsorted))
| """
This is a pure Python implementation of the bogosort algorithm,
also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
Bogosort generates random permutations until it guesses the correct one.
More info on: https://en.wikipedia.org/wiki/Bogosort
For doctests run following command:
python -m doctest -v bogo_sort.py
or
python3 -m doctest -v bogo_sort.py
For manual testing run:
python bogo_sort.py
"""
import random
def bogo_sort(collection):
"""Pure implementation of the bogosort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bogo_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bogo_sort([])
[]
>>> bogo_sort([-2, -5, -45])
[-45, -5, -2]
"""
def is_sorted(collection):
if len(collection) < 2:
return True
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
return False
return True
while not is_sorted(collection):
random.shuffle(collection)
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(bogo_sort(unsorted))
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #
| #
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Python program to implement Pigeonhole Sorting in python
# Algorithm for the pigeonhole sorting
def pigeonhole_sort(a):
"""
>>> a = [8, 3, 2, 7, 4, 6, 8]
>>> b = sorted(a) # a nondestructive sort
>>> pigeonhole_sort(a) # a destructive sort
>>> a == b
True
"""
# size of range of values in the list (ie, number of pigeonholes we need)
min_val = min(a) # min() finds the minimum value
max_val = max(a) # max() finds the maximum value
size = max_val - min_val + 1 # size is difference of max and min values plus one
# list of pigeonholes of size equal to the variable size
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert isinstance(x, int), "integers only please"
holes[x - min_val] += 1
# Putting the elements back into the array in an order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + min_val
i += 1
def main():
a = [8, 3, 2, 7, 4, 6, 8]
pigeonhole_sort(a)
print("Sorted order is:", " ".join(a))
if __name__ == "__main__":
main()
| # Python program to implement Pigeonhole Sorting in python
# Algorithm for the pigeonhole sorting
def pigeonhole_sort(a):
"""
>>> a = [8, 3, 2, 7, 4, 6, 8]
>>> b = sorted(a) # a nondestructive sort
>>> pigeonhole_sort(a) # a destructive sort
>>> a == b
True
"""
# size of range of values in the list (ie, number of pigeonholes we need)
min_val = min(a) # min() finds the minimum value
max_val = max(a) # max() finds the maximum value
size = max_val - min_val + 1 # size is difference of max and min values plus one
# list of pigeonholes of size equal to the variable size
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert isinstance(x, int), "integers only please"
holes[x - min_val] += 1
# Putting the elements back into the array in an order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + min_val
i += 1
def main():
a = [8, 3, 2, 7, 4, 6, 8]
pigeonhole_sort(a)
print("Sorted order is:", " ".join(a))
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def points_to_polynomial(coordinates: list[list[int]]) -> str:
"""
coordinates is a two dimensional matrix: [[x, y], [x, y], ...]
number of points you want to use
>>> print(points_to_polynomial([]))
The program cannot work out a fitting polynomial.
>>> print(points_to_polynomial([[]]))
The program cannot work out a fitting polynomial.
>>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))
f(x)=x^2*0.0+x^1*-0.0+x^0*0.0
>>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))
f(x)=x^2*0.0+x^1*-0.0+x^0*1.0
>>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))
f(x)=x^2*0.0+x^1*-0.0+x^0*3.0
>>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))
f(x)=x^2*0.0+x^1*1.0+x^0*0.0
>>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))
f(x)=x^2*1.0+x^1*-0.0+x^0*0.0
>>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
f(x)=x^2*1.0+x^1*-0.0+x^0*2.0
>>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0
>>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
f(x)=x^2*5.0+x^1*-18.0+x^0*18.0
"""
try:
check = 1
more_check = 0
d = coordinates[0][0]
for j in range(len(coordinates)):
if j == 0:
continue
if d == coordinates[j][0]:
more_check += 1
solved = "x=" + str(coordinates[j][0])
if more_check == len(coordinates) - 1:
check = 2
break
elif more_check > 0 and more_check != len(coordinates) - 1:
check = 3
else:
check = 1
if len(coordinates) == 1 and coordinates[0][0] == 0:
check = 2
solved = "x=0"
except Exception:
check = 3
x = len(coordinates)
if check == 1:
count_of_line = 0
matrix: list[list[float]] = []
# put the x and x to the power values in a matrix
while count_of_line < x:
count_in_line = 0
a = coordinates[count_of_line][0]
count_line: list[float] = []
while count_in_line < x:
count_line.append(a ** (x - (count_in_line + 1)))
count_in_line += 1
matrix.append(count_line)
count_of_line += 1
count_of_line = 0
# put the y values into a vector
vector: list[float] = []
while count_of_line < x:
vector.append(coordinates[count_of_line][1])
count_of_line += 1
count = 0
while count < x:
zahlen = 0
while zahlen < x:
if count == zahlen:
zahlen += 1
if zahlen == x:
break
bruch = matrix[zahlen][count] / matrix[count][count]
for counting_columns, item in enumerate(matrix[count]):
# manipulating all the values in the matrix
matrix[zahlen][counting_columns] -= item * bruch
# manipulating the values in the vector
vector[zahlen] -= vector[count] * bruch
zahlen += 1
count += 1
count = 0
# make solutions
solution: list[str] = []
while count < x:
solution.append(str(vector[count] / matrix[count][count]))
count += 1
count = 0
solved = "f(x)="
while count < x:
remove_e: list[str] = solution[count].split("E")
if len(remove_e) > 1:
solution[count] = remove_e[0] + "*10^" + remove_e[1]
solved += "x^" + str(x - (count + 1)) + "*" + str(solution[count])
if count + 1 != x:
solved += "+"
count += 1
return solved
elif check == 2:
return solved
else:
return "The program cannot work out a fitting polynomial."
if __name__ == "__main__":
print(points_to_polynomial([]))
print(points_to_polynomial([[]]))
print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))
print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))
print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))
print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))
print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))
print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
| def points_to_polynomial(coordinates: list[list[int]]) -> str:
"""
coordinates is a two dimensional matrix: [[x, y], [x, y], ...]
number of points you want to use
>>> print(points_to_polynomial([]))
The program cannot work out a fitting polynomial.
>>> print(points_to_polynomial([[]]))
The program cannot work out a fitting polynomial.
>>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))
f(x)=x^2*0.0+x^1*-0.0+x^0*0.0
>>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))
f(x)=x^2*0.0+x^1*-0.0+x^0*1.0
>>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))
f(x)=x^2*0.0+x^1*-0.0+x^0*3.0
>>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))
f(x)=x^2*0.0+x^1*1.0+x^0*0.0
>>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))
f(x)=x^2*1.0+x^1*-0.0+x^0*0.0
>>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
f(x)=x^2*1.0+x^1*-0.0+x^0*2.0
>>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0
>>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
f(x)=x^2*5.0+x^1*-18.0+x^0*18.0
"""
try:
check = 1
more_check = 0
d = coordinates[0][0]
for j in range(len(coordinates)):
if j == 0:
continue
if d == coordinates[j][0]:
more_check += 1
solved = "x=" + str(coordinates[j][0])
if more_check == len(coordinates) - 1:
check = 2
break
elif more_check > 0 and more_check != len(coordinates) - 1:
check = 3
else:
check = 1
if len(coordinates) == 1 and coordinates[0][0] == 0:
check = 2
solved = "x=0"
except Exception:
check = 3
x = len(coordinates)
if check == 1:
count_of_line = 0
matrix: list[list[float]] = []
# put the x and x to the power values in a matrix
while count_of_line < x:
count_in_line = 0
a = coordinates[count_of_line][0]
count_line: list[float] = []
while count_in_line < x:
count_line.append(a ** (x - (count_in_line + 1)))
count_in_line += 1
matrix.append(count_line)
count_of_line += 1
count_of_line = 0
# put the y values into a vector
vector: list[float] = []
while count_of_line < x:
vector.append(coordinates[count_of_line][1])
count_of_line += 1
count = 0
while count < x:
zahlen = 0
while zahlen < x:
if count == zahlen:
zahlen += 1
if zahlen == x:
break
bruch = matrix[zahlen][count] / matrix[count][count]
for counting_columns, item in enumerate(matrix[count]):
# manipulating all the values in the matrix
matrix[zahlen][counting_columns] -= item * bruch
# manipulating the values in the vector
vector[zahlen] -= vector[count] * bruch
zahlen += 1
count += 1
count = 0
# make solutions
solution: list[str] = []
while count < x:
solution.append(str(vector[count] / matrix[count][count]))
count += 1
count = 0
solved = "f(x)="
while count < x:
remove_e: list[str] = solution[count].split("E")
if len(remove_e) > 1:
solution[count] = remove_e[0] + "*10^" + remove_e[1]
solved += "x^" + str(x - (count + 1)) + "*" + str(solution[count])
if count + 1 != x:
solved += "+"
count += 1
return solved
elif check == 2:
return solved
else:
return "The program cannot work out a fitting polynomial."
if __name__ == "__main__":
print(points_to_polynomial([]))
print(points_to_polynomial([[]]))
print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))
print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))
print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))
print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))
print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))
print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Program to join a list of strings with a given separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings to be joined
"""
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator)
if __name__ == "__main__":
from doctest import testmod
testmod()
| """
Program to join a list of strings with a given separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings to be joined
"""
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator)
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
import sys
class Letter:
def __init__(self, letter: str, freq: int):
self.letter: str = letter
self.freq: int = freq
self.bitstring: dict[str, str] = {}
def __repr__(self) -> str:
return f"{self.letter}:{self.freq}"
class TreeNode:
def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):
self.freq: int = freq
self.left: Letter | TreeNode = left
self.right: Letter | TreeNode = right
def parse_file(file_path: str) -> list[Letter]:
"""
Read the file and build a dict of all letters and their
frequencies, then convert the dict into a list of Letters.
"""
chars: dict[str, int] = {}
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
chars[c] = chars[c] + 1 if c in chars.keys() else 1
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)
def build_tree(letters: list[Letter]) -> Letter | TreeNode:
"""
Run through the list of Letters and build the min heap
for the Huffman Tree.
"""
response: list[Letter | TreeNode] = letters # type: ignore
while len(response) > 1:
left = response.pop(0)
right = response.pop(0)
total_freq = left.freq + right.freq
node = TreeNode(total_freq, left, right)
response.append(node)
response.sort(key=lambda l: l.freq)
return response[0]
def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:
"""
Recursively traverse the Huffman Tree to set each
Letter's bitstring dictionary, and return the list of Letters
"""
if type(root) is Letter:
root.bitstring[root.letter] = bitstring
return [root]
treenode: TreeNode = root # type: ignore
letters = []
letters += traverse_tree(treenode.left, bitstring + "0")
letters += traverse_tree(treenode.right, bitstring + "1")
return letters
def huffman(file_path: str) -> None:
"""
Parse the file, build the tree, then run through the file
again, using the letters dictionary to find and print out the
bitstring for each letter.
"""
letters_list = parse_file(file_path)
root = build_tree(letters_list)
letters = {
k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items()
}
print(f"Huffman Coding of {file_path}: ")
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
print(letters[c], end=" ")
print()
if __name__ == "__main__":
# pass the file path to the huffman function
huffman(sys.argv[1])
| from __future__ import annotations
import sys
class Letter:
def __init__(self, letter: str, freq: int):
self.letter: str = letter
self.freq: int = freq
self.bitstring: dict[str, str] = {}
def __repr__(self) -> str:
return f"{self.letter}:{self.freq}"
class TreeNode:
def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):
self.freq: int = freq
self.left: Letter | TreeNode = left
self.right: Letter | TreeNode = right
def parse_file(file_path: str) -> list[Letter]:
"""
Read the file and build a dict of all letters and their
frequencies, then convert the dict into a list of Letters.
"""
chars: dict[str, int] = {}
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
chars[c] = chars[c] + 1 if c in chars.keys() else 1
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)
def build_tree(letters: list[Letter]) -> Letter | TreeNode:
"""
Run through the list of Letters and build the min heap
for the Huffman Tree.
"""
response: list[Letter | TreeNode] = letters # type: ignore
while len(response) > 1:
left = response.pop(0)
right = response.pop(0)
total_freq = left.freq + right.freq
node = TreeNode(total_freq, left, right)
response.append(node)
response.sort(key=lambda l: l.freq)
return response[0]
def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:
"""
Recursively traverse the Huffman Tree to set each
Letter's bitstring dictionary, and return the list of Letters
"""
if type(root) is Letter:
root.bitstring[root.letter] = bitstring
return [root]
treenode: TreeNode = root # type: ignore
letters = []
letters += traverse_tree(treenode.left, bitstring + "0")
letters += traverse_tree(treenode.right, bitstring + "1")
return letters
def huffman(file_path: str) -> None:
"""
Parse the file, build the tree, then run through the file
again, using the letters dictionary to find and print out the
bitstring for each letter.
"""
letters_list = parse_file(file_path)
root = build_tree(letters_list)
letters = {
k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items()
}
print(f"Huffman Coding of {file_path}: ")
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
print(letters[c], end=" ")
print()
if __name__ == "__main__":
# pass the file path to the huffman function
huffman(sys.argv[1])
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a pure Python implementation of the selection sort algorithm
For doctests run following command:
python -m doctest -v selection_sort.py
or
python3 -m doctest -v selection_sort.py
For manual testing run:
python selection_sort.py
"""
def selection_sort(collection):
"""Pure implementation of the selection sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> selection_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> selection_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if collection[k] < collection[least]:
least = k
if least != i:
collection[least], collection[i] = (collection[i], collection[least])
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(selection_sort(unsorted))
| """
This is a pure Python implementation of the selection sort algorithm
For doctests run following command:
python -m doctest -v selection_sort.py
or
python3 -m doctest -v selection_sort.py
For manual testing run:
python selection_sort.py
"""
def selection_sort(collection):
"""Pure implementation of the selection sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> selection_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> selection_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if collection[k] < collection[least]:
least = k
if least != i:
collection[least], collection[i] = (collection[i], collection[least])
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(selection_sort(unsorted))
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Uses Pythagoras theorem to calculate the distance between two points in space."""
import math
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self) -> str:
return f"Point({self.x}, {self.y}, {self.z})"
def distance(a: Point, b: Point) -> float:
return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2))
def test_distance() -> None:
"""
>>> point1 = Point(2, -1, 7)
>>> point2 = Point(1, -3, 5)
>>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}")
Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| """Uses Pythagoras theorem to calculate the distance between two points in space."""
import math
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self) -> str:
return f"Point({self.x}, {self.y}, {self.z})"
def distance(a: Point, b: Point) -> float:
return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2))
def test_distance() -> None:
"""
>>> point1 = Point(2, -1, 7)
>>> point2 = Point(1, -3, 5)
>>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}")
Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
from cmath import sqrt
def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:
"""
Given the numerical coefficients a, b and c,
calculates the roots for any quadratic equation of the form ax^2 + bx + c
>>> quadratic_roots(a=1, b=3, c=-4)
(1.0, -4.0)
>>> quadratic_roots(5, 6, 1)
(-0.2, -1.0)
>>> quadratic_roots(1, -6, 25)
((3+4j), (3-4j))
"""
if a == 0:
raise ValueError("Coefficient 'a' must not be zero.")
delta = b * b - 4 * a * c
root_1 = (-b + sqrt(delta)) / (2 * a)
root_2 = (-b - sqrt(delta)) / (2 * a)
return (
root_1.real if not root_1.imag else root_1,
root_2.real if not root_2.imag else root_2,
)
def main():
solution1, solution2 = quadratic_roots(a=5, b=6, c=1)
print(f"The solutions are: {solution1} and {solution2}")
if __name__ == "__main__":
main()
| from __future__ import annotations
from cmath import sqrt
def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:
"""
Given the numerical coefficients a, b and c,
calculates the roots for any quadratic equation of the form ax^2 + bx + c
>>> quadratic_roots(a=1, b=3, c=-4)
(1.0, -4.0)
>>> quadratic_roots(5, 6, 1)
(-0.2, -1.0)
>>> quadratic_roots(1, -6, 25)
((3+4j), (3-4j))
"""
if a == 0:
raise ValueError("Coefficient 'a' must not be zero.")
delta = b * b - 4 * a * c
root_1 = (-b + sqrt(delta)) / (2 * a)
root_2 = (-b - sqrt(delta)) / (2 * a)
return (
root_1.real if not root_1.imag else root_1,
root_2.real if not root_2.imag else root_2,
)
def main():
solution1, solution2 = quadratic_roots(a=5, b=6, c=1)
print(f"The solutions are: {solution1} and {solution2}")
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Program to check if a cycle is present in a given graph
"""
def check_cycle(graph: dict) -> bool:
"""
Returns True if graph is cyclic else False
>>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]})
False
>>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]})
True
"""
# Keep track of visited nodes
visited = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
rec_stk = set()
for node in graph:
if node not in visited:
if depth_first_search(graph, node, visited, rec_stk):
return True
return False
def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:
"""
Recur for all neighbours.
If any neighbour is visited and in rec_stk then graph is cyclic.
>>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}
>>> vertex, visited, rec_stk = 0, set(), set()
>>> depth_first_search(graph, vertex, visited, rec_stk)
False
"""
# Mark current node as visited and add to recursion stack
visited.add(vertex)
rec_stk.add(vertex)
for node in graph[vertex]:
if node not in visited:
if depth_first_search(graph, node, visited, rec_stk):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(vertex)
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| """
Program to check if a cycle is present in a given graph
"""
def check_cycle(graph: dict) -> bool:
"""
Returns True if graph is cyclic else False
>>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]})
False
>>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]})
True
"""
# Keep track of visited nodes
visited = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
rec_stk = set()
for node in graph:
if node not in visited:
if depth_first_search(graph, node, visited, rec_stk):
return True
return False
def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:
"""
Recur for all neighbours.
If any neighbour is visited and in rec_stk then graph is cyclic.
>>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}
>>> vertex, visited, rec_stk = 0, set(), set()
>>> depth_first_search(graph, vertex, visited, rec_stk)
False
"""
# Mark current node as visited and add to recursion stack
visited.add(vertex)
rec_stk.add(vertex)
for node in graph[vertex]:
if node not in visited:
if depth_first_search(graph, node, visited, rec_stk):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(vertex)
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Print all subset combinations of n element in given set of r element.
def combination_util(arr, n, r, index, data, i):
"""
Current combination is ready to be printed, print it
arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed
"""
if index == r:
for j in range(r):
print(data[j], end=" ")
print(" ")
return
# When no more elements are there to put in data[]
if i >= n:
return
# current is included, put next at next location
data[index] = arr[i]
combination_util(arr, n, r, index + 1, data, i + 1)
# current is excluded, replace it with
# next (Note that i+1 is passed, but
# index is not changed)
combination_util(arr, n, r, index, data, i + 1)
# The main function that prints all combinations
# of size r in arr[] of size n. This function
# mainly uses combinationUtil()
def print_combination(arr, n, r):
# A temporary array to store all combination one by one
data = [0] * r
# Print all combination using temporary array 'data[]'
combination_util(arr, n, r, 0, data, 0)
# Driver function to check for above function
arr = [10, 20, 30, 40, 50]
print_combination(arr, len(arr), 3)
# This code is contributed by Ambuj sahu
| # Print all subset combinations of n element in given set of r element.
def combination_util(arr, n, r, index, data, i):
"""
Current combination is ready to be printed, print it
arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed
"""
if index == r:
for j in range(r):
print(data[j], end=" ")
print(" ")
return
# When no more elements are there to put in data[]
if i >= n:
return
# current is included, put next at next location
data[index] = arr[i]
combination_util(arr, n, r, index + 1, data, i + 1)
# current is excluded, replace it with
# next (Note that i+1 is passed, but
# index is not changed)
combination_util(arr, n, r, index, data, i + 1)
# The main function that prints all combinations
# of size r in arr[] of size n. This function
# mainly uses combinationUtil()
def print_combination(arr, n, r):
# A temporary array to store all combination one by one
data = [0] * r
# Print all combination using temporary array 'data[]'
combination_util(arr, n, r, 0, data, 0)
# Driver function to check for above function
arr = [10, 20, 30, 40, 50]
print_combination(arr, len(arr), 3)
# This code is contributed by Ambuj sahu
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In a multi-threaded download, this algorithm could be used to provide
each worker thread with a block of non-overlapping bytes to download.
For example:
for i in allocation_list:
requests.get(url,headers={'Range':f'bytes={i}'})
"""
from __future__ import annotations
def allocation_num(number_of_bytes: int, partitions: int) -> list[str]:
"""
Divide a number of bytes into x partitions.
:param number_of_bytes: the total of bytes.
:param partitions: the number of partition need to be allocated.
:return: list of bytes to be assigned to each worker thread
>>> allocation_num(16647, 4)
['1-4161', '4162-8322', '8323-12483', '12484-16647']
>>> allocation_num(50000, 5)
['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000']
>>> allocation_num(888, 999)
Traceback (most recent call last):
...
ValueError: partitions can not > number_of_bytes!
>>> allocation_num(888, -4)
Traceback (most recent call last):
...
ValueError: partitions must be a positive number!
"""
if partitions <= 0:
raise ValueError("partitions must be a positive number!")
if partitions > number_of_bytes:
raise ValueError("partitions can not > number_of_bytes!")
bytes_per_partition = number_of_bytes // partitions
allocation_list = []
for i in range(partitions):
start_bytes = i * bytes_per_partition + 1
end_bytes = (
number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
)
allocation_list.append(f"{start_bytes}-{end_bytes}")
return allocation_list
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
In a multi-threaded download, this algorithm could be used to provide
each worker thread with a block of non-overlapping bytes to download.
For example:
for i in allocation_list:
requests.get(url,headers={'Range':f'bytes={i}'})
"""
from __future__ import annotations
def allocation_num(number_of_bytes: int, partitions: int) -> list[str]:
"""
Divide a number of bytes into x partitions.
:param number_of_bytes: the total of bytes.
:param partitions: the number of partition need to be allocated.
:return: list of bytes to be assigned to each worker thread
>>> allocation_num(16647, 4)
['1-4161', '4162-8322', '8323-12483', '12484-16647']
>>> allocation_num(50000, 5)
['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000']
>>> allocation_num(888, 999)
Traceback (most recent call last):
...
ValueError: partitions can not > number_of_bytes!
>>> allocation_num(888, -4)
Traceback (most recent call last):
...
ValueError: partitions must be a positive number!
"""
if partitions <= 0:
raise ValueError("partitions must be a positive number!")
if partitions > number_of_bytes:
raise ValueError("partitions can not > number_of_bytes!")
bytes_per_partition = number_of_bytes // partitions
allocation_list = []
for i in range(partitions):
start_bytes = i * bytes_per_partition + 1
end_bytes = (
number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
)
allocation_list.append(f"{start_bytes}-{end_bytes}")
return allocation_list
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git merge" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message to
# stderr if it wants to stop the merge commit.
#
# To enable this hook, rename this file to "pre-merge-commit".
. git-sh-setup
test -x "$GIT_DIR/hooks/pre-commit" &&
exec "$GIT_DIR/hooks/pre-commit"
:
| #!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git merge" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message to
# stderr if it wants to stop the merge commit.
#
# To enable this hook, rename this file to "pre-merge-commit".
. git-sh-setup
test -x "$GIT_DIR/hooks/pre-commit" &&
exec "$GIT_DIR/hooks/pre-commit"
:
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #
| #
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def reverse_words(input_str: str) -> str:
"""
Reverses words in a given string
>>> reverse_words("I love Python")
'Python love I'
>>> reverse_words("I Love Python")
'Python Love I'
"""
return " ".join(input_str.split()[::-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
| def reverse_words(input_str: str) -> str:
"""
Reverses words in a given string
>>> reverse_words("I love Python")
'Python love I'
>>> reverse_words("I Love Python")
'Python Love I'
"""
return " ".join(input_str.split()[::-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Chinese Remainder Theorem:
GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )
If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b
there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are
two such integers, then n1=n2(mod ab)
Algorithm :
1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1
2. Take n = ra*by + rb*ax
"""
from __future__ import annotations
# Extended Euclid
def extended_euclid(a: int, b: int) -> tuple[int, int]:
"""
>>> extended_euclid(10, 6)
(-1, 2)
>>> extended_euclid(7, 5)
(-2, 3)
"""
if b == 0:
return (1, 0)
(x, y) = extended_euclid(b, a % b)
k = a // b
return (y, x - k * y)
# Uses ExtendedEuclid to find inverses
def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int:
"""
>>> chinese_remainder_theorem(5,1,7,3)
31
Explanation : 31 is the smallest number such that
(i) When we divide it by 5, we get remainder 1
(ii) When we divide it by 7, we get remainder 3
>>> chinese_remainder_theorem(6,1,4,3)
14
"""
(x, y) = extended_euclid(n1, n2)
m = n1 * n2
n = r2 * x * n1 + r1 * y * n2
return (n % m + m) % m
# ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid----------------
# This function find the inverses of a i.e., a^(-1)
def invert_modulo(a: int, n: int) -> int:
"""
>>> invert_modulo(2, 5)
3
>>> invert_modulo(8,7)
1
"""
(b, x) = extended_euclid(a, n)
if b < 0:
b = (b % n + n) % n
return b
# Same a above using InvertingModulo
def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int:
"""
>>> chinese_remainder_theorem2(5,1,7,3)
31
>>> chinese_remainder_theorem2(6,1,4,3)
14
"""
x, y = invert_modulo(n1, n2), invert_modulo(n2, n1)
m = n1 * n2
n = r2 * x * n1 + r1 * y * n2
return (n % m + m) % m
if __name__ == "__main__":
from doctest import testmod
testmod(name="chinese_remainder_theorem", verbose=True)
testmod(name="chinese_remainder_theorem2", verbose=True)
testmod(name="invert_modulo", verbose=True)
testmod(name="extended_euclid", verbose=True)
| """
Chinese Remainder Theorem:
GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )
If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b
there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are
two such integers, then n1=n2(mod ab)
Algorithm :
1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1
2. Take n = ra*by + rb*ax
"""
from __future__ import annotations
# Extended Euclid
def extended_euclid(a: int, b: int) -> tuple[int, int]:
"""
>>> extended_euclid(10, 6)
(-1, 2)
>>> extended_euclid(7, 5)
(-2, 3)
"""
if b == 0:
return (1, 0)
(x, y) = extended_euclid(b, a % b)
k = a // b
return (y, x - k * y)
# Uses ExtendedEuclid to find inverses
def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int:
"""
>>> chinese_remainder_theorem(5,1,7,3)
31
Explanation : 31 is the smallest number such that
(i) When we divide it by 5, we get remainder 1
(ii) When we divide it by 7, we get remainder 3
>>> chinese_remainder_theorem(6,1,4,3)
14
"""
(x, y) = extended_euclid(n1, n2)
m = n1 * n2
n = r2 * x * n1 + r1 * y * n2
return (n % m + m) % m
# ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid----------------
# This function find the inverses of a i.e., a^(-1)
def invert_modulo(a: int, n: int) -> int:
"""
>>> invert_modulo(2, 5)
3
>>> invert_modulo(8,7)
1
"""
(b, x) = extended_euclid(a, n)
if b < 0:
b = (b % n + n) % n
return b
# Same a above using InvertingModulo
def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int:
"""
>>> chinese_remainder_theorem2(5,1,7,3)
31
>>> chinese_remainder_theorem2(6,1,4,3)
14
"""
x, y = invert_modulo(n1, n2), invert_modulo(n2, n1)
m = n1 * n2
n = r2 * x * n1 + r1 * y * n2
return (n % m + m) % m
if __name__ == "__main__":
from doctest import testmod
testmod(name="chinese_remainder_theorem", verbose=True)
testmod(name="chinese_remainder_theorem2", verbose=True)
testmod(name="invert_modulo", verbose=True)
testmod(name="extended_euclid", verbose=True)
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
from __future__ import annotations
def maximum_non_adjacent_sum(nums: list[int]) -> int:
"""
Find the maximum non-adjacent sum of the integers in the nums input list
>>> print(maximum_non_adjacent_sum([1, 2, 3]))
4
>>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])
18
>>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])
0
>>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])
500
"""
if not nums:
return 0
max_including = nums[0]
max_excluding = 0
for num in nums[1:]:
max_including, max_excluding = (
max_excluding + num,
max(max_including, max_excluding),
)
return max(max_excluding, max_including)
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
from __future__ import annotations
def maximum_non_adjacent_sum(nums: list[int]) -> int:
"""
Find the maximum non-adjacent sum of the integers in the nums input list
>>> print(maximum_non_adjacent_sum([1, 2, 3]))
4
>>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])
18
>>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])
0
>>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])
500
"""
if not nums:
return 0
max_including = nums[0]
max_excluding = 0
for num in nums[1:]:
max_including, max_excluding = (
max_excluding + num,
max(max_including, max_excluding),
)
return max(max_excluding, max_including)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Functions for 2D matrix operations
"""
from __future__ import annotations
def add(*matrix_s: list[list]) -> list[list]:
"""
>>> add([[1,2],[3,4]],[[2,3],[4,5]])
[[3, 5], [7, 9]]
>>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])
[[3.2, 5.4], [7, 9]]
>>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]])
[[7, 14], [12, 16]]
"""
if all(_check_not_integer(m) for m in matrix_s):
for i in matrix_s[1:]:
_verify_matrix_sizes(matrix_s[0], i)
return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> subtract([[1,2],[3,4]],[[2,3],[4,5]])
[[-1, -1], [-1, -1]]
>>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
[[-1, -0.5], [-1, -1.5]]
"""
if (
_check_not_integer(matrix_a)
and _check_not_integer(matrix_b)
and _verify_matrix_sizes(matrix_a, matrix_b)
):
return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)]
def scalar_multiply(matrix: list[list], n: int) -> list[list]:
"""
>>> scalar_multiply([[1,2],[3,4]],5)
[[5, 10], [15, 20]]
>>> scalar_multiply([[1.4,2.3],[3,4]],5)
[[7.0, 11.5], [15, 20]]
"""
return [[x * n for x in row] for row in matrix]
def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> multiply([[1,2],[3,4]],[[5,5],[7,5]])
[[19, 15], [43, 35]]
>>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]]
>>> multiply([[1, 2, 3]], [[2], [3], [4]])
[[20]]
"""
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
if cols[0] != rows[1]:
raise ValueError(
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
f"and ({rows[1]},{cols[1]})"
)
return [
[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a
]
def identity(n: int) -> list[list]:
"""
:param n: dimension for nxn matrix
:type n: int
:return: Identity matrix of shape [n, n]
>>> identity(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
n = int(n)
return [[int(row == column) for column in range(n)] for row in range(n)]
def transpose(matrix: list[list], return_map: bool = True) -> list[list]:
"""
>>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS
<map object at ...
>>> transpose([[1,2],[3,4]], return_map=False)
[[1, 3], [2, 4]]
"""
if _check_not_integer(matrix):
if return_map:
return map(list, zip(*matrix))
else:
return list(map(list, zip(*matrix)))
def minor(matrix: list[list], row: int, column: int) -> list[list]:
"""
>>> minor([[1, 2], [3, 4]], 1, 1)
[[1]]
"""
minor = matrix[:row] + matrix[row + 1 :]
return [row[:column] + row[column + 1 :] for row in minor]
def determinant(matrix: list[list]) -> int:
"""
>>> determinant([[1, 2], [3, 4]])
-2
>>> determinant([[1.5, 2.5], [3, 4]])
-1.5
"""
if len(matrix) == 1:
return matrix[0][0]
return sum(
x * determinant(minor(matrix, 0, i)) * (-1) ** i
for i, x in enumerate(matrix[0])
)
def inverse(matrix: list[list]) -> list[list]:
"""
>>> inverse([[1, 2], [3, 4]])
[[-2.0, 1.0], [1.5, -0.5]]
>>> inverse([[1, 1], [1, 1]])
"""
# https://stackoverflow.com/questions/20047519/python-doctests-test-for-none
det = determinant(matrix)
if det == 0:
return None
matrix_minor = [
[determinant(minor(matrix, i, j)) for j in range(len(matrix))]
for i in range(len(matrix))
]
cofactors = [
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
for row in range(len(matrix))
]
adjugate = transpose(cofactors)
return scalar_multiply(adjugate, 1 / det)
def _check_not_integer(matrix: list[list]) -> bool:
if not isinstance(matrix, int) and not isinstance(matrix[0], int):
return True
raise TypeError("Expected a matrix, got int/list instead")
def _shape(matrix: list[list]) -> list:
return len(matrix), len(matrix[0])
def _verify_matrix_sizes(matrix_a: list[list], matrix_b: list[list]) -> tuple[list]:
shape = _shape(matrix_a) + _shape(matrix_b)
if shape[0] != shape[3] or shape[1] != shape[2]:
raise ValueError(
f"operands could not be broadcast together with shape "
f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
)
return (shape[0], shape[2]), (shape[1], shape[3])
def main():
matrix_a = [[12, 10], [3, 9]]
matrix_b = [[3, 4], [7, 4]]
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
print(
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
)
print(f"Identity: {identity(5)}\n")
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| """
Functions for 2D matrix operations
"""
from __future__ import annotations
def add(*matrix_s: list[list]) -> list[list]:
"""
>>> add([[1,2],[3,4]],[[2,3],[4,5]])
[[3, 5], [7, 9]]
>>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])
[[3.2, 5.4], [7, 9]]
>>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]])
[[7, 14], [12, 16]]
"""
if all(_check_not_integer(m) for m in matrix_s):
for i in matrix_s[1:]:
_verify_matrix_sizes(matrix_s[0], i)
return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> subtract([[1,2],[3,4]],[[2,3],[4,5]])
[[-1, -1], [-1, -1]]
>>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
[[-1, -0.5], [-1, -1.5]]
"""
if (
_check_not_integer(matrix_a)
and _check_not_integer(matrix_b)
and _verify_matrix_sizes(matrix_a, matrix_b)
):
return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)]
def scalar_multiply(matrix: list[list], n: int) -> list[list]:
"""
>>> scalar_multiply([[1,2],[3,4]],5)
[[5, 10], [15, 20]]
>>> scalar_multiply([[1.4,2.3],[3,4]],5)
[[7.0, 11.5], [15, 20]]
"""
return [[x * n for x in row] for row in matrix]
def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> multiply([[1,2],[3,4]],[[5,5],[7,5]])
[[19, 15], [43, 35]]
>>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]]
>>> multiply([[1, 2, 3]], [[2], [3], [4]])
[[20]]
"""
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
if cols[0] != rows[1]:
raise ValueError(
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
f"and ({rows[1]},{cols[1]})"
)
return [
[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a
]
def identity(n: int) -> list[list]:
"""
:param n: dimension for nxn matrix
:type n: int
:return: Identity matrix of shape [n, n]
>>> identity(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
n = int(n)
return [[int(row == column) for column in range(n)] for row in range(n)]
def transpose(matrix: list[list], return_map: bool = True) -> list[list]:
"""
>>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS
<map object at ...
>>> transpose([[1,2],[3,4]], return_map=False)
[[1, 3], [2, 4]]
"""
if _check_not_integer(matrix):
if return_map:
return map(list, zip(*matrix))
else:
return list(map(list, zip(*matrix)))
def minor(matrix: list[list], row: int, column: int) -> list[list]:
"""
>>> minor([[1, 2], [3, 4]], 1, 1)
[[1]]
"""
minor = matrix[:row] + matrix[row + 1 :]
return [row[:column] + row[column + 1 :] for row in minor]
def determinant(matrix: list[list]) -> int:
"""
>>> determinant([[1, 2], [3, 4]])
-2
>>> determinant([[1.5, 2.5], [3, 4]])
-1.5
"""
if len(matrix) == 1:
return matrix[0][0]
return sum(
x * determinant(minor(matrix, 0, i)) * (-1) ** i
for i, x in enumerate(matrix[0])
)
def inverse(matrix: list[list]) -> list[list]:
"""
>>> inverse([[1, 2], [3, 4]])
[[-2.0, 1.0], [1.5, -0.5]]
>>> inverse([[1, 1], [1, 1]])
"""
# https://stackoverflow.com/questions/20047519/python-doctests-test-for-none
det = determinant(matrix)
if det == 0:
return None
matrix_minor = [
[determinant(minor(matrix, i, j)) for j in range(len(matrix))]
for i in range(len(matrix))
]
cofactors = [
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
for row in range(len(matrix))
]
adjugate = transpose(cofactors)
return scalar_multiply(adjugate, 1 / det)
def _check_not_integer(matrix: list[list]) -> bool:
if not isinstance(matrix, int) and not isinstance(matrix[0], int):
return True
raise TypeError("Expected a matrix, got int/list instead")
def _shape(matrix: list[list]) -> list:
return len(matrix), len(matrix[0])
def _verify_matrix_sizes(matrix_a: list[list], matrix_b: list[list]) -> tuple[list]:
shape = _shape(matrix_a) + _shape(matrix_b)
if shape[0] != shape[3] or shape[1] != shape[2]:
raise ValueError(
f"operands could not be broadcast together with shape "
f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
)
return (shape[0], shape[2]), (shape[1], shape[3])
def main():
matrix_a = [[12, 10], [3, 9]]
matrix_b = [[3, 4], [7, 4]]
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
print(
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
)
print(f"Identity: {identity(5)}\n")
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| -1 |
TheAlgorithms/Python | 5,566 | [mypy] Fix type annotations for stack.py | ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| archaengel | "2021-10-23T18:21:43Z" | "2021-10-26T18:33:08Z" | 582f57f41fb9d36ae8fe4d49c98775877b9013b7 | c0ed031b3fcf47736f98dfd89e2588dbffceadde | [mypy] Fix type annotations for stack.py. ```
$ git checkout mypy-fix-stacks-stack
Switched to branch 'mypy-fix-stacks-stack'
$ mypy --ignore-missing-imports data_structures/stacks/stack.py --strict
Success: no issues found in 1 source file
$ mypy --ignore-missing-imports data_structures/stacks --strict > after.txt
$ git checkout master
Switched to branch 'master'
$ mypy --ignore-missing-imports data_structures/stacks --strict > before.txt
$ diff before.txt after.txt
39,49d38
< data_structures/stacks/stack.py:31: error: Function is missing a type annotation
< data_structures/stacks/stack.py:37: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:50: error: Function is missing a return type annotation
< data_structures/stacks/stack.py:74: error: Function is missing a type annotation for one or more arguments
< data_structures/stacks/stack.py:90: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:96: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:103: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:109: error: Call to untyped function "pop" in typed context
< data_structures/stacks/stack.py:110: error: Call to untyped function "peek" in typed context
< data_structures/stacks/stack.py:112: error: Call to untyped function "push" in typed context
< data_structures/stacks/stack.py:116: error: Call to untyped function "push" in typed context
52,62d40
< data_structures/stacks/dijkstras_two_stack_algorithm.py:60: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:63: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:66: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:67: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:68: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:69: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:70: error: Call to untyped function "peek" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:71: error: Call to untyped function "pop" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:74: error: Call to untyped function "push" in typed context
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Returning Any from function declared to return "int"
< data_structures/stacks/dijkstras_two_stack_algorithm.py:77: error: Call to untyped function "peek" in typed context
75,85c53
< data_structures/stacks/balanced_parentheses.py:21: error: Call to untyped function "push" in typed context
< data_structures/stacks/balanced_parentheses.py:23: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:47: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:49: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:50: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:51: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:53: error: Call to untyped function "peek" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:54: error: Call to untyped function "pop" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:55: error: Call to untyped function "push" in typed context
< data_structures/stacks/infix_to_postfix_conversion.py:57: error: Call to untyped function "pop" in typed context
< Found 82 errors in 12 files (checked 13 source files)
---
> Found 50 errors in 8 files (checked 13 source files)
```
Related to #4052
### **Describe your change:**
Add generic type annotations to functions in `stack.py`. Add type annotations to variables of `Stack` class.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 9: https://projecteuler.net/problem=9
Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product a*b*c.
References:
- https://en.wikipedia.org/wiki/Pythagorean_triple
"""
def solution(n: int = 1000) -> int:
"""
Return the product of a,b,c which are Pythagorean Triplet that satisfies
the following:
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = n
>>> solution(36)
1620
>>> solution(126)
66780
"""
product = -1
candidate = 0
for a in range(1, n // 3):
# Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
b = (n * n - 2 * a * n) // (2 * n - 2 * a)
c = n - a - b
if c * c == (a * a + b * b):
candidate = a * b * c
if candidate >= product:
product = candidate
return product
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 9: https://projecteuler.net/problem=9
Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product a*b*c.
References:
- https://en.wikipedia.org/wiki/Pythagorean_triple
"""
def solution(n: int = 1000) -> int:
"""
Return the product of a,b,c which are Pythagorean Triplet that satisfies
the following:
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = n
>>> solution(36)
1620
>>> solution(126)
66780
"""
product = -1
candidate = 0
for a in range(1, n // 3):
# Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
b = (n * n - 2 * a * n) // (2 * n - 2 * a)
c = n - a - b
if c * c == (a * a + b * b):
candidate = a * b * c
if candidate >= product:
product = candidate
return product
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
|
## Arithmetic Analysis
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py)
* [Gaussian Elimination](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py)
* [Lu Decomposition](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_raphson.py)
* [Secant Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/secant_method.py)
## Backtracking
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Hamiltonian Cycle](https://github.com/TheAlgorithms/Python/blob/master/backtracking/hamiltonian_cycle.py)
* [Knight Tour](https://github.com/TheAlgorithms/Python/blob/master/backtracking/knight_tour.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [N Queens Math](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens_math.py)
* [Rat In Maze](https://github.com/TheAlgorithms/Python/blob/master/backtracking/rat_in_maze.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
* [Binary Shifts](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_number_of_one_bits.py)
* [Reverse Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/reverse_bits.py)
* [Single Bit Manipulation Operations](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/single_bit_manipulation_operations.py)
## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
* [Modular Division](https://github.com/TheAlgorithms/Python/blob/master/blockchain/modular_division.py)
## Boolean Algebra
* [Quine Mc Cluskey](https://github.com/TheAlgorithms/Python/blob/master/boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/conways_game_of_life.py)
* [Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/game_of_life.py)
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Baconian Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/baconian_cipher.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64 Encoding](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64_encoding.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/caesar_cipher.py)
* [Cryptomath Module](https://github.com/TheAlgorithms/Python/blob/master/ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](https://github.com/TheAlgorithms/Python/blob/master/ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Diffie Hellman](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie_hellman.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
* [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
* [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
* [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
* [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
* [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
* [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
* [Rot13](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rot13.py)
* [Rsa Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_cipher.py)
* [Rsa Factorization](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_factorization.py)
* [Rsa Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/trafid_cipher.py)
* [Transposition Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/vigenere_cipher.py)
* [Xor Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](https://github.com/TheAlgorithms/Python/blob/master/compression/burrows_wheeler.py)
* [Huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py)
* [Lempel Ziv](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv.py)
* [Lempel Ziv Decompress](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](https://github.com/TheAlgorithms/Python/blob/master/compression/peak_signal_to_noise_ratio.py)
## Computer Vision
* [Cnn Classification](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/cnn_classification.py)
* [Harris Corner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harris_corner.py)
* [Mean Threshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mean_threshold.py)
## Conversions
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)
* [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_hexadecimal.py)
* [Decimal To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_octal.py)
* [Hex To Bin](https://github.com/TheAlgorithms/Python/blob/master/conversions/hex_to_bin.py)
* [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.py)
* [Length Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/length_conversion.py)
* [Molecular Chemistry](https://github.com/TheAlgorithms/Python/blob/master/conversions/molecular_chemistry.py)
* [Octal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/octal_to_decimal.py)
* [Prefix Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/prefix_conversions.py)
* [Rgb Hsv Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/rgb_hsv_conversion.py)
* [Roman Numerals](https://github.com/TheAlgorithms/Python/blob/master/conversions/roman_numerals.py)
* [Temperature Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/temperature_conversions.py)
* [Weight Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* [Wavelet Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
* [Hash Table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/binomial_heap.py)
* [Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap.py)
* [Heap Generic](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap_generic.py)
* [Max Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/max_heap.py)
* [Min Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/min_heap.py)
* [Randomized Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/randomized_heap.py)
* [Skew Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
* [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/print_reverse.py)
* [Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/singly_linked_list.py)
* [Skip List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/skip_list.py)
* [Swap Nodes](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue.py)
* [Double Ended Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/double_ended_queue.py)
* [Linked Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/linked_queue.py)
* [Priority Queue Using List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/priority_queue_using_list.py)
* [Queue On List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
* [Linked Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/linked_stack.py)
* [Next Greater Element](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/prefix_evaluation.py)
* [Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack.py)
* [Stack Using Dll](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_using_dll.py)
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_brightness.py)
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py)
* [Convolve](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/convolve.py)
* [Gaussian Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/median_filter.py)
* [Sobel Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/rotation/rotation.py)
* [Sepia](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/sepia.py)
* [Test Digital Image Processing](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/inversions.py)
* [Kth Order Statistic](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_subarray_sum.py)
* [Mergesort](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/mergesort.py)
* [Peak](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/peak.py)
* [Power](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/abbreviation.py)
* [Bitmask](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/bitmask.py)
* [Catalan Numbers](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/climbing_stairs.py)
* [Edit Distance](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py)
* [Factorial](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/factorial.py)
* [Fast Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fast_fibonacci.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fibonacci.py)
* [Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/iterating_through_submasks.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/knapsack.py)
* [Longest Common Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](https://github.com/TheAlgorithms/Python/blob/master/electronics/carrier_concentration.py)
* [Coulombs Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/coulombs_law.py)
* [Electric Power](https://github.com/TheAlgorithms/Python/blob/master/electronics/electric_power.py)
* [Ohms Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/ohms_law.py)
## File Transfer
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
* Tests
* [Test Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/tests/test_send_file.py)
## Fractals
* [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py)
* [Koch Snowflake](https://github.com/TheAlgorithms/Python/blob/master/fractals/koch_snowflake.py)
* [Mandelbrot](https://github.com/TheAlgorithms/Python/blob/master/fractals/mandelbrot.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](https://github.com/TheAlgorithms/Python/blob/master/fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](https://github.com/TheAlgorithms/Python/blob/master/graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](https://github.com/TheAlgorithms/Python/blob/master/graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/a_star.py)
* [Articulation Points](https://github.com/TheAlgorithms/Python/blob/master/graphs/articulation_points.py)
* [Basic Graphs](https://github.com/TheAlgorithms/Python/blob/master/graphs/basic_graphs.py)
* [Bellman Ford](https://github.com/TheAlgorithms/Python/blob/master/graphs/bellman_ford.py)
* [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_breadth_first_search.py)
* [Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/boruvka.py)
* [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
* [Breadth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
* [Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/connected_components.py)
* [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
* [Depth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search_2.py)
* [Dijkstra](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra.py)
* [Dijkstra 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_2.py)
* [Dijkstra Algorithm](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_algorithm.py)
* [Dinic](https://github.com/TheAlgorithms/Python/blob/master/graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](https://github.com/TheAlgorithms/Python/blob/master/graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](https://github.com/TheAlgorithms/Python/blob/master/graphs/even_tree.py)
* [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py)
* [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py)
* [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py)
* [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py)
* [Greedy Best First](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
* [Karger](https://github.com/TheAlgorithms/Python/blob/master/graphs/karger.py)
* [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/graphs/markov_chain.py)
* [Matching Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/matching_min_vertex_cover.py)
* [Minimum Spanning Tree Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
* [Strongly Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/strongly_connected_components.py)
* [Tarjans Scc](https://github.com/TheAlgorithms/Python/blob/master/graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](https://github.com/TheAlgorithms/Python/blob/master/greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](https://github.com/TheAlgorithms/Python/blob/master/hashes/adler32.py)
* [Chaos Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/chaos_machine.py)
* [Djb2](https://github.com/TheAlgorithms/Python/blob/master/hashes/djb2.py)
* [Enigma Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/enigma_machine.py)
* [Hamming Code](https://github.com/TheAlgorithms/Python/blob/master/hashes/hamming_code.py)
* [Luhn](https://github.com/TheAlgorithms/Python/blob/master/hashes/luhn.py)
* [Md5](https://github.com/TheAlgorithms/Python/blob/master/hashes/md5.py)
* [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py)
* [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py)
## Knapsack
* [Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/greedy_knapsack.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/conjugate_gradient.py)
* [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py)
* [Polynom For Points](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/polynom_for_points.py)
* [Power Iteration](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/astar.py)
* [Data Transformations](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/data_transformations.py)
* [Decision Tree](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/decision_tree.py)
* Forecasting
* [Run](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_descent.py)
* [K Means Clust](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_means_clust.py)
* [K Nearest Neighbours](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_regression.py)
* [Logistic Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/polymonial_regression.py)
* [Random Forest Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_regressor.py)
* [Scoring Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/similarity_search.py)
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
* [Word Frequency Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)
* [Add](https://github.com/TheAlgorithms/Python/blob/master/maths/add.py)
* [Aliquot Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/aliquot_sum.py)
* [Allocation Number](https://github.com/TheAlgorithms/Python/blob/master/maths/allocation_number.py)
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)
* [Bailey Borwein Plouffe](https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py)
* [Basic Maths](https://github.com/TheAlgorithms/Python/blob/master/maths/basic_maths.py)
* [Binary Exp Mod](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py)
* [Binary Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py)
* [Binary Exponentiation 2](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_3.py)
* [Binomial Coefficient](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_coefficient.py)
* [Binomial Distribution](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_distribution.py)
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/maths/bisection.py)
* [Ceil](https://github.com/TheAlgorithms/Python/blob/master/maths/ceil.py)
* [Check Polygon](https://github.com/TheAlgorithms/Python/blob/master/maths/check_polygon.py)
* [Chudnovsky Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/chudnovsky_algorithm.py)
* [Collatz Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/collatz_sequence.py)
* [Combinations](https://github.com/TheAlgorithms/Python/blob/master/maths/combinations.py)
* [Decimal Isolate](https://github.com/TheAlgorithms/Python/blob/master/maths/decimal_isolate.py)
* [Double Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_iterative.py)
* [Double Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_recursive.py)
* [Entropy](https://github.com/TheAlgorithms/Python/blob/master/maths/entropy.py)
* [Euclidean Distance](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_distance.py)
* [Euclidean Gcd](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_gcd.py)
* [Euler Method](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_method.py)
* [Euler Modified](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_modified.py)
* [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
* [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
* [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
* [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
* [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci.py)
* [Fibonacci Sequence Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci_sequence_recursion.py)
* [Find Max](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max.py)
* [Find Max Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max_recursion.py)
* [Find Min](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min.py)
* [Find Min Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min_recursion.py)
* [Floor](https://github.com/TheAlgorithms/Python/blob/master/maths/floor.py)
* [Gamma](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma.py)
* [Gamma Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma_recursive.py)
* [Gaussian](https://github.com/TheAlgorithms/Python/blob/master/maths/gaussian.py)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/Python/blob/master/maths/greatest_common_divisor.py)
* [Greedy Coin Change](https://github.com/TheAlgorithms/Python/blob/master/maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](https://github.com/TheAlgorithms/Python/blob/master/maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](https://github.com/TheAlgorithms/Python/blob/master/maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](https://github.com/TheAlgorithms/Python/blob/master/maths/is_ip_v4_address_valid.py)
* [Is Square Free](https://github.com/TheAlgorithms/Python/blob/master/maths/is_square_free.py)
* [Jaccard Similarity](https://github.com/TheAlgorithms/Python/blob/master/maths/jaccard_similarity.py)
* [Kadanes](https://github.com/TheAlgorithms/Python/blob/master/maths/kadanes.py)
* [Karatsuba](https://github.com/TheAlgorithms/Python/blob/master/maths/karatsuba.py)
* [Krishnamurthy Number](https://github.com/TheAlgorithms/Python/blob/master/maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](https://github.com/TheAlgorithms/Python/blob/master/maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_subarray_sum.py)
* [Least Common Multiple](https://github.com/TheAlgorithms/Python/blob/master/maths/least_common_multiple.py)
* [Line Length](https://github.com/TheAlgorithms/Python/blob/master/maths/line_length.py)
* [Lucas Lehmer Primality Test](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py)
* [Lucas Series](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_series.py)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/maths/median_of_two_arrays.py)
* [Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py)
* [Mobius Function](https://github.com/TheAlgorithms/Python/blob/master/maths/mobius_function.py)
* [Modular Exponential](https://github.com/TheAlgorithms/Python/blob/master/maths/modular_exponential.py)
* [Monte Carlo](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo.py)
* [Monte Carlo Dice](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo_dice.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/maths/newton_raphson.py)
* [Number Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/number_of_digits.py)
* [Numerical Integration](https://github.com/TheAlgorithms/Python/blob/master/maths/numerical_integration.py)
* [Perfect Cube](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_cube.py)
* [Perfect Number](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_number.py)
* [Perfect Square](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_square.py)
* [Pi Monte Carlo Estimation](https://github.com/TheAlgorithms/Python/blob/master/maths/pi_monte_carlo_estimation.py)
* [Polynomial Evaluation](https://github.com/TheAlgorithms/Python/blob/master/maths/polynomial_evaluation.py)
* [Power Using Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/power_using_recursion.py)
* [Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py)
* [Prime Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py)
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_sieve_eratosthenes.py)
* [Primelib](https://github.com/TheAlgorithms/Python/blob/master/maths/primelib.py)
* [Proth Number](https://github.com/TheAlgorithms/Python/blob/master/maths/proth_number.py)
* [Pythagoras](https://github.com/TheAlgorithms/Python/blob/master/maths/pythagoras.py)
* [Qr Decomposition](https://github.com/TheAlgorithms/Python/blob/master/maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/quadratic_equations_complex_numbers.py)
* [Radians](https://github.com/TheAlgorithms/Python/blob/master/maths/radians.py)
* [Radix2 Fft](https://github.com/TheAlgorithms/Python/blob/master/maths/radix2_fft.py)
* [Relu](https://github.com/TheAlgorithms/Python/blob/master/maths/relu.py)
* [Runge Kutta](https://github.com/TheAlgorithms/Python/blob/master/maths/runge_kutta.py)
* [Segmented Sieve](https://github.com/TheAlgorithms/Python/blob/master/maths/segmented_sieve.py)
* Series
* [Arithmetic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic.py)
* [Geometric](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric.py)
* [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.py)
* [Harmonic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic.py)
* [Harmonic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic_series.py)
* [P Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/p_series.py)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/sieve_of_eratosthenes.py)
* [Sigmoid](https://github.com/TheAlgorithms/Python/blob/master/maths/sigmoid.py)
* [Simpson Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/simpson_rule.py)
* [Softmax](https://github.com/TheAlgorithms/Python/blob/master/maths/softmax.py)
* [Square Root](https://github.com/TheAlgorithms/Python/blob/master/maths/square_root.py)
* [Sum Of Arithmetic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_digits.py)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/sylvester_sequence.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/maths/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/two_sum.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/inverse_of_matrix.py)
* [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py)
* [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](https://github.com/TheAlgorithms/Python/blob/master/matrix/sherman_morrison.py)
* [Spiral Print](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py)
* [Minimum Cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/convolution_neural_network.py)
* [Perceptron](https://github.com/TheAlgorithms/Python/blob/master/neural_network/perceptron.py)
## Other
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
* [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
* [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
* [Gauss Easter](https://github.com/TheAlgorithms/Python/blob/master/other/gauss_easter.py)
* [Graham Scan](https://github.com/TheAlgorithms/Python/blob/master/other/graham_scan.py)
* [Greedy](https://github.com/TheAlgorithms/Python/blob/master/other/greedy.py)
* [Least Recently Used](https://github.com/TheAlgorithms/Python/blob/master/other/least_recently_used.py)
* [Lfu Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lfu_cache.py)
* [Linear Congruential Generator](https://github.com/TheAlgorithms/Python/blob/master/other/linear_congruential_generator.py)
* [Lru Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lru_cache.py)
* [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py)
* [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py)
* [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py)
* [Scoring Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/scoring_algorithm.py)
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
## Physics
* [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py)
## Project Euler
* Problem 001
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol5.py)
* [Sol6](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol6.py)
* [Sol7](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/sol1.py)
* [Test Poker Hand](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
* Problem 069
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_077/sol1.py)
* Problem 080
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_102/sol1.py)
* Problem 107
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_107/sol1.py)
* Problem 109
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_109/sol1.py)
* Problem 112
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_112/sol1.py)
* Problem 113
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_113/sol1.py)
* Problem 119
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_203/sol1.py)
* Problem 206
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_301/sol1.py)
* Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
## Quantum
* [Deutsch Jozsa](https://github.com/TheAlgorithms/Python/blob/master/quantum/deutsch_jozsa.py)
* [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
* [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
* [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
* [Ripple Adder Classic](https://github.com/TheAlgorithms/Python/blob/master/quantum/ripple_adder_classic.py)
* [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](https://github.com/TheAlgorithms/Python/blob/master/scheduling/first_come_first_served.py)
* [Round Robin](https://github.com/TheAlgorithms/Python/blob/master/scheduling/round_robin.py)
* [Shortest Job First](https://github.com/TheAlgorithms/Python/blob/master/scheduling/shortest_job_first.py)
## Searches
* [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py)
* [Binary Tree Traversal](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_tree_traversal.py)
* [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py)
* [Double Linear Search Recursion](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search_recursion.py)
* [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py)
* [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py)
* [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py)
* [Jump Search](https://github.com/TheAlgorithms/Python/blob/master/searches/jump_search.py)
* [Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/linear_search.py)
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
* [Simple Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple_binary_search.py)
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
## Sorts
* [Bead Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bead_sort.py)
* [Bitonic Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bitonic_sort.py)
* [Bogo Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bogo_sort.py)
* [Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py)
* [Bucket Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bucket_sort.py)
* [Cocktail Shaker Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py)
* [Comb Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/comb_sort.py)
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
* [Heap Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/heap_sort.py)
* [Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/insertion_sort.py)
* [Intro Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/intro_sort.py)
* [Iterative Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/iterative_merge_sort.py)
* [Merge Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_insertion_sort.py)
* [Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_sort.py)
* [Msd Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/msd_radix_sort.py)
* [Natural Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/natural_sort.py)
* [Odd Even Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_sort.py)
* [Odd Even Transposition Parallel](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_parallel.py)
* [Odd Even Transposition Single Threaded](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_single_threaded.py)
* [Pancake Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pancake_sort.py)
* [Patience Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/patience_sort.py)
* [Pigeon Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeon_sort.py)
* [Pigeonhole Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeonhole_sort.py)
* [Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py)
* [Quick Sort 3 Partition](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort_3_partition.py)
* [Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/radix_sort.py)
* [Random Normal Distribution Quicksort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_normal_distribution_quicksort.py)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_pivot_quick_sort.py)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_bubble_sort.py)
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Recursive Mergesort Array](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_mergesort_array.py)
* [Recursive Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_quick_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Slowsort](https://github.com/TheAlgorithms/Python/blob/master/sorts/slowsort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
* [Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/topological_sort.py)
* [Tree Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tree_sort.py)
* [Unknown Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/unknown_sort.py)
* [Wiggle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/wiggle_sort.py)
## Strings
* [Aho Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho_corasick.py)
* [Alternative String Arrange](https://github.com/TheAlgorithms/Python/blob/master/strings/alternative_string_arrange.py)
* [Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/anagrams.py)
* [Autocomplete Using Trie](https://github.com/TheAlgorithms/Python/blob/master/strings/autocomplete_using_trie.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Can String Be Rearranged As Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Detecting English Programmatically](https://github.com/TheAlgorithms/Python/blob/master/strings/detecting_english_programmatically.py)
* [Frequency Finder](https://github.com/TheAlgorithms/Python/blob/master/strings/frequency_finder.py)
* [Indian Phone Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/indian_phone_validator.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
* [Jaro Winkler](https://github.com/TheAlgorithms/Python/blob/master/strings/jaro_winkler.py)
* [Join](https://github.com/TheAlgorithms/Python/blob/master/strings/join.py)
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/Python/blob/master/strings/knuth_morris_pratt.py)
* [Levenshtein Distance](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py)
* [Lower](https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py)
* [Manacher](https://github.com/TheAlgorithms/Python/blob/master/strings/manacher.py)
* [Min Cost String Conversion](https://github.com/TheAlgorithms/Python/blob/master/strings/min_cost_string_conversion.py)
* [Naive String Search](https://github.com/TheAlgorithms/Python/blob/master/strings/naive_string_search.py)
* [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/palindrome.py)
* [Prefix Function](https://github.com/TheAlgorithms/Python/blob/master/strings/prefix_function.py)
* [Rabin Karp](https://github.com/TheAlgorithms/Python/blob/master/strings/rabin_karp.py)
* [Remove Duplicate](https://github.com/TheAlgorithms/Python/blob/master/strings/remove_duplicate.py)
* [Reverse Letters](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_letters.py)
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
* [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
* [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
## Web Programming
* [Co2 Emission](https://github.com/TheAlgorithms/Python/blob/master/web_programming/co2_emission.py)
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
* [Download Images From Google Query](https://github.com/TheAlgorithms/Python/blob/master/web_programming/download_images_from_google_query.py)
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Giphy](https://github.com/TheAlgorithms/Python/blob/master/web_programming/giphy.py)
* [Instagram Crawler](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_crawler.py)
* [Instagram Pic](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_pic.py)
* [Instagram Video](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_video.py)
* [Random Anime Character](https://github.com/TheAlgorithms/Python/blob/master/web_programming/random_anime_character.py)
* [Recaptcha Verification](https://github.com/TheAlgorithms/Python/blob/master/web_programming/recaptcha_verification.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)
* [Test Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/test_fetch_github_info.py)
* [World Covid19 Stats](https://github.com/TheAlgorithms/Python/blob/master/web_programming/world_covid19_stats.py)
|
## Arithmetic Analysis
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py)
* [Gaussian Elimination](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py)
* [Lu Decomposition](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_raphson.py)
* [Secant Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/secant_method.py)
## Backtracking
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Hamiltonian Cycle](https://github.com/TheAlgorithms/Python/blob/master/backtracking/hamiltonian_cycle.py)
* [Knight Tour](https://github.com/TheAlgorithms/Python/blob/master/backtracking/knight_tour.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [N Queens Math](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens_math.py)
* [Rat In Maze](https://github.com/TheAlgorithms/Python/blob/master/backtracking/rat_in_maze.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
* [Binary Shifts](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_number_of_one_bits.py)
* [Reverse Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/reverse_bits.py)
* [Single Bit Manipulation Operations](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/single_bit_manipulation_operations.py)
## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
* [Modular Division](https://github.com/TheAlgorithms/Python/blob/master/blockchain/modular_division.py)
## Boolean Algebra
* [Quine Mc Cluskey](https://github.com/TheAlgorithms/Python/blob/master/boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/conways_game_of_life.py)
* [Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/game_of_life.py)
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Baconian Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/baconian_cipher.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64 Encoding](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64_encoding.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/caesar_cipher.py)
* [Cryptomath Module](https://github.com/TheAlgorithms/Python/blob/master/ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](https://github.com/TheAlgorithms/Python/blob/master/ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Diffie Hellman](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie_hellman.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
* [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
* [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
* [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
* [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
* [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
* [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
* [Rot13](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rot13.py)
* [Rsa Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_cipher.py)
* [Rsa Factorization](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_factorization.py)
* [Rsa Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/trafid_cipher.py)
* [Transposition Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/vigenere_cipher.py)
* [Xor Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](https://github.com/TheAlgorithms/Python/blob/master/compression/burrows_wheeler.py)
* [Huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py)
* [Lempel Ziv](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv.py)
* [Lempel Ziv Decompress](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](https://github.com/TheAlgorithms/Python/blob/master/compression/peak_signal_to_noise_ratio.py)
## Computer Vision
* [Cnn Classification](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/cnn_classification.py)
* [Harris Corner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harris_corner.py)
* [Mean Threshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mean_threshold.py)
## Conversions
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)
* [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_hexadecimal.py)
* [Decimal To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_octal.py)
* [Hex To Bin](https://github.com/TheAlgorithms/Python/blob/master/conversions/hex_to_bin.py)
* [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.py)
* [Length Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/length_conversion.py)
* [Molecular Chemistry](https://github.com/TheAlgorithms/Python/blob/master/conversions/molecular_chemistry.py)
* [Octal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/octal_to_decimal.py)
* [Prefix Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/prefix_conversions.py)
* [Rgb Hsv Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/rgb_hsv_conversion.py)
* [Roman Numerals](https://github.com/TheAlgorithms/Python/blob/master/conversions/roman_numerals.py)
* [Temperature Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/temperature_conversions.py)
* [Weight Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* [Wavelet Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
* [Hash Table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/binomial_heap.py)
* [Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap.py)
* [Heap Generic](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap_generic.py)
* [Max Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/max_heap.py)
* [Min Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/min_heap.py)
* [Randomized Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/randomized_heap.py)
* [Skew Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
* [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/print_reverse.py)
* [Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/singly_linked_list.py)
* [Skip List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/skip_list.py)
* [Swap Nodes](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue.py)
* [Double Ended Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/double_ended_queue.py)
* [Linked Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/linked_queue.py)
* [Priority Queue Using List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/priority_queue_using_list.py)
* [Queue On List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
* [Linked Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/linked_stack.py)
* [Next Greater Element](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/prefix_evaluation.py)
* [Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack.py)
* [Stack Using Dll](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_using_dll.py)
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_brightness.py)
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py)
* [Convolve](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/convolve.py)
* [Gaussian Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/median_filter.py)
* [Sobel Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/rotation/rotation.py)
* [Sepia](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/sepia.py)
* [Test Digital Image Processing](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/inversions.py)
* [Kth Order Statistic](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_subarray_sum.py)
* [Mergesort](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/mergesort.py)
* [Peak](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/peak.py)
* [Power](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/abbreviation.py)
* [Bitmask](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/bitmask.py)
* [Catalan Numbers](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/climbing_stairs.py)
* [Edit Distance](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py)
* [Factorial](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/factorial.py)
* [Fast Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fast_fibonacci.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fibonacci.py)
* [Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/iterating_through_submasks.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/knapsack.py)
* [Longest Common Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](https://github.com/TheAlgorithms/Python/blob/master/electronics/carrier_concentration.py)
* [Coulombs Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/coulombs_law.py)
* [Electric Power](https://github.com/TheAlgorithms/Python/blob/master/electronics/electric_power.py)
* [Ohms Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/ohms_law.py)
## File Transfer
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
* Tests
* [Test Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/tests/test_send_file.py)
## Fractals
* [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py)
* [Koch Snowflake](https://github.com/TheAlgorithms/Python/blob/master/fractals/koch_snowflake.py)
* [Mandelbrot](https://github.com/TheAlgorithms/Python/blob/master/fractals/mandelbrot.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](https://github.com/TheAlgorithms/Python/blob/master/fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](https://github.com/TheAlgorithms/Python/blob/master/graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](https://github.com/TheAlgorithms/Python/blob/master/graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/a_star.py)
* [Articulation Points](https://github.com/TheAlgorithms/Python/blob/master/graphs/articulation_points.py)
* [Basic Graphs](https://github.com/TheAlgorithms/Python/blob/master/graphs/basic_graphs.py)
* [Bellman Ford](https://github.com/TheAlgorithms/Python/blob/master/graphs/bellman_ford.py)
* [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_breadth_first_search.py)
* [Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/boruvka.py)
* [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
* [Breadth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
* [Check Cycle](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_cycle.py)
* [Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/connected_components.py)
* [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
* [Depth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search_2.py)
* [Dijkstra](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra.py)
* [Dijkstra 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_2.py)
* [Dijkstra Algorithm](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_algorithm.py)
* [Dinic](https://github.com/TheAlgorithms/Python/blob/master/graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](https://github.com/TheAlgorithms/Python/blob/master/graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](https://github.com/TheAlgorithms/Python/blob/master/graphs/even_tree.py)
* [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py)
* [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py)
* [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py)
* [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py)
* [Greedy Best First](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
* [Karger](https://github.com/TheAlgorithms/Python/blob/master/graphs/karger.py)
* [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/graphs/markov_chain.py)
* [Matching Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/matching_min_vertex_cover.py)
* [Minimum Spanning Tree Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
* [Strongly Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/strongly_connected_components.py)
* [Tarjans Scc](https://github.com/TheAlgorithms/Python/blob/master/graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](https://github.com/TheAlgorithms/Python/blob/master/greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](https://github.com/TheAlgorithms/Python/blob/master/hashes/adler32.py)
* [Chaos Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/chaos_machine.py)
* [Djb2](https://github.com/TheAlgorithms/Python/blob/master/hashes/djb2.py)
* [Enigma Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/enigma_machine.py)
* [Hamming Code](https://github.com/TheAlgorithms/Python/blob/master/hashes/hamming_code.py)
* [Luhn](https://github.com/TheAlgorithms/Python/blob/master/hashes/luhn.py)
* [Md5](https://github.com/TheAlgorithms/Python/blob/master/hashes/md5.py)
* [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py)
* [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py)
* [Sha256](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha256.py)
## Knapsack
* [Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/greedy_knapsack.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/conjugate_gradient.py)
* [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py)
* [Polynom For Points](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/polynom_for_points.py)
* [Power Iteration](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/astar.py)
* [Data Transformations](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/data_transformations.py)
* [Decision Tree](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/decision_tree.py)
* Forecasting
* [Run](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_descent.py)
* [K Means Clust](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_means_clust.py)
* [K Nearest Neighbours](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_regression.py)
* [Logistic Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/polymonial_regression.py)
* [Random Forest Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_regressor.py)
* [Scoring Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/similarity_search.py)
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
* [Word Frequency Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)
* [Add](https://github.com/TheAlgorithms/Python/blob/master/maths/add.py)
* [Aliquot Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/aliquot_sum.py)
* [Allocation Number](https://github.com/TheAlgorithms/Python/blob/master/maths/allocation_number.py)
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)
* [Bailey Borwein Plouffe](https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py)
* [Basic Maths](https://github.com/TheAlgorithms/Python/blob/master/maths/basic_maths.py)
* [Binary Exp Mod](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py)
* [Binary Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py)
* [Binary Exponentiation 2](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_3.py)
* [Binomial Coefficient](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_coefficient.py)
* [Binomial Distribution](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_distribution.py)
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/maths/bisection.py)
* [Ceil](https://github.com/TheAlgorithms/Python/blob/master/maths/ceil.py)
* [Check Polygon](https://github.com/TheAlgorithms/Python/blob/master/maths/check_polygon.py)
* [Chudnovsky Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/chudnovsky_algorithm.py)
* [Collatz Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/collatz_sequence.py)
* [Combinations](https://github.com/TheAlgorithms/Python/blob/master/maths/combinations.py)
* [Decimal Isolate](https://github.com/TheAlgorithms/Python/blob/master/maths/decimal_isolate.py)
* [Double Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_iterative.py)
* [Double Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_recursive.py)
* [Entropy](https://github.com/TheAlgorithms/Python/blob/master/maths/entropy.py)
* [Euclidean Distance](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_distance.py)
* [Euclidean Gcd](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_gcd.py)
* [Euler Method](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_method.py)
* [Euler Modified](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_modified.py)
* [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
* [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
* [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
* [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
* [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci.py)
* [Fibonacci Sequence Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci_sequence_recursion.py)
* [Find Max](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max.py)
* [Find Max Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max_recursion.py)
* [Find Min](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min.py)
* [Find Min Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min_recursion.py)
* [Floor](https://github.com/TheAlgorithms/Python/blob/master/maths/floor.py)
* [Gamma](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma.py)
* [Gamma Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma_recursive.py)
* [Gaussian](https://github.com/TheAlgorithms/Python/blob/master/maths/gaussian.py)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/Python/blob/master/maths/greatest_common_divisor.py)
* [Greedy Coin Change](https://github.com/TheAlgorithms/Python/blob/master/maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](https://github.com/TheAlgorithms/Python/blob/master/maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](https://github.com/TheAlgorithms/Python/blob/master/maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](https://github.com/TheAlgorithms/Python/blob/master/maths/is_ip_v4_address_valid.py)
* [Is Square Free](https://github.com/TheAlgorithms/Python/blob/master/maths/is_square_free.py)
* [Jaccard Similarity](https://github.com/TheAlgorithms/Python/blob/master/maths/jaccard_similarity.py)
* [Kadanes](https://github.com/TheAlgorithms/Python/blob/master/maths/kadanes.py)
* [Karatsuba](https://github.com/TheAlgorithms/Python/blob/master/maths/karatsuba.py)
* [Krishnamurthy Number](https://github.com/TheAlgorithms/Python/blob/master/maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](https://github.com/TheAlgorithms/Python/blob/master/maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_subarray_sum.py)
* [Least Common Multiple](https://github.com/TheAlgorithms/Python/blob/master/maths/least_common_multiple.py)
* [Line Length](https://github.com/TheAlgorithms/Python/blob/master/maths/line_length.py)
* [Lucas Lehmer Primality Test](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py)
* [Lucas Series](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_series.py)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/maths/median_of_two_arrays.py)
* [Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py)
* [Mobius Function](https://github.com/TheAlgorithms/Python/blob/master/maths/mobius_function.py)
* [Modular Exponential](https://github.com/TheAlgorithms/Python/blob/master/maths/modular_exponential.py)
* [Monte Carlo](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo.py)
* [Monte Carlo Dice](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo_dice.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/maths/newton_raphson.py)
* [Number Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/number_of_digits.py)
* [Numerical Integration](https://github.com/TheAlgorithms/Python/blob/master/maths/numerical_integration.py)
* [Perfect Cube](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_cube.py)
* [Perfect Number](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_number.py)
* [Perfect Square](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_square.py)
* [Pi Monte Carlo Estimation](https://github.com/TheAlgorithms/Python/blob/master/maths/pi_monte_carlo_estimation.py)
* [Polynomial Evaluation](https://github.com/TheAlgorithms/Python/blob/master/maths/polynomial_evaluation.py)
* [Power Using Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/power_using_recursion.py)
* [Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py)
* [Prime Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py)
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_sieve_eratosthenes.py)
* [Primelib](https://github.com/TheAlgorithms/Python/blob/master/maths/primelib.py)
* [Proth Number](https://github.com/TheAlgorithms/Python/blob/master/maths/proth_number.py)
* [Pythagoras](https://github.com/TheAlgorithms/Python/blob/master/maths/pythagoras.py)
* [Qr Decomposition](https://github.com/TheAlgorithms/Python/blob/master/maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/quadratic_equations_complex_numbers.py)
* [Radians](https://github.com/TheAlgorithms/Python/blob/master/maths/radians.py)
* [Radix2 Fft](https://github.com/TheAlgorithms/Python/blob/master/maths/radix2_fft.py)
* [Relu](https://github.com/TheAlgorithms/Python/blob/master/maths/relu.py)
* [Runge Kutta](https://github.com/TheAlgorithms/Python/blob/master/maths/runge_kutta.py)
* [Segmented Sieve](https://github.com/TheAlgorithms/Python/blob/master/maths/segmented_sieve.py)
* Series
* [Arithmetic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic.py)
* [Geometric](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric.py)
* [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.py)
* [Harmonic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic.py)
* [Harmonic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic_series.py)
* [P Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/p_series.py)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/sieve_of_eratosthenes.py)
* [Sigmoid](https://github.com/TheAlgorithms/Python/blob/master/maths/sigmoid.py)
* [Simpson Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/simpson_rule.py)
* [Softmax](https://github.com/TheAlgorithms/Python/blob/master/maths/softmax.py)
* [Square Root](https://github.com/TheAlgorithms/Python/blob/master/maths/square_root.py)
* [Sum Of Arithmetic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_digits.py)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/sylvester_sequence.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/maths/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/two_sum.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/inverse_of_matrix.py)
* [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py)
* [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](https://github.com/TheAlgorithms/Python/blob/master/matrix/sherman_morrison.py)
* [Spiral Print](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py)
* [Minimum Cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/convolution_neural_network.py)
* [Perceptron](https://github.com/TheAlgorithms/Python/blob/master/neural_network/perceptron.py)
## Other
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
* [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
* [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
* [Gauss Easter](https://github.com/TheAlgorithms/Python/blob/master/other/gauss_easter.py)
* [Graham Scan](https://github.com/TheAlgorithms/Python/blob/master/other/graham_scan.py)
* [Greedy](https://github.com/TheAlgorithms/Python/blob/master/other/greedy.py)
* [Least Recently Used](https://github.com/TheAlgorithms/Python/blob/master/other/least_recently_used.py)
* [Lfu Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lfu_cache.py)
* [Linear Congruential Generator](https://github.com/TheAlgorithms/Python/blob/master/other/linear_congruential_generator.py)
* [Lru Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lru_cache.py)
* [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py)
* [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py)
* [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py)
* [Scoring Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/scoring_algorithm.py)
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
## Physics
* [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py)
## Project Euler
* Problem 001
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol5.py)
* [Sol6](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol6.py)
* [Sol7](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/sol1.py)
* [Test Poker Hand](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
* Problem 069
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_077/sol1.py)
* Problem 080
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_102/sol1.py)
* Problem 107
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_107/sol1.py)
* Problem 109
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_109/sol1.py)
* Problem 112
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_112/sol1.py)
* Problem 113
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_113/sol1.py)
* Problem 119
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_203/sol1.py)
* Problem 206
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_301/sol1.py)
* Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
## Quantum
* [Deutsch Jozsa](https://github.com/TheAlgorithms/Python/blob/master/quantum/deutsch_jozsa.py)
* [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
* [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
* [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
* [Ripple Adder Classic](https://github.com/TheAlgorithms/Python/blob/master/quantum/ripple_adder_classic.py)
* [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](https://github.com/TheAlgorithms/Python/blob/master/scheduling/first_come_first_served.py)
* [Round Robin](https://github.com/TheAlgorithms/Python/blob/master/scheduling/round_robin.py)
* [Shortest Job First](https://github.com/TheAlgorithms/Python/blob/master/scheduling/shortest_job_first.py)
## Searches
* [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py)
* [Binary Tree Traversal](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_tree_traversal.py)
* [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py)
* [Double Linear Search Recursion](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search_recursion.py)
* [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py)
* [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py)
* [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py)
* [Jump Search](https://github.com/TheAlgorithms/Python/blob/master/searches/jump_search.py)
* [Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/linear_search.py)
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
* [Simple Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple_binary_search.py)
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
## Sorts
* [Bead Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bead_sort.py)
* [Bitonic Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bitonic_sort.py)
* [Bogo Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bogo_sort.py)
* [Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py)
* [Bucket Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bucket_sort.py)
* [Cocktail Shaker Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py)
* [Comb Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/comb_sort.py)
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
* [Heap Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/heap_sort.py)
* [Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/insertion_sort.py)
* [Intro Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/intro_sort.py)
* [Iterative Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/iterative_merge_sort.py)
* [Merge Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_insertion_sort.py)
* [Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_sort.py)
* [Msd Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/msd_radix_sort.py)
* [Natural Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/natural_sort.py)
* [Odd Even Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_sort.py)
* [Odd Even Transposition Parallel](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_parallel.py)
* [Odd Even Transposition Single Threaded](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_single_threaded.py)
* [Pancake Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pancake_sort.py)
* [Patience Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/patience_sort.py)
* [Pigeon Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeon_sort.py)
* [Pigeonhole Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeonhole_sort.py)
* [Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py)
* [Quick Sort 3 Partition](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort_3_partition.py)
* [Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/radix_sort.py)
* [Random Normal Distribution Quicksort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_normal_distribution_quicksort.py)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_pivot_quick_sort.py)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_bubble_sort.py)
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Recursive Mergesort Array](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_mergesort_array.py)
* [Recursive Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_quick_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Slowsort](https://github.com/TheAlgorithms/Python/blob/master/sorts/slowsort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
* [Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/topological_sort.py)
* [Tree Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tree_sort.py)
* [Unknown Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/unknown_sort.py)
* [Wiggle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/wiggle_sort.py)
## Strings
* [Aho Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho_corasick.py)
* [Alternative String Arrange](https://github.com/TheAlgorithms/Python/blob/master/strings/alternative_string_arrange.py)
* [Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/anagrams.py)
* [Autocomplete Using Trie](https://github.com/TheAlgorithms/Python/blob/master/strings/autocomplete_using_trie.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Can String Be Rearranged As Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Detecting English Programmatically](https://github.com/TheAlgorithms/Python/blob/master/strings/detecting_english_programmatically.py)
* [Frequency Finder](https://github.com/TheAlgorithms/Python/blob/master/strings/frequency_finder.py)
* [Indian Phone Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/indian_phone_validator.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
* [Jaro Winkler](https://github.com/TheAlgorithms/Python/blob/master/strings/jaro_winkler.py)
* [Join](https://github.com/TheAlgorithms/Python/blob/master/strings/join.py)
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/Python/blob/master/strings/knuth_morris_pratt.py)
* [Levenshtein Distance](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py)
* [Lower](https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py)
* [Manacher](https://github.com/TheAlgorithms/Python/blob/master/strings/manacher.py)
* [Min Cost String Conversion](https://github.com/TheAlgorithms/Python/blob/master/strings/min_cost_string_conversion.py)
* [Naive String Search](https://github.com/TheAlgorithms/Python/blob/master/strings/naive_string_search.py)
* [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/palindrome.py)
* [Prefix Function](https://github.com/TheAlgorithms/Python/blob/master/strings/prefix_function.py)
* [Rabin Karp](https://github.com/TheAlgorithms/Python/blob/master/strings/rabin_karp.py)
* [Remove Duplicate](https://github.com/TheAlgorithms/Python/blob/master/strings/remove_duplicate.py)
* [Reverse Letters](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_letters.py)
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
* [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
* [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
## Web Programming
* [Co2 Emission](https://github.com/TheAlgorithms/Python/blob/master/web_programming/co2_emission.py)
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
* [Download Images From Google Query](https://github.com/TheAlgorithms/Python/blob/master/web_programming/download_images_from_google_query.py)
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Giphy](https://github.com/TheAlgorithms/Python/blob/master/web_programming/giphy.py)
* [Instagram Crawler](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_crawler.py)
* [Instagram Pic](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_pic.py)
* [Instagram Video](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_video.py)
* [Nasa Data](https://github.com/TheAlgorithms/Python/blob/master/web_programming/nasa_data.py)
* [Random Anime Character](https://github.com/TheAlgorithms/Python/blob/master/web_programming/random_anime_character.py)
* [Recaptcha Verification](https://github.com/TheAlgorithms/Python/blob/master/web_programming/recaptcha_verification.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)
* [Test Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/test_fetch_github_info.py)
* [World Covid19 Stats](https://github.com/TheAlgorithms/Python/blob/master/web_programming/world_covid19_stats.py)
| 1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The Mandelbrot set is the set of complex numbers "c" for which the series
"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
complex number "c" is a member of the Mandelbrot set if, when starting with
"z_0 = 0" and applying the iteration repeatedly, the absolute value of
"z_n" remains bounded for all "n > 0". Complex numbers can be written as
"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
is the imaginary component, usually drawn on the y-axis. Most visualizations
of the Mandelbrot set use a color-coding to indicate after how many steps in
the series the numbers outside the set diverge. Images of the Mandelbrot set
exhibit an elaborate and infinitely complicated boundary that reveals
progressively ever-finer recursive detail at increasing magnifications, making
the boundary of the Mandelbrot set a fractal curve.
(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set )
(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set )
"""
import colorsys
from PIL import Image # type: ignore
def get_distance(x: float, y: float, max_step: int) -> float:
"""
Return the relative distance (= step/max_step) after which the complex number
constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
diverge so their distance is 1.
>>> get_distance(0, 0, 50)
1.0
>>> get_distance(0.5, 0.5, 50)
0.061224489795918366
>>> get_distance(2, 0, 50)
0.0
"""
a = x
b = y
for step in range(max_step):
a_new = a * a - b * b + x
b = 2 * a * b + y
a = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def get_black_and_white_rgb(distance: float) -> tuple:
"""
Black&white color-coding that ignores the relative distance. The Mandelbrot
set is black, everything else is white.
>>> get_black_and_white_rgb(0)
(255, 255, 255)
>>> get_black_and_white_rgb(0.5)
(255, 255, 255)
>>> get_black_and_white_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def get_color_coded_rgb(distance: float) -> tuple:
"""
Color-coding taking the relative distance into account. The Mandelbrot set
is black.
>>> get_color_coded_rgb(0)
(255, 0, 0)
>>> get_color_coded_rgb(0.5)
(0, 255, 255)
>>> get_color_coded_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))
def get_image(
image_width: int = 800,
image_height: int = 600,
figure_center_x: float = -0.6,
figure_center_y: float = 0,
figure_width: float = 3.2,
max_step: int = 50,
use_distance_color_coding: bool = True,
) -> Image.Image:
"""
Function to generate the image of the Mandelbrot set. Two types of coordinates
are used: image-coordinates that refer to the pixels and figure-coordinates
that refer to the complex numbers inside and outside the Mandelbrot set. The
figure-coordinates in the arguments of this function determine which section
of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.
>>> get_image().load()[0,0]
(255, 0, 0)
>>> get_image(use_distance_color_coding = False).load()[0,0]
(255, 255, 255)
"""
img = Image.new("RGB", (image_width, image_height))
pixels = img.load()
# loop through the image-coordinates
for image_x in range(image_width):
for image_y in range(image_height):
# determine the figure-coordinates based on the image-coordinates
figure_height = figure_width / image_width * image_height
figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width
figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height
distance = get_distance(figure_x, figure_y, max_step)
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
pixels[image_x, image_y] = get_color_coded_rgb(distance)
else:
pixels[image_x, image_y] = get_black_and_white_rgb(distance)
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
img = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| """
The Mandelbrot set is the set of complex numbers "c" for which the series
"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
complex number "c" is a member of the Mandelbrot set if, when starting with
"z_0 = 0" and applying the iteration repeatedly, the absolute value of
"z_n" remains bounded for all "n > 0". Complex numbers can be written as
"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
is the imaginary component, usually drawn on the y-axis. Most visualizations
of the Mandelbrot set use a color-coding to indicate after how many steps in
the series the numbers outside the set diverge. Images of the Mandelbrot set
exhibit an elaborate and infinitely complicated boundary that reveals
progressively ever-finer recursive detail at increasing magnifications, making
the boundary of the Mandelbrot set a fractal curve.
(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set )
(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set )
"""
import colorsys
from PIL import Image # type: ignore
def get_distance(x: float, y: float, max_step: int) -> float:
"""
Return the relative distance (= step/max_step) after which the complex number
constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
diverge so their distance is 1.
>>> get_distance(0, 0, 50)
1.0
>>> get_distance(0.5, 0.5, 50)
0.061224489795918366
>>> get_distance(2, 0, 50)
0.0
"""
a = x
b = y
for step in range(max_step):
a_new = a * a - b * b + x
b = 2 * a * b + y
a = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def get_black_and_white_rgb(distance: float) -> tuple:
"""
Black&white color-coding that ignores the relative distance. The Mandelbrot
set is black, everything else is white.
>>> get_black_and_white_rgb(0)
(255, 255, 255)
>>> get_black_and_white_rgb(0.5)
(255, 255, 255)
>>> get_black_and_white_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def get_color_coded_rgb(distance: float) -> tuple:
"""
Color-coding taking the relative distance into account. The Mandelbrot set
is black.
>>> get_color_coded_rgb(0)
(255, 0, 0)
>>> get_color_coded_rgb(0.5)
(0, 255, 255)
>>> get_color_coded_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))
def get_image(
image_width: int = 800,
image_height: int = 600,
figure_center_x: float = -0.6,
figure_center_y: float = 0,
figure_width: float = 3.2,
max_step: int = 50,
use_distance_color_coding: bool = True,
) -> Image.Image:
"""
Function to generate the image of the Mandelbrot set. Two types of coordinates
are used: image-coordinates that refer to the pixels and figure-coordinates
that refer to the complex numbers inside and outside the Mandelbrot set. The
figure-coordinates in the arguments of this function determine which section
of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.
Commenting out tests that slow down pytest...
# 13.35s call fractals/mandelbrot.py::mandelbrot.get_image
# >>> get_image().load()[0,0]
(255, 0, 0)
# >>> get_image(use_distance_color_coding = False).load()[0,0]
(255, 255, 255)
"""
img = Image.new("RGB", (image_width, image_height))
pixels = img.load()
# loop through the image-coordinates
for image_x in range(image_width):
for image_y in range(image_height):
# determine the figure-coordinates based on the image-coordinates
figure_height = figure_width / image_width * image_height
figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width
figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height
distance = get_distance(figure_x, figure_y, max_step)
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
pixels[image_x, image_y] = get_color_coded_rgb(distance)
else:
pixels[image_x, image_y] = get_black_and_white_rgb(distance)
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
img = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| 1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/Bidirectional_search
"""
from __future__ import annotations
import time
Path = list[tuple[int, int]]
grid = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class Node:
def __init__(
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None
):
self.pos_x = pos_x
self.pos_y = pos_y
self.pos = (pos_y, pos_x)
self.goal_x = goal_x
self.goal_y = goal_y
self.parent = parent
class BreadthFirstSearch:
"""
>>> bfs = BreadthFirstSearch((0, 0), (len(grid) - 1, len(grid[0]) - 1))
>>> (bfs.start.pos_y + delta[3][0], bfs.start.pos_x + delta[3][1])
(0, 1)
>>> [x.pos for x in bfs.get_successors(bfs.start)]
[(1, 0), (0, 1)]
>>> (bfs.start.pos_y + delta[2][0], bfs.start.pos_x + delta[2][1])
(1, 0)
>>> bfs.retrace_path(bfs.start)
[(0, 0)]
>>> bfs.search() # doctest: +NORMALIZE_WHITESPACE
[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
"""
def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
self.start = Node(start[1], start[0], goal[1], goal[0], None)
self.target = Node(goal[1], goal[0], goal[1], goal[0], None)
self.node_queue = [self.start]
self.reached = False
def search(self) -> Path | None:
while self.node_queue:
current_node = self.node_queue.pop(0)
if current_node.pos == self.target.pos:
self.reached = True
return self.retrace_path(current_node)
successors = self.get_successors(current_node)
for node in successors:
self.node_queue.append(node)
if not self.reached:
return [self.start.pos]
return None
def get_successors(self, parent: Node) -> list[Node]:
"""
Returns a list of successors (both in the grid and free spaces)
"""
successors = []
for action in delta:
pos_x = parent.pos_x + action[1]
pos_y = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent)
)
return successors
def retrace_path(self, node: Node | None) -> Path:
"""
Retrace the path from parents to parents until start node
"""
current_node = node
path = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x))
current_node = current_node.parent
path.reverse()
return path
class BidirectionalBreadthFirstSearch:
"""
>>> bd_bfs = BidirectionalBreadthFirstSearch((0, 0), (len(grid) - 1,
... len(grid[0]) - 1))
>>> bd_bfs.fwd_bfs.start.pos == bd_bfs.bwd_bfs.target.pos
True
>>> bd_bfs.retrace_bidirectional_path(bd_bfs.fwd_bfs.start,
... bd_bfs.bwd_bfs.start)
[(0, 0)]
>>> bd_bfs.search() # doctest: +NORMALIZE_WHITESPACE
[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3),
(2, 4), (3, 4), (3, 5), (3, 6), (4, 6), (5, 6), (6, 6)]
"""
def __init__(self, start, goal):
self.fwd_bfs = BreadthFirstSearch(start, goal)
self.bwd_bfs = BreadthFirstSearch(goal, start)
self.reached = False
def search(self) -> Path | None:
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
current_fwd_node = self.fwd_bfs.node_queue.pop(0)
current_bwd_node = self.bwd_bfs.node_queue.pop(0)
if current_bwd_node.pos == current_fwd_node.pos:
self.reached = True
return self.retrace_bidirectional_path(
current_fwd_node, current_bwd_node
)
self.fwd_bfs.target = current_bwd_node
self.bwd_bfs.target = current_fwd_node
successors = {
self.fwd_bfs: self.fwd_bfs.get_successors(current_fwd_node),
self.bwd_bfs: self.bwd_bfs.get_successors(current_bwd_node),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(node)
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def retrace_bidirectional_path(self, fwd_node: Node, bwd_node: Node) -> Path:
fwd_path = self.fwd_bfs.retrace_path(fwd_node)
bwd_path = self.bwd_bfs.retrace_path(bwd_node)
bwd_path.pop()
bwd_path.reverse()
path = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
init = (0, 0)
goal = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
start_bfs_time = time.time()
bfs = BreadthFirstSearch(init, goal)
path = bfs.search()
bfs_time = time.time() - start_bfs_time
print("Unidirectional BFS computation time : ", bfs_time)
start_bd_bfs_time = time.time()
bd_bfs = BidirectionalBreadthFirstSearch(init, goal)
bd_path = bd_bfs.search()
bd_bfs_time = time.time() - start_bd_bfs_time
print("Bidirectional BFS computation time : ", bd_bfs_time)
| """
https://en.wikipedia.org/wiki/Bidirectional_search
"""
from __future__ import annotations
import time
Path = list[tuple[int, int]]
grid = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class Node:
def __init__(
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None
):
self.pos_x = pos_x
self.pos_y = pos_y
self.pos = (pos_y, pos_x)
self.goal_x = goal_x
self.goal_y = goal_y
self.parent = parent
class BreadthFirstSearch:
"""
# Comment out slow pytests...
# 9.15s call graphs/bidirectional_breadth_first_search.py:: \
# graphs.bidirectional_breadth_first_search.BreadthFirstSearch
# >>> bfs = BreadthFirstSearch((0, 0), (len(grid) - 1, len(grid[0]) - 1))
# >>> (bfs.start.pos_y + delta[3][0], bfs.start.pos_x + delta[3][1])
(0, 1)
# >>> [x.pos for x in bfs.get_successors(bfs.start)]
[(1, 0), (0, 1)]
# >>> (bfs.start.pos_y + delta[2][0], bfs.start.pos_x + delta[2][1])
(1, 0)
# >>> bfs.retrace_path(bfs.start)
[(0, 0)]
# >>> bfs.search() # doctest: +NORMALIZE_WHITESPACE
[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
"""
def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
self.start = Node(start[1], start[0], goal[1], goal[0], None)
self.target = Node(goal[1], goal[0], goal[1], goal[0], None)
self.node_queue = [self.start]
self.reached = False
def search(self) -> Path | None:
while self.node_queue:
current_node = self.node_queue.pop(0)
if current_node.pos == self.target.pos:
self.reached = True
return self.retrace_path(current_node)
successors = self.get_successors(current_node)
for node in successors:
self.node_queue.append(node)
if not self.reached:
return [self.start.pos]
return None
def get_successors(self, parent: Node) -> list[Node]:
"""
Returns a list of successors (both in the grid and free spaces)
"""
successors = []
for action in delta:
pos_x = parent.pos_x + action[1]
pos_y = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent)
)
return successors
def retrace_path(self, node: Node | None) -> Path:
"""
Retrace the path from parents to parents until start node
"""
current_node = node
path = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x))
current_node = current_node.parent
path.reverse()
return path
class BidirectionalBreadthFirstSearch:
"""
>>> bd_bfs = BidirectionalBreadthFirstSearch((0, 0), (len(grid) - 1,
... len(grid[0]) - 1))
>>> bd_bfs.fwd_bfs.start.pos == bd_bfs.bwd_bfs.target.pos
True
>>> bd_bfs.retrace_bidirectional_path(bd_bfs.fwd_bfs.start,
... bd_bfs.bwd_bfs.start)
[(0, 0)]
>>> bd_bfs.search() # doctest: +NORMALIZE_WHITESPACE
[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3),
(2, 4), (3, 4), (3, 5), (3, 6), (4, 6), (5, 6), (6, 6)]
"""
def __init__(self, start, goal):
self.fwd_bfs = BreadthFirstSearch(start, goal)
self.bwd_bfs = BreadthFirstSearch(goal, start)
self.reached = False
def search(self) -> Path | None:
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
current_fwd_node = self.fwd_bfs.node_queue.pop(0)
current_bwd_node = self.bwd_bfs.node_queue.pop(0)
if current_bwd_node.pos == current_fwd_node.pos:
self.reached = True
return self.retrace_bidirectional_path(
current_fwd_node, current_bwd_node
)
self.fwd_bfs.target = current_bwd_node
self.bwd_bfs.target = current_fwd_node
successors = {
self.fwd_bfs: self.fwd_bfs.get_successors(current_fwd_node),
self.bwd_bfs: self.bwd_bfs.get_successors(current_bwd_node),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(node)
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def retrace_bidirectional_path(self, fwd_node: Node, bwd_node: Node) -> Path:
fwd_path = self.fwd_bfs.retrace_path(fwd_node)
bwd_path = self.bwd_bfs.retrace_path(bwd_node)
bwd_path.pop()
bwd_path.reverse()
path = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
init = (0, 0)
goal = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
start_bfs_time = time.time()
bfs = BreadthFirstSearch(init, goal)
path = bfs.search()
bfs_time = time.time() - start_bfs_time
print("Unidirectional BFS computation time : ", bfs_time)
start_bd_bfs_time = time.time()
bd_bfs = BidirectionalBreadthFirstSearch(init, goal)
bd_path = bd_bfs.search()
bd_bfs_time = time.time() - start_bd_bfs_time
print("Bidirectional BFS computation time : ", bd_bfs_time)
| 1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import random
from .binary_exp_mod import bin_exp_mod
# This is a probabilistic check to test primality, useful for big numbers!
# if it's a prime, it will return true
# if it's not a prime, the chance of it returning true is at most 1/4**prec
def is_prime(n, prec=1000):
"""
>>> from .prime_check import prime_check
>>> all(is_prime(i) == prime_check(i) for i in range(1000))
True
"""
if n < 2:
return False
if n % 2 == 0:
return n == 2
# this means n is odd
d = n - 1
exp = 0
while d % 2 == 0:
d /= 2
exp += 1
# n - 1=d*(2**exp)
count = 0
while count < prec:
a = random.randint(2, n - 1)
b = bin_exp_mod(a, d, n)
if b != 1:
flag = True
for i in range(exp):
if b == n - 1:
flag = False
break
b = b * b
b %= n
if flag:
return False
count += 1
return True
if __name__ == "__main__":
n = abs(int(input("Enter bound : ").strip()))
print("Here's the list of primes:")
print(", ".join(str(i) for i in range(n + 1) if is_prime(i)))
| import random
from .binary_exp_mod import bin_exp_mod
# This is a probabilistic check to test primality, useful for big numbers!
# if it's a prime, it will return true
# if it's not a prime, the chance of it returning true is at most 1/4**prec
def is_prime(n, prec=1000):
"""
>>> from .prime_check import prime_check
>>> # all(is_prime(i) == prime_check(i) for i in range(1000)) # 3.45s
>>> all(is_prime(i) == prime_check(i) for i in range(256))
True
"""
if n < 2:
return False
if n % 2 == 0:
return n == 2
# this means n is odd
d = n - 1
exp = 0
while d % 2 == 0:
d /= 2
exp += 1
# n - 1=d*(2**exp)
count = 0
while count < prec:
a = random.randint(2, n - 1)
b = bin_exp_mod(a, d, n)
if b != 1:
flag = True
for i in range(exp):
if b == n - 1:
flag = False
break
b = b * b
b %= n
if flag:
return False
count += 1
return True
if __name__ == "__main__":
n = abs(int(input("Enter bound : ").strip()))
print("Here's the list of primes:")
print(", ".join(str(i) for i in range(n + 1) if is_prime(i)))
| 1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import json
import os
import re
import sys
import urllib.request
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int:
"""Searches google using the provided query term and downloads the images in a folder.
Args:
query : The image search term to be provided by the user. Defaults to
"dhaka".
image_numbers : [description]. Defaults to 5.
Returns:
The number of images successfully downloaded.
>>> download_images_from_google_query()
5
>>> download_images_from_google_query("potato")
5
"""
max_images = min(max_images, 50) # Prevent abuse!
params = {
"q": query,
"tbm": "isch",
"hl": "en",
"ijn": "0",
}
html = requests.get("https://www.google.com/search", params=params, headers=headers)
soup = BeautifulSoup(html.text, "html.parser")
matched_images_data = "".join(
re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script")))
)
matched_images_data_fix = json.dumps(matched_images_data)
matched_images_data_json = json.loads(matched_images_data_fix)
matched_google_image_data = re.findall(
r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",",
matched_images_data_json,
)
if not matched_google_image_data:
return 0
removed_matched_google_images_thumbnails = re.sub(
r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]",
"",
str(matched_google_image_data),
)
matched_google_full_resolution_images = re.findall(
r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]",
removed_matched_google_images_thumbnails,
)
for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images):
if index >= max_images:
return index
original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode(
"unicode-escape"
)
original_size_img = bytes(original_size_img_not_fixed, "ascii").decode(
"unicode-escape"
)
opener = urllib.request.build_opener()
opener.addheaders = [
(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582",
)
]
urllib.request.install_opener(opener)
path_name = f"query_{query.replace(' ', '_')}"
if not os.path.exists(path_name):
os.makedirs(path_name)
urllib.request.urlretrieve(
original_size_img, f"{path_name}/original_size_img_{index}.jpg"
)
return index
if __name__ == "__main__":
try:
image_count = download_images_from_google_query(sys.argv[1])
print(f"{image_count} images were downloaded to disk.")
except IndexError:
print("Please provide a search term.")
raise
| import json
import os
import re
import sys
import urllib.request
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int:
"""Searches google using the provided query term and downloads the images in a folder.
Args:
query : The image search term to be provided by the user. Defaults to
"dhaka".
image_numbers : [description]. Defaults to 5.
Returns:
The number of images successfully downloaded.
# Comment out slow (4.20s call) doctests
# >>> download_images_from_google_query()
5
# >>> download_images_from_google_query("potato")
5
"""
max_images = min(max_images, 50) # Prevent abuse!
params = {
"q": query,
"tbm": "isch",
"hl": "en",
"ijn": "0",
}
html = requests.get("https://www.google.com/search", params=params, headers=headers)
soup = BeautifulSoup(html.text, "html.parser")
matched_images_data = "".join(
re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script")))
)
matched_images_data_fix = json.dumps(matched_images_data)
matched_images_data_json = json.loads(matched_images_data_fix)
matched_google_image_data = re.findall(
r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",",
matched_images_data_json,
)
if not matched_google_image_data:
return 0
removed_matched_google_images_thumbnails = re.sub(
r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]",
"",
str(matched_google_image_data),
)
matched_google_full_resolution_images = re.findall(
r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]",
removed_matched_google_images_thumbnails,
)
for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images):
if index >= max_images:
return index
original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode(
"unicode-escape"
)
original_size_img = bytes(original_size_img_not_fixed, "ascii").decode(
"unicode-escape"
)
opener = urllib.request.build_opener()
opener.addheaders = [
(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582",
)
]
urllib.request.install_opener(opener)
path_name = f"query_{query.replace(' ', '_')}"
if not os.path.exists(path_name):
os.makedirs(path_name)
urllib.request.urlretrieve(
original_size_img, f"{path_name}/original_size_img_{index}.jpg"
)
return index
if __name__ == "__main__":
try:
image_count = download_images_from_google_query(sys.argv[1])
print(f"{image_count} images were downloaded to disk.")
except IndexError:
print("Please provide a search term.")
raise
| 1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
from __future__ import annotations
import random
from typing import Generic, Iterable, TypeVar
T = TypeVar("T")
class RandomizedHeapNode(Generic[T]):
"""
One node of the randomized heap. Contains the value and references to
two children.
"""
def __init__(self, value: T) -> None:
self._value: T = value
self.left: RandomizedHeapNode[T] | None = None
self.right: RandomizedHeapNode[T] | None = None
@property
def value(self) -> T:
"""Return the value of the node."""
return self._value
@staticmethod
def merge(
root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None
) -> RandomizedHeapNode[T] | None:
"""Merge 2 nodes together."""
if not root1:
return root2
if not root2:
return root1
if root1.value > root2.value:
root1, root2 = root2, root1
if random.choice([True, False]):
root1.left, root1.right = root1.right, root1.left
root1.left = RandomizedHeapNode.merge(root1.left, root2)
return root1
class RandomizedHeap(Generic[T]):
"""
A data structure that allows inserting a new value and to pop the smallest
values. Both operations take O(logN) time where N is the size of the
structure.
Wiki: https://en.wikipedia.org/wiki/Randomized_meldable_heap
>>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list()
[1, 1, 2, 3, 5, 7]
>>> rh = RandomizedHeap()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
>>> rh.insert(1)
>>> rh.insert(-1)
>>> rh.insert(0)
>>> rh.to_sorted_list()
[-1, 0, 1]
"""
def __init__(self, data: Iterable[T] | None = ()) -> None:
"""
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
self._root: RandomizedHeapNode[T] | None = None
for item in data:
self.insert(item)
def insert(self, value: T) -> None:
"""
Insert the value into the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.insert(1)
>>> rh.insert(3)
>>> rh.insert(7)
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value))
def pop(self) -> T:
"""
Pop the smallest value from the heap and return it.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.pop()
1
>>> rh.pop()
3
>>> rh.pop()
3
>>> rh.pop()
7
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
result = self.top()
self._root = RandomizedHeapNode.merge(self._root.left, self._root.right)
return result
def top(self) -> T:
"""
Return the smallest value from the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.top()
3
>>> rh.insert(1)
>>> rh.top()
1
>>> rh.insert(3)
>>> rh.top()
1
>>> rh.insert(7)
>>> rh.top()
1
"""
if not self._root:
raise IndexError("Can't get top element for the empty heap.")
return self._root.value
def clear(self):
"""
Clear the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.clear()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
self._root = None
def to_sorted_list(self) -> list[T]:
"""
Returns sorted list containing all the values in the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
result = []
while self:
result.append(self.pop())
return result
def __bool__(self) -> bool:
"""
Check if the heap is not empty.
>>> rh = RandomizedHeap()
>>> bool(rh)
False
>>> rh.insert(1)
>>> bool(rh)
True
>>> rh.clear()
>>> bool(rh)
False
"""
return self._root is not None
if __name__ == "__main__":
import doctest
doctest.testmod()
| #!/usr/bin/env python3
from __future__ import annotations
import random
from typing import Generic, Iterable, TypeVar
T = TypeVar("T")
class RandomizedHeapNode(Generic[T]):
"""
One node of the randomized heap. Contains the value and references to
two children.
"""
def __init__(self, value: T) -> None:
self._value: T = value
self.left: RandomizedHeapNode[T] | None = None
self.right: RandomizedHeapNode[T] | None = None
@property
def value(self) -> T:
"""Return the value of the node."""
return self._value
@staticmethod
def merge(
root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None
) -> RandomizedHeapNode[T] | None:
"""Merge 2 nodes together."""
if not root1:
return root2
if not root2:
return root1
if root1.value > root2.value:
root1, root2 = root2, root1
if random.choice([True, False]):
root1.left, root1.right = root1.right, root1.left
root1.left = RandomizedHeapNode.merge(root1.left, root2)
return root1
class RandomizedHeap(Generic[T]):
"""
A data structure that allows inserting a new value and to pop the smallest
values. Both operations take O(logN) time where N is the size of the
structure.
Wiki: https://en.wikipedia.org/wiki/Randomized_meldable_heap
>>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list()
[1, 1, 2, 3, 5, 7]
>>> rh = RandomizedHeap()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
>>> rh.insert(1)
>>> rh.insert(-1)
>>> rh.insert(0)
>>> rh.to_sorted_list()
[-1, 0, 1]
"""
def __init__(self, data: Iterable[T] | None = ()) -> None:
"""
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
self._root: RandomizedHeapNode[T] | None = None
for item in data:
self.insert(item)
def insert(self, value: T) -> None:
"""
Insert the value into the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.insert(1)
>>> rh.insert(3)
>>> rh.insert(7)
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value))
def pop(self) -> T:
"""
Pop the smallest value from the heap and return it.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.pop()
1
>>> rh.pop()
3
>>> rh.pop()
3
>>> rh.pop()
7
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
result = self.top()
self._root = RandomizedHeapNode.merge(self._root.left, self._root.right)
return result
def top(self) -> T:
"""
Return the smallest value from the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.top()
3
>>> rh.insert(1)
>>> rh.top()
1
>>> rh.insert(3)
>>> rh.top()
1
>>> rh.insert(7)
>>> rh.top()
1
"""
if not self._root:
raise IndexError("Can't get top element for the empty heap.")
return self._root.value
def clear(self):
"""
Clear the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.clear()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
self._root = None
def to_sorted_list(self) -> list[T]:
"""
Returns sorted list containing all the values in the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
result = []
while self:
result.append(self.pop())
return result
def __bool__(self) -> bool:
"""
Check if the heap is not empty.
>>> rh = RandomizedHeap()
>>> bool(rh)
False
>>> rh.insert(1)
>>> bool(rh)
True
>>> rh.clear()
>>> bool(rh)
False
"""
return self._root is not None
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Convert a Decimal Number to an Octal Number."""
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
"""Convert a Decimal Number to an Octal Number.
>>> all(decimal_to_octal(i) == oct(i) for i
... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
True
"""
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.floor(math.pow(10, counter)))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f"0o{int(octal)}"
def main() -> None:
"""Print octal equivalents of decimal numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal is:")
print(decimal_to_octal(512)) # = 1000
print("\n")
if __name__ == "__main__":
main()
| """Convert a Decimal Number to an Octal Number."""
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
"""Convert a Decimal Number to an Octal Number.
>>> all(decimal_to_octal(i) == oct(i) for i
... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
True
"""
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.floor(math.pow(10, counter)))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f"0o{int(octal)}"
def main() -> None:
"""Print octal equivalents of decimal numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal is:")
print(decimal_to_octal(512)) # = 1000
print("\n")
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle
through a graph that visits each node exactly once.
Determining whether such paths and cycles exist in graphs
is the 'Hamiltonian path problem', which is NP-complete.
Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
"""
def valid_connection(
graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]
) -> bool:
"""
Checks whether it is possible to add next into path by validating 2 statements
1. There should be path between current and next vertex
2. Next vertex should not be in path
If both validations succeed we return True, saying that it is possible to connect
this vertices, otherwise we return False
Case 1:Use exact graph as in main function, with initialized values
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, -1, -1, -1, -1, 0]
>>> curr_ind = 1
>>> next_ver = 1
>>> valid_connection(graph, next_ver, curr_ind, path)
True
Case 2: Same graph, but trying to connect to node that is already in path
>>> path = [0, 1, 2, 4, -1, 0]
>>> curr_ind = 4
>>> next_ver = 1
>>> valid_connection(graph, next_ver, curr_ind, path)
False
"""
# 1. Validate that path exists between current and next vertices
if graph[path[curr_ind - 1]][next_ver] == 0:
return False
# 2. Validate that next vertex is not already in path
return not any(vertex == next_ver for vertex in path)
def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool:
"""
Pseudo-Code
Base Case:
1. Check if we visited all of vertices
1.1 If last visited vertex has path to starting vertex return True either
return False
Recursive Step:
2. Iterate over each vertex
Check if next vertex is valid for transiting from current vertex
2.1 Remember next vertex as next transition
2.2 Do recursive call and check if going to this vertex solves problem
2.3 If next vertex leads to solution return True
2.4 Else backtrack, delete remembered vertex
Case 1: Use exact graph as in main function, with initialized values
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, -1, -1, -1, -1, 0]
>>> curr_ind = 1
>>> util_hamilton_cycle(graph, path, curr_ind)
True
>>> print(path)
[0, 1, 2, 4, 3, 0]
Case 2: Use exact graph as in previous case, but in the properties taken from
middle of calculation
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, 1, 2, -1, -1, 0]
>>> curr_ind = 3
>>> util_hamilton_cycle(graph, path, curr_ind)
True
>>> print(path)
[0, 1, 2, 4, 3, 0]
"""
# Base Case
if curr_ind == len(graph):
# return whether path exists between current and starting vertices
return graph[path[curr_ind - 1]][path[0]] == 1
# Recursive Step
for next in range(0, len(graph)):
if valid_connection(graph, next, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next
# Validate created path
if util_hamilton_cycle(graph, path, curr_ind + 1):
return True
# Backtrack
path[curr_ind] = -1
return False
def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]:
r"""
Wrapper function to call subroutine called util_hamilton_cycle,
which will either return array of vertices indicating hamiltonian cycle
or an empty list indicating that hamiltonian cycle was not found.
Case 1:
Following graph consists of 5 edges.
If we look closely, we can see that there are multiple Hamiltonian cycles.
For example one result is when we iterate like:
(0)->(1)->(2)->(4)->(3)->(0)
(0)---(1)---(2)
| / \ |
| / \ |
| / \ |
|/ \|
(3)---------(4)
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> hamilton_cycle(graph)
[0, 1, 2, 4, 3, 0]
Case 2:
Same Graph as it was in Case 1, changed starting index from default to 3
(0)---(1)---(2)
| / \ |
| / \ |
| / \ |
|/ \|
(3)---------(4)
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> hamilton_cycle(graph, 3)
[3, 0, 1, 2, 4, 3]
Case 3:
Following Graph is exactly what it was before, but edge 3-4 is removed.
Result is that there is no Hamiltonian Cycle anymore.
(0)---(1)---(2)
| / \ |
| / \ |
| / \ |
|/ \|
(3) (4)
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 0],
... [0, 1, 1, 0, 0]]
>>> hamilton_cycle(graph,4)
[]
"""
# Initialize path with -1, indicating that we have not visited them yet
path = [-1] * (len(graph) + 1)
# initialize start and end of path with starting index
path[0] = path[-1] = start_index
# evaluate and if we find answer return path either return empty array
return path if util_hamilton_cycle(graph, path, 1) else []
| """
A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle
through a graph that visits each node exactly once.
Determining whether such paths and cycles exist in graphs
is the 'Hamiltonian path problem', which is NP-complete.
Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
"""
def valid_connection(
graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]
) -> bool:
"""
Checks whether it is possible to add next into path by validating 2 statements
1. There should be path between current and next vertex
2. Next vertex should not be in path
If both validations succeed we return True, saying that it is possible to connect
this vertices, otherwise we return False
Case 1:Use exact graph as in main function, with initialized values
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, -1, -1, -1, -1, 0]
>>> curr_ind = 1
>>> next_ver = 1
>>> valid_connection(graph, next_ver, curr_ind, path)
True
Case 2: Same graph, but trying to connect to node that is already in path
>>> path = [0, 1, 2, 4, -1, 0]
>>> curr_ind = 4
>>> next_ver = 1
>>> valid_connection(graph, next_ver, curr_ind, path)
False
"""
# 1. Validate that path exists between current and next vertices
if graph[path[curr_ind - 1]][next_ver] == 0:
return False
# 2. Validate that next vertex is not already in path
return not any(vertex == next_ver for vertex in path)
def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool:
"""
Pseudo-Code
Base Case:
1. Check if we visited all of vertices
1.1 If last visited vertex has path to starting vertex return True either
return False
Recursive Step:
2. Iterate over each vertex
Check if next vertex is valid for transiting from current vertex
2.1 Remember next vertex as next transition
2.2 Do recursive call and check if going to this vertex solves problem
2.3 If next vertex leads to solution return True
2.4 Else backtrack, delete remembered vertex
Case 1: Use exact graph as in main function, with initialized values
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, -1, -1, -1, -1, 0]
>>> curr_ind = 1
>>> util_hamilton_cycle(graph, path, curr_ind)
True
>>> print(path)
[0, 1, 2, 4, 3, 0]
Case 2: Use exact graph as in previous case, but in the properties taken from
middle of calculation
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, 1, 2, -1, -1, 0]
>>> curr_ind = 3
>>> util_hamilton_cycle(graph, path, curr_ind)
True
>>> print(path)
[0, 1, 2, 4, 3, 0]
"""
# Base Case
if curr_ind == len(graph):
# return whether path exists between current and starting vertices
return graph[path[curr_ind - 1]][path[0]] == 1
# Recursive Step
for next in range(0, len(graph)):
if valid_connection(graph, next, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next
# Validate created path
if util_hamilton_cycle(graph, path, curr_ind + 1):
return True
# Backtrack
path[curr_ind] = -1
return False
def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]:
r"""
Wrapper function to call subroutine called util_hamilton_cycle,
which will either return array of vertices indicating hamiltonian cycle
or an empty list indicating that hamiltonian cycle was not found.
Case 1:
Following graph consists of 5 edges.
If we look closely, we can see that there are multiple Hamiltonian cycles.
For example one result is when we iterate like:
(0)->(1)->(2)->(4)->(3)->(0)
(0)---(1)---(2)
| / \ |
| / \ |
| / \ |
|/ \|
(3)---------(4)
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> hamilton_cycle(graph)
[0, 1, 2, 4, 3, 0]
Case 2:
Same Graph as it was in Case 1, changed starting index from default to 3
(0)---(1)---(2)
| / \ |
| / \ |
| / \ |
|/ \|
(3)---------(4)
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> hamilton_cycle(graph, 3)
[3, 0, 1, 2, 4, 3]
Case 3:
Following Graph is exactly what it was before, but edge 3-4 is removed.
Result is that there is no Hamiltonian Cycle anymore.
(0)---(1)---(2)
| / \ |
| / \ |
| / \ |
|/ \|
(3) (4)
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 0],
... [0, 1, 1, 0, 0]]
>>> hamilton_cycle(graph,4)
[]
"""
# Initialize path with -1, indicating that we have not visited them yet
path = [-1] * (len(graph) + 1)
# initialize start and end of path with starting index
path[0] = path[-1] = start_index
# evaluate and if we find answer return path either return empty array
return path if util_hamilton_cycle(graph, path, 1) else []
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
def n31(a: int) -> tuple[list[int], int]:
"""
Returns the Collatz sequence and its length of any positive integer.
>>> n31(4)
([4, 2, 1], 3)
"""
if not isinstance(a, int):
raise TypeError(f"Must be int, not {type(a).__name__}")
if a < 1:
raise ValueError(f"Given integer must be greater than 1, not {a}")
path = [a]
while a != 1:
if a % 2 == 0:
a = a // 2
else:
a = 3 * a + 1
path += [a]
return path, len(path)
def test_n31():
"""
>>> test_n31()
"""
assert n31(4) == ([4, 2, 1], 3)
assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15)
assert n31(31) == (
[
31,
94,
47,
142,
71,
214,
107,
322,
161,
484,
242,
121,
364,
182,
91,
274,
137,
412,
206,
103,
310,
155,
466,
233,
700,
350,
175,
526,
263,
790,
395,
1186,
593,
1780,
890,
445,
1336,
668,
334,
167,
502,
251,
754,
377,
1132,
566,
283,
850,
425,
1276,
638,
319,
958,
479,
1438,
719,
2158,
1079,
3238,
1619,
4858,
2429,
7288,
3644,
1822,
911,
2734,
1367,
4102,
2051,
6154,
3077,
9232,
4616,
2308,
1154,
577,
1732,
866,
433,
1300,
650,
325,
976,
488,
244,
122,
61,
184,
92,
46,
23,
70,
35,
106,
53,
160,
80,
40,
20,
10,
5,
16,
8,
4,
2,
1,
],
107,
)
if __name__ == "__main__":
num = 4
path, length = n31(num)
print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
| from __future__ import annotations
def n31(a: int) -> tuple[list[int], int]:
"""
Returns the Collatz sequence and its length of any positive integer.
>>> n31(4)
([4, 2, 1], 3)
"""
if not isinstance(a, int):
raise TypeError(f"Must be int, not {type(a).__name__}")
if a < 1:
raise ValueError(f"Given integer must be greater than 1, not {a}")
path = [a]
while a != 1:
if a % 2 == 0:
a = a // 2
else:
a = 3 * a + 1
path += [a]
return path, len(path)
def test_n31():
"""
>>> test_n31()
"""
assert n31(4) == ([4, 2, 1], 3)
assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15)
assert n31(31) == (
[
31,
94,
47,
142,
71,
214,
107,
322,
161,
484,
242,
121,
364,
182,
91,
274,
137,
412,
206,
103,
310,
155,
466,
233,
700,
350,
175,
526,
263,
790,
395,
1186,
593,
1780,
890,
445,
1336,
668,
334,
167,
502,
251,
754,
377,
1132,
566,
283,
850,
425,
1276,
638,
319,
958,
479,
1438,
719,
2158,
1079,
3238,
1619,
4858,
2429,
7288,
3644,
1822,
911,
2734,
1367,
4102,
2051,
6154,
3077,
9232,
4616,
2308,
1154,
577,
1732,
866,
433,
1300,
650,
325,
976,
488,
244,
122,
61,
184,
92,
46,
23,
70,
35,
106,
53,
160,
80,
40,
20,
10,
5,
16,
8,
4,
2,
1,
],
107,
)
if __name__ == "__main__":
num = 4
path, length = n31(num)
print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
"""
Illustrate how to implement bucket sort algorithm.
Author: OMKAR PATHAK
This program will illustrate how to implement bucket sort algorithm
Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works
by distributing the elements of an array into a number of buckets.
Each bucket is then sorted individually, either using a different sorting
algorithm, or by recursively applying the bucket sorting algorithm. It is a
distribution sort, and is a cousin of radix sort in the most to least
significant digit flavour.
Bucket sort is a generalization of pigeonhole sort. Bucket sort can be
implemented with comparisons and therefore can also be considered a
comparison sort algorithm. The computational complexity estimates involve the
number of buckets.
Time Complexity of Solution:
Worst case scenario occurs when all the elements are placed in a single bucket.
The overall performance would then be dominated by the algorithm used to sort each
bucket. In this case, O(n log n), because of TimSort
Average Case O(n + (n^2)/k + k), where k is the number of buckets
If k = O(n), time complexity is O(n)
Source: https://en.wikipedia.org/wiki/Bucket_sort
"""
from __future__ import annotations
def bucket_sort(my_list: list) -> list:
"""
>>> data = [-1, 2, -5, 0]
>>> bucket_sort(data) == sorted(data)
True
>>> data = [9, 8, 7, 6, -12]
>>> bucket_sort(data) == sorted(data)
True
>>> data = [.4, 1.2, .1, .2, -.9]
>>> bucket_sort(data) == sorted(data)
True
>>> bucket_sort([]) == sorted([])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 50)
>>> bucket_sort(collection) == sorted(collection)
True
"""
if len(my_list) == 0:
return []
min_value, max_value = min(my_list), max(my_list)
bucket_count = int(max_value - min_value) + 1
buckets: list[list] = [[] for _ in range(bucket_count)]
for i in range(len(my_list)):
buckets[(int(my_list[i] - min_value) // bucket_count)].append(my_list[i])
return [v for bucket in buckets for v in sorted(bucket)]
if __name__ == "__main__":
from doctest import testmod
testmod()
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
| #!/usr/bin/env python3
"""
Illustrate how to implement bucket sort algorithm.
Author: OMKAR PATHAK
This program will illustrate how to implement bucket sort algorithm
Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works
by distributing the elements of an array into a number of buckets.
Each bucket is then sorted individually, either using a different sorting
algorithm, or by recursively applying the bucket sorting algorithm. It is a
distribution sort, and is a cousin of radix sort in the most to least
significant digit flavour.
Bucket sort is a generalization of pigeonhole sort. Bucket sort can be
implemented with comparisons and therefore can also be considered a
comparison sort algorithm. The computational complexity estimates involve the
number of buckets.
Time Complexity of Solution:
Worst case scenario occurs when all the elements are placed in a single bucket.
The overall performance would then be dominated by the algorithm used to sort each
bucket. In this case, O(n log n), because of TimSort
Average Case O(n + (n^2)/k + k), where k is the number of buckets
If k = O(n), time complexity is O(n)
Source: https://en.wikipedia.org/wiki/Bucket_sort
"""
from __future__ import annotations
def bucket_sort(my_list: list) -> list:
"""
>>> data = [-1, 2, -5, 0]
>>> bucket_sort(data) == sorted(data)
True
>>> data = [9, 8, 7, 6, -12]
>>> bucket_sort(data) == sorted(data)
True
>>> data = [.4, 1.2, .1, .2, -.9]
>>> bucket_sort(data) == sorted(data)
True
>>> bucket_sort([]) == sorted([])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 50)
>>> bucket_sort(collection) == sorted(collection)
True
"""
if len(my_list) == 0:
return []
min_value, max_value = min(my_list), max(my_list)
bucket_count = int(max_value - min_value) + 1
buckets: list[list] = [[] for _ in range(bucket_count)]
for i in range(len(my_list)):
buckets[(int(my_list[i] - min_value) // bucket_count)].append(my_list[i])
return [v for bucket in buckets for v in sorted(bucket)]
if __name__ == "__main__":
from doctest import testmod
testmod()
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Eulerian Path is a path in graph that visits every edge exactly once.
# Eulerian Circuit is an Eulerian Path which starts and ends on the same
# vertex.
# time complexity is O(V+E)
# space complexity is O(VE)
# using dfs for finding eulerian path traversal
def dfs(u, graph, visited_edge, path=None):
path = (path or []) + [u]
for v in graph[u]:
if visited_edge[u][v] is False:
visited_edge[u][v], visited_edge[v][u] = True, True
path = dfs(v, graph, visited_edge, path)
return path
# for checking in graph has euler path or circuit
def check_circuit_or_path(graph, max_node):
odd_degree_nodes = 0
odd_node = -1
for i in range(max_node):
if i not in graph.keys():
continue
if len(graph[i]) % 2 == 1:
odd_degree_nodes += 1
odd_node = i
if odd_degree_nodes == 0:
return 1, odd_node
if odd_degree_nodes == 2:
return 2, odd_node
return 3, odd_node
def check_euler(graph, max_node):
visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)]
check, odd_node = check_circuit_or_path(graph, max_node)
if check == 3:
print("graph is not Eulerian")
print("no path")
return
start_node = 1
if check == 2:
start_node = odd_node
print("graph has a Euler path")
if check == 1:
print("graph has a Euler cycle")
path = dfs(start_node, graph, visited_edge)
print(path)
def main():
G1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
G2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
G3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
G4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
G5 = {
1: [],
2: []
# all degree is zero
}
max_node = 10
check_euler(G1, max_node)
check_euler(G2, max_node)
check_euler(G3, max_node)
check_euler(G4, max_node)
check_euler(G5, max_node)
if __name__ == "__main__":
main()
| # Eulerian Path is a path in graph that visits every edge exactly once.
# Eulerian Circuit is an Eulerian Path which starts and ends on the same
# vertex.
# time complexity is O(V+E)
# space complexity is O(VE)
# using dfs for finding eulerian path traversal
def dfs(u, graph, visited_edge, path=None):
path = (path or []) + [u]
for v in graph[u]:
if visited_edge[u][v] is False:
visited_edge[u][v], visited_edge[v][u] = True, True
path = dfs(v, graph, visited_edge, path)
return path
# for checking in graph has euler path or circuit
def check_circuit_or_path(graph, max_node):
odd_degree_nodes = 0
odd_node = -1
for i in range(max_node):
if i not in graph.keys():
continue
if len(graph[i]) % 2 == 1:
odd_degree_nodes += 1
odd_node = i
if odd_degree_nodes == 0:
return 1, odd_node
if odd_degree_nodes == 2:
return 2, odd_node
return 3, odd_node
def check_euler(graph, max_node):
visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)]
check, odd_node = check_circuit_or_path(graph, max_node)
if check == 3:
print("graph is not Eulerian")
print("no path")
return
start_node = 1
if check == 2:
start_node = odd_node
print("graph has a Euler path")
if check == 1:
print("graph has a Euler cycle")
path = dfs(start_node, graph, visited_edge)
print(path)
def main():
G1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
G2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
G3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
G4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
G5 = {
1: [],
2: []
# all degree is zero
}
max_node = 10
check_euler(G1, max_node)
check_euler(G2, max_node)
check_euler(G3, max_node)
check_euler(G4, max_node)
check_euler(G5, max_node)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| class things:
def __init__(self, name, value, weight):
self.name = name
self.value = value
self.weight = weight
def __repr__(self):
return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})"
def get_value(self):
return self.value
def get_name(self):
return self.name
def get_weight(self):
return self.weight
def value_Weight(self):
return self.value / self.weight
def build_menu(name, value, weight):
menu = []
for i in range(len(value)):
menu.append(things(name[i], value[i], weight[i]))
return menu
def greedy(item, maxCost, keyFunc):
itemsCopy = sorted(item, key=keyFunc, reverse=True)
result = []
totalValue, total_cost = 0.0, 0.0
for i in range(len(itemsCopy)):
if (total_cost + itemsCopy[i].get_weight()) <= maxCost:
result.append(itemsCopy[i])
total_cost += itemsCopy[i].get_weight()
totalValue += itemsCopy[i].get_value()
return (result, totalValue)
def test_greedy():
"""
>>> food = ["Burger", "Pizza", "Coca Cola", "Rice",
... "Sambhar", "Chicken", "Fries", "Milk"]
>>> value = [80, 100, 60, 70, 50, 110, 90, 60]
>>> weight = [40, 60, 40, 70, 100, 85, 55, 70]
>>> foods = build_menu(food, value, weight)
>>> foods # doctest: +NORMALIZE_WHITESPACE
[things(Burger, 80, 40), things(Pizza, 100, 60), things(Coca Cola, 60, 40),
things(Rice, 70, 70), things(Sambhar, 50, 100), things(Chicken, 110, 85),
things(Fries, 90, 55), things(Milk, 60, 70)]
>>> greedy(foods, 500, things.get_value) # doctest: +NORMALIZE_WHITESPACE
([things(Chicken, 110, 85), things(Pizza, 100, 60), things(Fries, 90, 55),
things(Burger, 80, 40), things(Rice, 70, 70), things(Coca Cola, 60, 40),
things(Milk, 60, 70)], 570.0)
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| class things:
def __init__(self, name, value, weight):
self.name = name
self.value = value
self.weight = weight
def __repr__(self):
return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})"
def get_value(self):
return self.value
def get_name(self):
return self.name
def get_weight(self):
return self.weight
def value_Weight(self):
return self.value / self.weight
def build_menu(name, value, weight):
menu = []
for i in range(len(value)):
menu.append(things(name[i], value[i], weight[i]))
return menu
def greedy(item, maxCost, keyFunc):
itemsCopy = sorted(item, key=keyFunc, reverse=True)
result = []
totalValue, total_cost = 0.0, 0.0
for i in range(len(itemsCopy)):
if (total_cost + itemsCopy[i].get_weight()) <= maxCost:
result.append(itemsCopy[i])
total_cost += itemsCopy[i].get_weight()
totalValue += itemsCopy[i].get_value()
return (result, totalValue)
def test_greedy():
"""
>>> food = ["Burger", "Pizza", "Coca Cola", "Rice",
... "Sambhar", "Chicken", "Fries", "Milk"]
>>> value = [80, 100, 60, 70, 50, 110, 90, 60]
>>> weight = [40, 60, 40, 70, 100, 85, 55, 70]
>>> foods = build_menu(food, value, weight)
>>> foods # doctest: +NORMALIZE_WHITESPACE
[things(Burger, 80, 40), things(Pizza, 100, 60), things(Coca Cola, 60, 40),
things(Rice, 70, 70), things(Sambhar, 50, 100), things(Chicken, 110, 85),
things(Fries, 90, 55), things(Milk, 60, 70)]
>>> greedy(foods, 500, things.get_value) # doctest: +NORMALIZE_WHITESPACE
([things(Chicken, 110, 85), things(Pizza, 100, 60), things(Fries, 90, 55),
things(Burger, 80, 40), things(Rice, 70, 70), things(Coca Cola, 60, 40),
things(Milk, 60, 70)], 570.0)
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Created on Mon Feb 26 14:29:11 2018
@author: Christian Bender
@license: MIT-license
This module contains some useful classes and functions for dealing
with linear algebra in python.
Overview:
- class Vector
- function zeroVector(dimension)
- function unitBasisVector(dimension,pos)
- function axpy(scalar,vector1,vector2)
- function randomVector(N,a,b)
- class Matrix
- function squareZeroMatrix(N)
- function randomMatrix(W,H,a,b)
"""
from __future__ import annotations
import math
import random
from typing import Collection, overload
class Vector:
"""
This class represents a vector of arbitrary size.
You need to give the vector components.
Overview about the methods:
constructor(components : list) : init the vector
set(components : list) : changes the vector components.
__str__() : toString method
component(i : int): gets the i-th component (start by 0)
__len__() : gets the size of the vector (number of components)
euclidLength() : returns the euclidean length of the vector.
operator + : vector addition
operator - : vector subtraction
operator * : scalar multiplication and dot product
copy() : copies this vector and returns it.
changeComponent(pos,value) : changes the specified component.
TODO: compare-operator
"""
def __init__(self, components: Collection[float] | None = None) -> None:
"""
input: components or nothing
simple constructor for init the vector
"""
if components is None:
components = []
self.__components = list(components)
def set(self, components: Collection[float]) -> None:
"""
input: new components
changes the components of the vector.
replace the components with newer one.
"""
if len(components) > 0:
self.__components = list(components)
else:
raise Exception("please give any vector")
def __str__(self) -> str:
"""
returns a string representation of the vector
"""
return "(" + ",".join(map(str, self.__components)) + ")"
def component(self, i: int) -> float:
"""
input: index (start at 0)
output: the i-th component of the vector.
"""
if type(i) is int and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception("index out of range")
def __len__(self) -> int:
"""
returns the size of the vector
"""
return len(self.__components)
def euclidLength(self) -> float:
"""
returns the euclidean length of the vector
"""
summe: float = 0
for c in self.__components:
summe += c ** 2
return math.sqrt(summe)
def __add__(self, other: Vector) -> Vector:
"""
input: other vector
assumes: other vector has the same size
returns a new vector that represents the sum.
"""
size = len(self)
if size == len(other):
result = [self.__components[i] + other.component(i) for i in range(size)]
return Vector(result)
else:
raise Exception("must have the same size")
def __sub__(self, other: Vector) -> Vector:
"""
input: other vector
assumes: other vector has the same size
returns a new vector that represents the difference.
"""
size = len(self)
if size == len(other):
result = [self.__components[i] - other.component(i) for i in range(size)]
return Vector(result)
else: # error case
raise Exception("must have the same size")
@overload
def __mul__(self, other: float) -> Vector:
...
@overload
def __mul__(self, other: Vector) -> float:
...
def __mul__(self, other: float | Vector) -> float | Vector:
"""
mul implements the scalar multiplication
and the dot-product
"""
if isinstance(other, float) or isinstance(other, int):
ans = [c * other for c in self.__components]
return Vector(ans)
elif isinstance(other, Vector) and (len(self) == len(other)):
size = len(self)
summe: float = 0
for i in range(size):
summe += self.__components[i] * other.component(i)
return summe
else: # error case
raise Exception("invalid operand!")
def magnitude(self) -> float:
"""
Magnitude of a Vector
>>> Vector([2, 3, 4]).magnitude()
5.385164807134504
"""
return sum([i ** 2 for i in self.__components]) ** (1 / 2)
def angle(self, other: Vector, deg: bool = False) -> float:
"""
find angle between two Vector (self, Vector)
>>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]))
1.4906464636572374
>>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True)
85.40775111366095
>>> Vector([3, 4, -1]).angle(Vector([2, -1]))
Traceback (most recent call last):
...
Exception: invalid operand!
"""
num = self * other
den = self.magnitude() * other.magnitude()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def copy(self) -> Vector:
"""
copies this vector and returns it.
"""
return Vector(self.__components)
def changeComponent(self, pos: int, value: float) -> None:
"""
input: an index (pos) and a value
changes the specified component (pos) with the
'value'
"""
# precondition
assert -len(self.__components) <= pos < len(self.__components)
self.__components[pos] = value
def zeroVector(dimension: int) -> Vector:
"""
returns a zero-vector of size 'dimension'
"""
# precondition
assert isinstance(dimension, int)
return Vector([0] * dimension)
def unitBasisVector(dimension: int, pos: int) -> Vector:
"""
returns a unit basis vector with a One
at index 'pos' (indexing at 0)
"""
# precondition
assert isinstance(dimension, int) and (isinstance(pos, int))
ans = [0] * dimension
ans[pos] = 1
return Vector(ans)
def axpy(scalar: float, x: Vector, y: Vector) -> Vector:
"""
input: a 'scalar' and two vectors 'x' and 'y'
output: a vector
computes the axpy operation
"""
# precondition
assert (
isinstance(x, Vector)
and (isinstance(y, Vector))
and (isinstance(scalar, int) or isinstance(scalar, float))
)
return x * scalar + y
def randomVector(N: int, a: int, b: int) -> Vector:
"""
input: size (N) of the vector.
random range (a,b)
output: returns a random vector of size N, with
random integer components between 'a' and 'b'.
"""
random.seed(None)
ans = [random.randint(a, b) for _ in range(N)]
return Vector(ans)
class Matrix:
"""
class: Matrix
This class represents a arbitrary matrix.
Overview about the methods:
__str__() : returns a string representation
operator * : implements the matrix vector multiplication
implements the matrix-scalar multiplication.
changeComponent(x,y,value) : changes the specified component.
component(x,y) : returns the specified component.
width() : returns the width of the matrix
height() : returns the height of the matrix
operator + : implements the matrix-addition.
operator - _ implements the matrix-subtraction
"""
def __init__(self, matrix: list[list[float]], w: int, h: int) -> None:
"""
simple constructor for initializing
the matrix with components.
"""
self.__matrix = matrix
self.__width = w
self.__height = h
def __str__(self) -> str:
"""
returns a string representation of this
matrix.
"""
ans = ""
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def changeComponent(self, x: int, y: int, value: float) -> None:
"""
changes the x-y component of this matrix
"""
if 0 <= x < self.__height and 0 <= y < self.__width:
self.__matrix[x][y] = value
else:
raise Exception("changeComponent: indices out of bounds")
def component(self, x: int, y: int) -> float:
"""
returns the specified (x,y) component
"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception("changeComponent: indices out of bounds")
def width(self) -> int:
"""
getter for the width
"""
return self.__width
def height(self) -> int:
"""
getter for the height
"""
return self.__height
def determinate(self) -> float:
"""
returns the determinate of an nxn matrix using Laplace expansion
"""
if self.__height == self.__width and self.__width >= 2:
total = 0
if self.__width > 2:
for x in range(0, self.__width):
for y in range(0, self.__height):
total += (
self.__matrix[x][y]
* (-1) ** (x + y)
* Matrix(
self.__matrix[0:x] + self.__matrix[x + 1 :],
self.__width - 1,
self.__height - 1,
).determinate()
)
else:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
return total
else:
raise Exception("matrix is not square")
@overload
def __mul__(self, other: float) -> Matrix:
...
@overload
def __mul__(self, other: Vector) -> Vector:
...
def __mul__(self, other: float | Vector) -> Vector | Matrix:
"""
implements the matrix-vector multiplication.
implements the matrix-scalar multiplication
"""
if isinstance(other, Vector): # vector-matrix
if len(other) == self.__width:
ans = zeroVector(self.__height)
for i in range(self.__height):
summe: float = 0
for j in range(self.__width):
summe += other.component(j) * self.__matrix[i][j]
ans.changeComponent(i, summe)
summe = 0
return ans
else:
raise Exception(
"vector must have the same size as the "
+ "number of columns of the matrix!"
)
elif isinstance(other, int) or isinstance(other, float): # matrix-scalar
matrix = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(matrix, self.__width, self.__height)
def __add__(self, other: Matrix) -> Matrix:
"""
implements the matrix-addition.
"""
if self.__width == other.width() and self.__height == other.height():
matrix = []
for i in range(self.__height):
row = []
for j in range(self.__width):
row.append(self.__matrix[i][j] + other.component(i, j))
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
else:
raise Exception("matrix must have the same dimension!")
def __sub__(self, other: Matrix) -> Matrix:
"""
implements the matrix-subtraction.
"""
if self.__width == other.width() and self.__height == other.height():
matrix = []
for i in range(self.__height):
row = []
for j in range(self.__width):
row.append(self.__matrix[i][j] - other.component(i, j))
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
else:
raise Exception("matrix must have the same dimension!")
def squareZeroMatrix(N: int) -> Matrix:
"""
returns a square zero-matrix of dimension NxN
"""
ans: list[list[float]] = [[0] * N for _ in range(N)]
return Matrix(ans, N, N)
def randomMatrix(W: int, H: int, a: int, b: int) -> Matrix:
"""
returns a random matrix WxH with integer components
between 'a' and 'b'
"""
random.seed(None)
matrix: list[list[float]] = [
[random.randint(a, b) for _ in range(W)] for _ in range(H)
]
return Matrix(matrix, W, H)
| """
Created on Mon Feb 26 14:29:11 2018
@author: Christian Bender
@license: MIT-license
This module contains some useful classes and functions for dealing
with linear algebra in python.
Overview:
- class Vector
- function zeroVector(dimension)
- function unitBasisVector(dimension,pos)
- function axpy(scalar,vector1,vector2)
- function randomVector(N,a,b)
- class Matrix
- function squareZeroMatrix(N)
- function randomMatrix(W,H,a,b)
"""
from __future__ import annotations
import math
import random
from typing import Collection, overload
class Vector:
"""
This class represents a vector of arbitrary size.
You need to give the vector components.
Overview about the methods:
constructor(components : list) : init the vector
set(components : list) : changes the vector components.
__str__() : toString method
component(i : int): gets the i-th component (start by 0)
__len__() : gets the size of the vector (number of components)
euclidLength() : returns the euclidean length of the vector.
operator + : vector addition
operator - : vector subtraction
operator * : scalar multiplication and dot product
copy() : copies this vector and returns it.
changeComponent(pos,value) : changes the specified component.
TODO: compare-operator
"""
def __init__(self, components: Collection[float] | None = None) -> None:
"""
input: components or nothing
simple constructor for init the vector
"""
if components is None:
components = []
self.__components = list(components)
def set(self, components: Collection[float]) -> None:
"""
input: new components
changes the components of the vector.
replace the components with newer one.
"""
if len(components) > 0:
self.__components = list(components)
else:
raise Exception("please give any vector")
def __str__(self) -> str:
"""
returns a string representation of the vector
"""
return "(" + ",".join(map(str, self.__components)) + ")"
def component(self, i: int) -> float:
"""
input: index (start at 0)
output: the i-th component of the vector.
"""
if type(i) is int and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception("index out of range")
def __len__(self) -> int:
"""
returns the size of the vector
"""
return len(self.__components)
def euclidLength(self) -> float:
"""
returns the euclidean length of the vector
"""
summe: float = 0
for c in self.__components:
summe += c ** 2
return math.sqrt(summe)
def __add__(self, other: Vector) -> Vector:
"""
input: other vector
assumes: other vector has the same size
returns a new vector that represents the sum.
"""
size = len(self)
if size == len(other):
result = [self.__components[i] + other.component(i) for i in range(size)]
return Vector(result)
else:
raise Exception("must have the same size")
def __sub__(self, other: Vector) -> Vector:
"""
input: other vector
assumes: other vector has the same size
returns a new vector that represents the difference.
"""
size = len(self)
if size == len(other):
result = [self.__components[i] - other.component(i) for i in range(size)]
return Vector(result)
else: # error case
raise Exception("must have the same size")
@overload
def __mul__(self, other: float) -> Vector:
...
@overload
def __mul__(self, other: Vector) -> float:
...
def __mul__(self, other: float | Vector) -> float | Vector:
"""
mul implements the scalar multiplication
and the dot-product
"""
if isinstance(other, float) or isinstance(other, int):
ans = [c * other for c in self.__components]
return Vector(ans)
elif isinstance(other, Vector) and (len(self) == len(other)):
size = len(self)
summe: float = 0
for i in range(size):
summe += self.__components[i] * other.component(i)
return summe
else: # error case
raise Exception("invalid operand!")
def magnitude(self) -> float:
"""
Magnitude of a Vector
>>> Vector([2, 3, 4]).magnitude()
5.385164807134504
"""
return sum([i ** 2 for i in self.__components]) ** (1 / 2)
def angle(self, other: Vector, deg: bool = False) -> float:
"""
find angle between two Vector (self, Vector)
>>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]))
1.4906464636572374
>>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True)
85.40775111366095
>>> Vector([3, 4, -1]).angle(Vector([2, -1]))
Traceback (most recent call last):
...
Exception: invalid operand!
"""
num = self * other
den = self.magnitude() * other.magnitude()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def copy(self) -> Vector:
"""
copies this vector and returns it.
"""
return Vector(self.__components)
def changeComponent(self, pos: int, value: float) -> None:
"""
input: an index (pos) and a value
changes the specified component (pos) with the
'value'
"""
# precondition
assert -len(self.__components) <= pos < len(self.__components)
self.__components[pos] = value
def zeroVector(dimension: int) -> Vector:
"""
returns a zero-vector of size 'dimension'
"""
# precondition
assert isinstance(dimension, int)
return Vector([0] * dimension)
def unitBasisVector(dimension: int, pos: int) -> Vector:
"""
returns a unit basis vector with a One
at index 'pos' (indexing at 0)
"""
# precondition
assert isinstance(dimension, int) and (isinstance(pos, int))
ans = [0] * dimension
ans[pos] = 1
return Vector(ans)
def axpy(scalar: float, x: Vector, y: Vector) -> Vector:
"""
input: a 'scalar' and two vectors 'x' and 'y'
output: a vector
computes the axpy operation
"""
# precondition
assert (
isinstance(x, Vector)
and (isinstance(y, Vector))
and (isinstance(scalar, int) or isinstance(scalar, float))
)
return x * scalar + y
def randomVector(N: int, a: int, b: int) -> Vector:
"""
input: size (N) of the vector.
random range (a,b)
output: returns a random vector of size N, with
random integer components between 'a' and 'b'.
"""
random.seed(None)
ans = [random.randint(a, b) for _ in range(N)]
return Vector(ans)
class Matrix:
"""
class: Matrix
This class represents a arbitrary matrix.
Overview about the methods:
__str__() : returns a string representation
operator * : implements the matrix vector multiplication
implements the matrix-scalar multiplication.
changeComponent(x,y,value) : changes the specified component.
component(x,y) : returns the specified component.
width() : returns the width of the matrix
height() : returns the height of the matrix
operator + : implements the matrix-addition.
operator - _ implements the matrix-subtraction
"""
def __init__(self, matrix: list[list[float]], w: int, h: int) -> None:
"""
simple constructor for initializing
the matrix with components.
"""
self.__matrix = matrix
self.__width = w
self.__height = h
def __str__(self) -> str:
"""
returns a string representation of this
matrix.
"""
ans = ""
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def changeComponent(self, x: int, y: int, value: float) -> None:
"""
changes the x-y component of this matrix
"""
if 0 <= x < self.__height and 0 <= y < self.__width:
self.__matrix[x][y] = value
else:
raise Exception("changeComponent: indices out of bounds")
def component(self, x: int, y: int) -> float:
"""
returns the specified (x,y) component
"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception("changeComponent: indices out of bounds")
def width(self) -> int:
"""
getter for the width
"""
return self.__width
def height(self) -> int:
"""
getter for the height
"""
return self.__height
def determinate(self) -> float:
"""
returns the determinate of an nxn matrix using Laplace expansion
"""
if self.__height == self.__width and self.__width >= 2:
total = 0
if self.__width > 2:
for x in range(0, self.__width):
for y in range(0, self.__height):
total += (
self.__matrix[x][y]
* (-1) ** (x + y)
* Matrix(
self.__matrix[0:x] + self.__matrix[x + 1 :],
self.__width - 1,
self.__height - 1,
).determinate()
)
else:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
return total
else:
raise Exception("matrix is not square")
@overload
def __mul__(self, other: float) -> Matrix:
...
@overload
def __mul__(self, other: Vector) -> Vector:
...
def __mul__(self, other: float | Vector) -> Vector | Matrix:
"""
implements the matrix-vector multiplication.
implements the matrix-scalar multiplication
"""
if isinstance(other, Vector): # vector-matrix
if len(other) == self.__width:
ans = zeroVector(self.__height)
for i in range(self.__height):
summe: float = 0
for j in range(self.__width):
summe += other.component(j) * self.__matrix[i][j]
ans.changeComponent(i, summe)
summe = 0
return ans
else:
raise Exception(
"vector must have the same size as the "
+ "number of columns of the matrix!"
)
elif isinstance(other, int) or isinstance(other, float): # matrix-scalar
matrix = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(matrix, self.__width, self.__height)
def __add__(self, other: Matrix) -> Matrix:
"""
implements the matrix-addition.
"""
if self.__width == other.width() and self.__height == other.height():
matrix = []
for i in range(self.__height):
row = []
for j in range(self.__width):
row.append(self.__matrix[i][j] + other.component(i, j))
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
else:
raise Exception("matrix must have the same dimension!")
def __sub__(self, other: Matrix) -> Matrix:
"""
implements the matrix-subtraction.
"""
if self.__width == other.width() and self.__height == other.height():
matrix = []
for i in range(self.__height):
row = []
for j in range(self.__width):
row.append(self.__matrix[i][j] - other.component(i, j))
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
else:
raise Exception("matrix must have the same dimension!")
def squareZeroMatrix(N: int) -> Matrix:
"""
returns a square zero-matrix of dimension NxN
"""
ans: list[list[float]] = [[0] * N for _ in range(N)]
return Matrix(ans, N, N)
def randomMatrix(W: int, H: int, a: int, b: int) -> Matrix:
"""
returns a random matrix WxH with integer components
between 'a' and 'b'
"""
random.seed(None)
matrix: list[list[float]] = [
[random.randint(a, b) for _ in range(W)] for _ in range(H)
]
return Matrix(matrix, W, H)
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 20: https://projecteuler.net/problem=20
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
from math import factorial
def solution(num: int = 100) -> int:
"""Returns the sum of the digits in the factorial of num
>>> solution(1000)
10539
>>> solution(200)
1404
>>> solution(100)
648
>>> solution(50)
216
>>> solution(10)
27
>>> solution(5)
3
>>> solution(3)
6
>>> solution(2)
2
>>> solution(1)
1
>>> solution(0)
1
"""
return sum(map(int, str(factorial(num))))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip())))
| """
Problem 20: https://projecteuler.net/problem=20
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
from math import factorial
def solution(num: int = 100) -> int:
"""Returns the sum of the digits in the factorial of num
>>> solution(1000)
10539
>>> solution(200)
1404
>>> solution(100)
648
>>> solution(50)
216
>>> solution(10)
27
>>> solution(5)
3
>>> solution(3)
6
>>> solution(2)
2
>>> solution(1)
1
>>> solution(0)
1
"""
return sum(map(int, str(factorial(num))))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip())))
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def apply_table(inp, table):
"""
>>> apply_table("0123456789", list(range(10)))
'9012345678'
>>> apply_table("0123456789", list(range(9, -1, -1)))
'8765432109'
"""
res = ""
for i in table:
res += inp[i - 1]
return res
def left_shift(data):
"""
>>> left_shift("0123456789")
'1234567890'
"""
return data[1:] + data[0]
def XOR(a, b):
"""
>>> XOR("01010101", "00001111")
'01011010'
"""
res = ""
for i in range(len(a)):
if a[i] == b[i]:
res += "0"
else:
res += "1"
return res
def apply_sbox(s, data):
row = int("0b" + data[0] + data[-1], 2)
col = int("0b" + data[1:3], 2)
return bin(s[row][col])[2:]
def function(expansion, s0, s1, key, message):
left = message[:4]
right = message[4:]
temp = apply_table(right, expansion)
temp = XOR(temp, key)
l = apply_sbox(s0, temp[:4]) # noqa: E741
r = apply_sbox(s1, temp[4:])
l = "0" * (2 - len(l)) + l # noqa: E741
r = "0" * (2 - len(r)) + r
temp = apply_table(l + r, p4_table)
temp = XOR(left, temp)
return temp + right
if __name__ == "__main__":
key = input("Enter 10 bit key: ")
message = input("Enter 8 bit message: ")
p8_table = [6, 3, 7, 4, 8, 5, 10, 9]
p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
p4_table = [2, 4, 3, 1]
IP = [2, 6, 3, 1, 4, 8, 5, 7]
IP_inv = [4, 1, 3, 5, 7, 2, 8, 6]
expansion = [4, 1, 2, 3, 2, 3, 4, 1]
s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
# key generation
temp = apply_table(key, p10_table)
left = temp[:5]
right = temp[5:]
left = left_shift(left)
right = left_shift(right)
key1 = apply_table(left + right, p8_table)
left = left_shift(left)
right = left_shift(right)
left = left_shift(left)
right = left_shift(right)
key2 = apply_table(left + right, p8_table)
# encryption
temp = apply_table(message, IP)
temp = function(expansion, s0, s1, key1, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key2, temp)
CT = apply_table(temp, IP_inv)
print("Cipher text is:", CT)
# decryption
temp = apply_table(CT, IP)
temp = function(expansion, s0, s1, key2, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key1, temp)
PT = apply_table(temp, IP_inv)
print("Plain text after decypting is:", PT)
| def apply_table(inp, table):
"""
>>> apply_table("0123456789", list(range(10)))
'9012345678'
>>> apply_table("0123456789", list(range(9, -1, -1)))
'8765432109'
"""
res = ""
for i in table:
res += inp[i - 1]
return res
def left_shift(data):
"""
>>> left_shift("0123456789")
'1234567890'
"""
return data[1:] + data[0]
def XOR(a, b):
"""
>>> XOR("01010101", "00001111")
'01011010'
"""
res = ""
for i in range(len(a)):
if a[i] == b[i]:
res += "0"
else:
res += "1"
return res
def apply_sbox(s, data):
row = int("0b" + data[0] + data[-1], 2)
col = int("0b" + data[1:3], 2)
return bin(s[row][col])[2:]
def function(expansion, s0, s1, key, message):
left = message[:4]
right = message[4:]
temp = apply_table(right, expansion)
temp = XOR(temp, key)
l = apply_sbox(s0, temp[:4]) # noqa: E741
r = apply_sbox(s1, temp[4:])
l = "0" * (2 - len(l)) + l # noqa: E741
r = "0" * (2 - len(r)) + r
temp = apply_table(l + r, p4_table)
temp = XOR(left, temp)
return temp + right
if __name__ == "__main__":
key = input("Enter 10 bit key: ")
message = input("Enter 8 bit message: ")
p8_table = [6, 3, 7, 4, 8, 5, 10, 9]
p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
p4_table = [2, 4, 3, 1]
IP = [2, 6, 3, 1, 4, 8, 5, 7]
IP_inv = [4, 1, 3, 5, 7, 2, 8, 6]
expansion = [4, 1, 2, 3, 2, 3, 4, 1]
s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
# key generation
temp = apply_table(key, p10_table)
left = temp[:5]
right = temp[5:]
left = left_shift(left)
right = left_shift(right)
key1 = apply_table(left + right, p8_table)
left = left_shift(left)
right = left_shift(right)
left = left_shift(left)
right = left_shift(right)
key2 = apply_table(left + right, p8_table)
# encryption
temp = apply_table(message, IP)
temp = function(expansion, s0, s1, key1, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key2, temp)
CT = apply_table(temp, IP_inv)
print("Cipher text is:", CT)
# decryption
temp = apply_table(CT, IP)
temp = function(expansion, s0, s1, key2, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key1, temp)
PT = apply_table(temp, IP_inv)
print("Plain text after decypting is:", PT)
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Random Forest Classifier Example
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import plot_confusion_matrix
from sklearn.model_selection import train_test_split
def main():
"""
Random Forest Classifier Example using sklearn function.
Iris type dataset is used to demonstrate algorithm.
"""
# Load Iris dataset
iris = load_iris()
# Split dataset into train and test data
X = iris["data"] # features
Y = iris["target"]
x_train, x_test, y_train, y_test = train_test_split(
X, Y, test_size=0.3, random_state=1
)
# Random Forest Classifier
rand_for = RandomForestClassifier(random_state=42, n_estimators=100)
rand_for.fit(x_train, y_train)
# Display Confusion Matrix of Classifier
plot_confusion_matrix(
rand_for,
x_test,
y_test,
display_labels=iris["target_names"],
cmap="Blues",
normalize="true",
)
plt.title("Normalized Confusion Matrix - IRIS Dataset")
plt.show()
if __name__ == "__main__":
main()
| # Random Forest Classifier Example
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import plot_confusion_matrix
from sklearn.model_selection import train_test_split
def main():
"""
Random Forest Classifier Example using sklearn function.
Iris type dataset is used to demonstrate algorithm.
"""
# Load Iris dataset
iris = load_iris()
# Split dataset into train and test data
X = iris["data"] # features
Y = iris["target"]
x_train, x_test, y_train, y_test = train_test_split(
X, Y, test_size=0.3, random_state=1
)
# Random Forest Classifier
rand_for = RandomForestClassifier(random_state=42, n_estimators=100)
rand_for.fit(x_train, y_train)
# Display Confusion Matrix of Classifier
plot_confusion_matrix(
rand_for,
x_test,
y_test,
display_labels=iris["target_names"],
cmap="Blues",
normalize="true",
)
plt.title("Normalized Confusion Matrix - IRIS Dataset")
plt.show()
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A pure Python implementation of the insertion sort algorithm
This algorithm sorts a collection by comparing adjacent elements.
When it finds that order is not respected, it moves the element compared
backward until the order is correct. It then goes back directly to the
element's initial position resuming forward comparison.
For doctests run following command:
python3 -m doctest -v insertion_sort.py
For manual testing run:
python3 insertion_sort.py
"""
def insertion_sort(collection: list) -> list:
"""A pure Python implementation of the insertion sort algorithm
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> insertion_sort([]) == sorted([])
True
>>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45])
True
>>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> insertion_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> insertion_sort(collection) == sorted(collection)
True
"""
for insert_index, insert_value in enumerate(collection[1:]):
temp_index = insert_index
while insert_index >= 0 and insert_value < collection[insert_index]:
collection[insert_index + 1] = collection[insert_index]
insert_index -= 1
if insert_index != temp_index:
collection[insert_index + 1] = insert_value
return collection
if __name__ == "__main__":
from doctest import testmod
testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{insertion_sort(unsorted) = }")
| """
A pure Python implementation of the insertion sort algorithm
This algorithm sorts a collection by comparing adjacent elements.
When it finds that order is not respected, it moves the element compared
backward until the order is correct. It then goes back directly to the
element's initial position resuming forward comparison.
For doctests run following command:
python3 -m doctest -v insertion_sort.py
For manual testing run:
python3 insertion_sort.py
"""
def insertion_sort(collection: list) -> list:
"""A pure Python implementation of the insertion sort algorithm
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> insertion_sort([]) == sorted([])
True
>>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45])
True
>>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> insertion_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> insertion_sort(collection) == sorted(collection)
True
"""
for insert_index, insert_value in enumerate(collection[1:]):
temp_index = insert_index
while insert_index >= 0 and insert_value < collection[insert_index]:
collection[insert_index + 1] = collection[insert_index]
insert_index -= 1
if insert_index != temp_index:
collection[insert_index + 1] = insert_value
return collection
if __name__ == "__main__":
from doctest import testmod
testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{insertion_sort(unsorted) = }")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In laser physics, a "white cell" is a mirror system that acts as a delay line for the
laser beam. The beam enters the cell, bounces around on the mirrors, and eventually
works its way back out.
The specific white cell we will be considering is an ellipse with the equation
4x^2 + y^2 = 100
The section corresponding to −0.01 ≤ x ≤ +0.01 at the top is missing, allowing the
light to enter and exit through the hole.

The light beam in this problem starts at the point (0.0,10.1) just outside the white
cell, and the beam first impacts the mirror at (1.4,-9.6).
Each time the laser beam hits the surface of the ellipse, it follows the usual law of
reflection "angle of incidence equals angle of reflection." That is, both the incident
and reflected beams make the same angle with the normal line at the point of incidence.
In the figure on the left, the red line shows the first two points of contact between
the laser beam and the wall of the white cell; the blue line shows the line tangent to
the ellipse at the point of incidence of the first bounce.
The slope m of the tangent line at any point (x,y) of the given ellipse is: m = −4x/y
The normal line is perpendicular to this tangent line at the point of incidence.
The animation on the right shows the first 10 reflections of the beam.
How many times does the beam hit the internal surface of the white cell before exiting?
"""
from math import isclose, sqrt
def next_point(
point_x: float, point_y: float, incoming_gradient: float
) -> tuple[float, float, float]:
"""
Given that a laser beam hits the interior of the white cell at point
(point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1)
where the next point of contact with the interior is (x,y) with gradient m1.
>>> next_point(5.0, 0.0, 0.0)
(-5.0, 0.0, 0.0)
>>> next_point(5.0, 0.0, -2.0)
(0.0, -10.0, 2.0)
"""
# normal_gradient = gradient of line through which the beam is reflected
# outgoing_gradient = gradient of reflected line
normal_gradient = point_y / 4 / point_x
s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient)
c2 = (1 - normal_gradient * normal_gradient) / (
1 + normal_gradient * normal_gradient
)
outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient)
# to find the next point, solve the simultaeneous equations:
# y^2 + 4x^2 = 100
# y - b = m * (x - a)
# ==> A x^2 + B x + C = 0
quadratic_term = outgoing_gradient ** 2 + 4
linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x)
constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100
x_minus = (
-linear_term - sqrt(linear_term ** 2 - 4 * quadratic_term * constant_term)
) / (2 * quadratic_term)
x_plus = (
-linear_term + sqrt(linear_term ** 2 - 4 * quadratic_term * constant_term)
) / (2 * quadratic_term)
# two solutions, one of which is our input point
next_x = x_minus if isclose(x_plus, point_x) else x_plus
next_y = point_y + outgoing_gradient * (next_x - point_x)
return next_x, next_y, outgoing_gradient
def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int:
"""
Return the number of times that the beam hits the interior wall of the
cell before exiting.
>>> solution(0.00001,-10)
1
>>> solution(5, 0)
287
"""
num_reflections: int = 0
point_x: float = first_x_coord
point_y: float = first_y_coord
gradient: float = (10.1 - point_y) / (0.0 - point_x)
while not (-0.01 <= point_x <= 0.01 and point_y > 0):
point_x, point_y, gradient = next_point(point_x, point_y, gradient)
num_reflections += 1
return num_reflections
if __name__ == "__main__":
print(f"{solution() = }")
| """
In laser physics, a "white cell" is a mirror system that acts as a delay line for the
laser beam. The beam enters the cell, bounces around on the mirrors, and eventually
works its way back out.
The specific white cell we will be considering is an ellipse with the equation
4x^2 + y^2 = 100
The section corresponding to −0.01 ≤ x ≤ +0.01 at the top is missing, allowing the
light to enter and exit through the hole.

The light beam in this problem starts at the point (0.0,10.1) just outside the white
cell, and the beam first impacts the mirror at (1.4,-9.6).
Each time the laser beam hits the surface of the ellipse, it follows the usual law of
reflection "angle of incidence equals angle of reflection." That is, both the incident
and reflected beams make the same angle with the normal line at the point of incidence.
In the figure on the left, the red line shows the first two points of contact between
the laser beam and the wall of the white cell; the blue line shows the line tangent to
the ellipse at the point of incidence of the first bounce.
The slope m of the tangent line at any point (x,y) of the given ellipse is: m = −4x/y
The normal line is perpendicular to this tangent line at the point of incidence.
The animation on the right shows the first 10 reflections of the beam.
How many times does the beam hit the internal surface of the white cell before exiting?
"""
from math import isclose, sqrt
def next_point(
point_x: float, point_y: float, incoming_gradient: float
) -> tuple[float, float, float]:
"""
Given that a laser beam hits the interior of the white cell at point
(point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1)
where the next point of contact with the interior is (x,y) with gradient m1.
>>> next_point(5.0, 0.0, 0.0)
(-5.0, 0.0, 0.0)
>>> next_point(5.0, 0.0, -2.0)
(0.0, -10.0, 2.0)
"""
# normal_gradient = gradient of line through which the beam is reflected
# outgoing_gradient = gradient of reflected line
normal_gradient = point_y / 4 / point_x
s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient)
c2 = (1 - normal_gradient * normal_gradient) / (
1 + normal_gradient * normal_gradient
)
outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient)
# to find the next point, solve the simultaeneous equations:
# y^2 + 4x^2 = 100
# y - b = m * (x - a)
# ==> A x^2 + B x + C = 0
quadratic_term = outgoing_gradient ** 2 + 4
linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x)
constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100
x_minus = (
-linear_term - sqrt(linear_term ** 2 - 4 * quadratic_term * constant_term)
) / (2 * quadratic_term)
x_plus = (
-linear_term + sqrt(linear_term ** 2 - 4 * quadratic_term * constant_term)
) / (2 * quadratic_term)
# two solutions, one of which is our input point
next_x = x_minus if isclose(x_plus, point_x) else x_plus
next_y = point_y + outgoing_gradient * (next_x - point_x)
return next_x, next_y, outgoing_gradient
def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int:
"""
Return the number of times that the beam hits the interior wall of the
cell before exiting.
>>> solution(0.00001,-10)
1
>>> solution(5, 0)
287
"""
num_reflections: int = 0
point_x: float = first_x_coord
point_y: float = first_y_coord
gradient: float = (10.1 - point_y) / (0.0 - point_x)
while not (-0.01 <= point_x <= 0.01 and point_y > 0):
point_x, point_y, gradient = next_point(point_x, point_y, gradient)
num_reflections += 1
return num_reflections
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Segmented Sieve."""
import math
def sieve(n):
"""Segmented Sieve."""
in_prime = []
start = 2
end = int(math.sqrt(n)) # Size of every segment
temp = [True] * (end + 1)
prime = []
while start <= end:
if temp[start] is True:
in_prime.append(start)
for i in range(start * start, end + 1, start):
if temp[i] is True:
temp[i] = False
start += 1
prime += in_prime
low = end + 1
high = low + end - 1
if high > n:
high = n
while low <= n:
temp = [True] * (high - low + 1)
for each in in_prime:
t = math.floor(low / each) * each
if t < low:
t += each
for j in range(t, high + 1, each):
temp[j - low] = False
for j in range(len(temp)):
if temp[j] is True:
prime.append(j + low)
low = high + 1
high = low + end - 1
if high > n:
high = n
return prime
print(sieve(10 ** 6))
| """Segmented Sieve."""
import math
def sieve(n):
"""Segmented Sieve."""
in_prime = []
start = 2
end = int(math.sqrt(n)) # Size of every segment
temp = [True] * (end + 1)
prime = []
while start <= end:
if temp[start] is True:
in_prime.append(start)
for i in range(start * start, end + 1, start):
if temp[i] is True:
temp[i] = False
start += 1
prime += in_prime
low = end + 1
high = low + end - 1
if high > n:
high = n
while low <= n:
temp = [True] * (high - low + 1)
for each in in_prime:
t = math.floor(low / each) * each
if t < low:
t += each
for j in range(t, high + 1, each):
temp[j - low] = False
for j in range(len(temp)):
if temp[j] is True:
prime.append(j + low)
low = high + 1
high = low + end - 1
if high > n:
high = n
return prime
print(sieve(10 ** 6))
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
import random
class Dice:
NUM_SIDES = 6
def __init__(self):
"""Initialize a six sided dice"""
self.sides = list(range(1, Dice.NUM_SIDES + 1))
def roll(self):
return random.choice(self.sides)
def _str_(self):
return "Fair Dice"
def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:
"""
Return probability list of all possible sums when throwing dice.
>>> random.seed(0)
>>> throw_dice(10, 1)
[10.0, 0.0, 30.0, 50.0, 10.0, 0.0]
>>> throw_dice(100, 1)
[19.0, 17.0, 17.0, 11.0, 23.0, 13.0]
>>> throw_dice(1000, 1)
[18.8, 15.5, 16.3, 17.6, 14.2, 17.6]
>>> throw_dice(10000, 1)
[16.35, 16.89, 16.93, 16.6, 16.52, 16.71]
>>> throw_dice(10000, 2)
[2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75]
"""
dices = [Dice() for i in range(num_dice)]
count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1)
for i in range(num_throws):
count_of_sum[sum(dice.roll() for dice in dices)] += 1
probability = [round((count * 100) / num_throws, 2) for count in count_of_sum]
return probability[num_dice:] # remove probability of sums that never appear
if __name__ == "__main__":
import doctest
doctest.testmod()
| from __future__ import annotations
import random
class Dice:
NUM_SIDES = 6
def __init__(self):
"""Initialize a six sided dice"""
self.sides = list(range(1, Dice.NUM_SIDES + 1))
def roll(self):
return random.choice(self.sides)
def _str_(self):
return "Fair Dice"
def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:
"""
Return probability list of all possible sums when throwing dice.
>>> random.seed(0)
>>> throw_dice(10, 1)
[10.0, 0.0, 30.0, 50.0, 10.0, 0.0]
>>> throw_dice(100, 1)
[19.0, 17.0, 17.0, 11.0, 23.0, 13.0]
>>> throw_dice(1000, 1)
[18.8, 15.5, 16.3, 17.6, 14.2, 17.6]
>>> throw_dice(10000, 1)
[16.35, 16.89, 16.93, 16.6, 16.52, 16.71]
>>> throw_dice(10000, 2)
[2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75]
"""
dices = [Dice() for i in range(num_dice)]
count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1)
for i in range(num_throws):
count_of_sum[sum(dice.roll() for dice in dices)] += 1
probability = [round((count * 100) / num_throws, 2) for count in count_of_sum]
return probability[num_dice:] # remove probability of sums that never appear
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
"""
Created by sarathkaul on 14/11/19
Updated by lawric1 on 24/11/20
Authentication will be made via access token.
To generate your personal access token visit https://github.com/settings/tokens.
NOTE:
Never hardcode any credential information in the code. Always use an environment
file to store the private information and use the `os` module to get the information
during runtime.
Create a ".env" file in the root directory and write these two lines in that file
with your token::
#!/usr/bin/env bash
export USER_TOKEN=""
"""
from __future__ import annotations
import os
from typing import Any
import requests
BASE_URL = "https://api.github.com"
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user"
# https://github.com/settings/tokens
USER_TOKEN = os.environ.get("USER_TOKEN", "")
def fetch_github_info(auth_token: str) -> dict[Any, Any]:
"""
Fetch GitHub info of a user using the requests module
"""
headers = {
"Authorization": f"token {auth_token}",
"Accept": "application/vnd.github.v3+json",
}
return requests.get(AUTHENTICATED_USER_ENDPOINT, headers=headers).json()
if __name__ == "__main__": # pragma: no cover
if USER_TOKEN:
for key, value in fetch_github_info(USER_TOKEN).items():
print(f"{key}: {value}")
else:
raise ValueError("'USER_TOKEN' field cannot be empty.")
| #!/usr/bin/env python3
"""
Created by sarathkaul on 14/11/19
Updated by lawric1 on 24/11/20
Authentication will be made via access token.
To generate your personal access token visit https://github.com/settings/tokens.
NOTE:
Never hardcode any credential information in the code. Always use an environment
file to store the private information and use the `os` module to get the information
during runtime.
Create a ".env" file in the root directory and write these two lines in that file
with your token::
#!/usr/bin/env bash
export USER_TOKEN=""
"""
from __future__ import annotations
import os
from typing import Any
import requests
BASE_URL = "https://api.github.com"
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user"
# https://github.com/settings/tokens
USER_TOKEN = os.environ.get("USER_TOKEN", "")
def fetch_github_info(auth_token: str) -> dict[Any, Any]:
"""
Fetch GitHub info of a user using the requests module
"""
headers = {
"Authorization": f"token {auth_token}",
"Accept": "application/vnd.github.v3+json",
}
return requests.get(AUTHENTICATED_USER_ENDPOINT, headers=headers).json()
if __name__ == "__main__": # pragma: no cover
if USER_TOKEN:
for key, value in fetch_github_info(USER_TOKEN).items():
print(f"{key}: {value}")
else:
raise ValueError("'USER_TOKEN' field cannot be empty.")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Algorithm for calculating the most cost-efficient sequence for converting one string
into another.
The only allowed operations are
--- Cost to copy a character is copy_cost
--- Cost to replace a character is replace_cost
--- Cost to delete a character is delete_cost
--- Cost to insert a character is insert_cost
"""
def compute_transform_tables(
source_string: str,
destination_string: str,
copy_cost: int,
replace_cost: int,
delete_cost: int,
insert_cost: int,
) -> tuple[list[list[int]], list[list[str]]]:
source_seq = list(source_string)
destination_seq = list(destination_string)
len_source_seq = len(source_seq)
len_destination_seq = len(destination_seq)
costs = [
[0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
ops = [
["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
for i in range(1, len_source_seq + 1):
costs[i][0] = i * delete_cost
ops[i][0] = "D%c" % source_seq[i - 1]
for i in range(1, len_destination_seq + 1):
costs[0][i] = i * insert_cost
ops[0][i] = "I%c" % destination_seq[i - 1]
for i in range(1, len_source_seq + 1):
for j in range(1, len_destination_seq + 1):
if source_seq[i - 1] == destination_seq[j - 1]:
costs[i][j] = costs[i - 1][j - 1] + copy_cost
ops[i][j] = "C%c" % source_seq[i - 1]
else:
costs[i][j] = costs[i - 1][j - 1] + replace_cost
ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1])
if costs[i - 1][j] + delete_cost < costs[i][j]:
costs[i][j] = costs[i - 1][j] + delete_cost
ops[i][j] = "D%c" % source_seq[i - 1]
if costs[i][j - 1] + insert_cost < costs[i][j]:
costs[i][j] = costs[i][j - 1] + insert_cost
ops[i][j] = "I%c" % destination_seq[j - 1]
return costs, ops
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
if i == 0 and j == 0:
return []
else:
if ops[i][j][0] == "C" or ops[i][j][0] == "R":
seq = assemble_transformation(ops, i - 1, j - 1)
seq.append(ops[i][j])
return seq
elif ops[i][j][0] == "D":
seq = assemble_transformation(ops, i - 1, j)
seq.append(ops[i][j])
return seq
else:
seq = assemble_transformation(ops, i, j - 1)
seq.append(ops[i][j])
return seq
if __name__ == "__main__":
_, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2)
m = len(operations)
n = len(operations[0])
sequence = assemble_transformation(operations, m - 1, n - 1)
string = list("Python")
i = 0
cost = 0
with open("min_cost.txt", "w") as file:
for op in sequence:
print("".join(string))
if op[0] == "C":
file.write("%-16s" % "Copy %c" % op[1])
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost -= 1
elif op[0] == "R":
string[i] = op[2]
file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2])))
file.write("\t\t" + "".join(string))
file.write("\r\n")
cost += 1
elif op[0] == "D":
string.pop(i)
file.write("%-16s" % "Delete %c" % op[1])
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
else:
string.insert(i, op[1])
file.write("%-16s" % "Insert %c" % op[1])
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
i += 1
print("".join(string))
print("Cost: ", cost)
file.write("\r\nMinimum cost: " + str(cost))
| """
Algorithm for calculating the most cost-efficient sequence for converting one string
into another.
The only allowed operations are
--- Cost to copy a character is copy_cost
--- Cost to replace a character is replace_cost
--- Cost to delete a character is delete_cost
--- Cost to insert a character is insert_cost
"""
def compute_transform_tables(
source_string: str,
destination_string: str,
copy_cost: int,
replace_cost: int,
delete_cost: int,
insert_cost: int,
) -> tuple[list[list[int]], list[list[str]]]:
source_seq = list(source_string)
destination_seq = list(destination_string)
len_source_seq = len(source_seq)
len_destination_seq = len(destination_seq)
costs = [
[0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
ops = [
["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
for i in range(1, len_source_seq + 1):
costs[i][0] = i * delete_cost
ops[i][0] = "D%c" % source_seq[i - 1]
for i in range(1, len_destination_seq + 1):
costs[0][i] = i * insert_cost
ops[0][i] = "I%c" % destination_seq[i - 1]
for i in range(1, len_source_seq + 1):
for j in range(1, len_destination_seq + 1):
if source_seq[i - 1] == destination_seq[j - 1]:
costs[i][j] = costs[i - 1][j - 1] + copy_cost
ops[i][j] = "C%c" % source_seq[i - 1]
else:
costs[i][j] = costs[i - 1][j - 1] + replace_cost
ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1])
if costs[i - 1][j] + delete_cost < costs[i][j]:
costs[i][j] = costs[i - 1][j] + delete_cost
ops[i][j] = "D%c" % source_seq[i - 1]
if costs[i][j - 1] + insert_cost < costs[i][j]:
costs[i][j] = costs[i][j - 1] + insert_cost
ops[i][j] = "I%c" % destination_seq[j - 1]
return costs, ops
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
if i == 0 and j == 0:
return []
else:
if ops[i][j][0] == "C" or ops[i][j][0] == "R":
seq = assemble_transformation(ops, i - 1, j - 1)
seq.append(ops[i][j])
return seq
elif ops[i][j][0] == "D":
seq = assemble_transformation(ops, i - 1, j)
seq.append(ops[i][j])
return seq
else:
seq = assemble_transformation(ops, i, j - 1)
seq.append(ops[i][j])
return seq
if __name__ == "__main__":
_, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2)
m = len(operations)
n = len(operations[0])
sequence = assemble_transformation(operations, m - 1, n - 1)
string = list("Python")
i = 0
cost = 0
with open("min_cost.txt", "w") as file:
for op in sequence:
print("".join(string))
if op[0] == "C":
file.write("%-16s" % "Copy %c" % op[1])
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost -= 1
elif op[0] == "R":
string[i] = op[2]
file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2])))
file.write("\t\t" + "".join(string))
file.write("\r\n")
cost += 1
elif op[0] == "D":
string.pop(i)
file.write("%-16s" % "Delete %c" % op[1])
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
else:
string.insert(i, op[1])
file.write("%-16s" % "Insert %c" % op[1])
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
i += 1
print("".join(string))
print("Cost: ", cost)
file.write("\r\nMinimum cost: " + str(cost))
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a Python implementation for questions involving task assignments between people.
Here Bitmasking and DP are used for solving this.
Question :-
We have N tasks and M people. Each person in M can do only certain of these tasks. Also
a person can do only one task and a task is performed only by one person.
Find the total no of ways in which the tasks can be distributed.
"""
from collections import defaultdict
class AssignmentUsingBitmask:
def __init__(self, task_performed, total):
self.total_tasks = total # total no of tasks (N)
# DP table will have a dimension of (2^M)*N
# initially all values are set to -1
self.dp = [
[-1 for i in range(total + 1)] for j in range(2 ** len(task_performed))
]
self.task = defaultdict(list) # stores the list of persons for each task
# final_mask is used to check if all persons are included by setting all bits
# to 1
self.final_mask = (1 << len(task_performed)) - 1
def CountWaysUtil(self, mask, task_no):
# if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.final_mask:
return 1
# if not everyone gets the task and no more tasks are available, return 0
if task_no > self.total_tasks:
return 0
# if case already considered
if self.dp[mask][task_no] != -1:
return self.dp[mask][task_no]
# Number of ways when we don't this task in the arrangement
total_ways_util = self.CountWaysUtil(mask, task_no + 1)
# now assign the tasks one by one to all possible persons and recursively
# assign for the remaining tasks.
if task_no in self.task:
for p in self.task[task_no]:
# if p is already given a task
if mask & (1 << p):
continue
# assign this task to p and change the mask value. And recursively
# assign tasks with the new mask value.
total_ways_util += self.CountWaysUtil(mask | (1 << p), task_no + 1)
# save the value.
self.dp[mask][task_no] = total_ways_util
return self.dp[mask][task_no]
def countNoOfWays(self, task_performed):
# Store the list of persons for each task
for i in range(len(task_performed)):
for j in task_performed[i]:
self.task[j].append(i)
# call the function to fill the DP table, final answer is stored in dp[0][1]
return self.CountWaysUtil(0, 1)
if __name__ == "__main__":
total_tasks = 5 # total no of tasks (the value of N)
# the list of tasks that can be done by M persons.
task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]]
print(
AssignmentUsingBitmask(task_performed, total_tasks).countNoOfWays(
task_performed
)
)
"""
For the particular example the tasks can be distributed as
(1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4),
(3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3)
total 10
"""
| """
This is a Python implementation for questions involving task assignments between people.
Here Bitmasking and DP are used for solving this.
Question :-
We have N tasks and M people. Each person in M can do only certain of these tasks. Also
a person can do only one task and a task is performed only by one person.
Find the total no of ways in which the tasks can be distributed.
"""
from collections import defaultdict
class AssignmentUsingBitmask:
def __init__(self, task_performed, total):
self.total_tasks = total # total no of tasks (N)
# DP table will have a dimension of (2^M)*N
# initially all values are set to -1
self.dp = [
[-1 for i in range(total + 1)] for j in range(2 ** len(task_performed))
]
self.task = defaultdict(list) # stores the list of persons for each task
# final_mask is used to check if all persons are included by setting all bits
# to 1
self.final_mask = (1 << len(task_performed)) - 1
def CountWaysUtil(self, mask, task_no):
# if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.final_mask:
return 1
# if not everyone gets the task and no more tasks are available, return 0
if task_no > self.total_tasks:
return 0
# if case already considered
if self.dp[mask][task_no] != -1:
return self.dp[mask][task_no]
# Number of ways when we don't this task in the arrangement
total_ways_util = self.CountWaysUtil(mask, task_no + 1)
# now assign the tasks one by one to all possible persons and recursively
# assign for the remaining tasks.
if task_no in self.task:
for p in self.task[task_no]:
# if p is already given a task
if mask & (1 << p):
continue
# assign this task to p and change the mask value. And recursively
# assign tasks with the new mask value.
total_ways_util += self.CountWaysUtil(mask | (1 << p), task_no + 1)
# save the value.
self.dp[mask][task_no] = total_ways_util
return self.dp[mask][task_no]
def countNoOfWays(self, task_performed):
# Store the list of persons for each task
for i in range(len(task_performed)):
for j in task_performed[i]:
self.task[j].append(i)
# call the function to fill the DP table, final answer is stored in dp[0][1]
return self.CountWaysUtil(0, 1)
if __name__ == "__main__":
total_tasks = 5 # total no of tasks (the value of N)
# the list of tasks that can be done by M persons.
task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]]
print(
AssignmentUsingBitmask(task_performed, total_tasks).countNoOfWays(
task_performed
)
)
"""
For the particular example the tasks can be distributed as
(1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4),
(3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3)
total 10
"""
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Implementation of regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
"""
def match_pattern(input_string: str, pattern: str) -> bool:
"""
uses bottom-up dynamic programming solution for matching the input
string with a given pattern.
Runtime: O(len(input_string)*len(pattern))
Arguments
--------
input_string: str, any string which should be compared with the pattern
pattern: str, the string that represents a pattern and may contain
'.' for single character matches and '*' for zero or more of preceding character
matches
Note
----
the pattern cannot start with a '*',
because there should be at least one character before *
Returns
-------
A Boolean denoting whether the given string follows the pattern
Examples
-------
>>> match_pattern("aab", "c*a*b")
True
>>> match_pattern("dabc", "*abc")
False
>>> match_pattern("aaa", "aa")
False
>>> match_pattern("aaa", "a.a")
True
>>> match_pattern("aaab", "aa*")
False
>>> match_pattern("aaab", ".*")
True
>>> match_pattern("a", "bbbb")
False
>>> match_pattern("", "bbbb")
False
>>> match_pattern("a", "")
False
>>> match_pattern("", "")
True
"""
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
dp = [[0 for i in range(len_pattern)] for j in range(len_string)]
# since string of zero length match pattern of zero length
dp[0][0] = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1, len_string):
dp[i][0] = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1, len_pattern):
dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1, len_string):
for j in range(1, len_pattern):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
dp[i][j] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
dp[i][j] = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = 0
else:
dp[i][j] = 0
return bool(dp[-1][-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
input_string = "aab"
pattern = "c*a*b"
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(f"{input_string} matches the given pattern {pattern}")
else:
print(f"{input_string} does not match with the given pattern {pattern}")
| """
Implementation of regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
"""
def match_pattern(input_string: str, pattern: str) -> bool:
"""
uses bottom-up dynamic programming solution for matching the input
string with a given pattern.
Runtime: O(len(input_string)*len(pattern))
Arguments
--------
input_string: str, any string which should be compared with the pattern
pattern: str, the string that represents a pattern and may contain
'.' for single character matches and '*' for zero or more of preceding character
matches
Note
----
the pattern cannot start with a '*',
because there should be at least one character before *
Returns
-------
A Boolean denoting whether the given string follows the pattern
Examples
-------
>>> match_pattern("aab", "c*a*b")
True
>>> match_pattern("dabc", "*abc")
False
>>> match_pattern("aaa", "aa")
False
>>> match_pattern("aaa", "a.a")
True
>>> match_pattern("aaab", "aa*")
False
>>> match_pattern("aaab", ".*")
True
>>> match_pattern("a", "bbbb")
False
>>> match_pattern("", "bbbb")
False
>>> match_pattern("a", "")
False
>>> match_pattern("", "")
True
"""
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
dp = [[0 for i in range(len_pattern)] for j in range(len_string)]
# since string of zero length match pattern of zero length
dp[0][0] = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1, len_string):
dp[i][0] = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1, len_pattern):
dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1, len_string):
for j in range(1, len_pattern):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
dp[i][j] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
dp[i][j] = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = 0
else:
dp[i][j] = 0
return bool(dp[-1][-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
input_string = "aab"
pattern = "c*a*b"
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(f"{input_string} matches the given pattern {pattern}")
else:
print(f"{input_string} does not match with the given pattern {pattern}")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Picks the random index as the pivot
"""
import random
def partition(A, left_index, right_index):
pivot = A[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
A[left_index], A[i - 1] = A[i - 1], A[left_index]
return i - 1
def quick_sort_random(A, left, right):
if left < right:
pivot = random.randint(left, right - 1)
A[pivot], A[left] = (
A[left],
A[pivot],
) # switches the pivot with the left most bound
pivot_index = partition(A, left, right)
quick_sort_random(
A, left, pivot_index
) # recursive quicksort to the left of the pivot point
quick_sort_random(
A, pivot_index + 1, right
) # recursive quicksort to the right of the pivot point
def main():
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
quick_sort_random(arr, 0, len(arr))
print(arr)
if __name__ == "__main__":
main()
| """
Picks the random index as the pivot
"""
import random
def partition(A, left_index, right_index):
pivot = A[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
A[left_index], A[i - 1] = A[i - 1], A[left_index]
return i - 1
def quick_sort_random(A, left, right):
if left < right:
pivot = random.randint(left, right - 1)
A[pivot], A[left] = (
A[left],
A[pivot],
) # switches the pivot with the left most bound
pivot_index = partition(A, left, right)
quick_sort_random(
A, left, pivot_index
) # recursive quicksort to the left of the pivot point
quick_sort_random(
A, pivot_index + 1, right
) # recursive quicksort to the right of the pivot point
def main():
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
quick_sort_random(arr, 0, len(arr))
print(arr)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://projecteuler.net/problem=51
Prime digit replacements
Problem 51
By replacing the 1st digit of the 2-digit number *3, it turns out that six of
the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit
number is the first example having seven primes among the ten generated numbers,
yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993.
Consequently 56003, being the first member of this family, is the smallest prime
with this property.
Find the smallest prime which, by replacing part of the number (not necessarily
adjacent digits) with the same digit, is part of an eight prime value family.
"""
from __future__ import annotations
from collections import Counter
def prime_sieve(n: int) -> list[int]:
"""
Sieve of Erotosthenes
Function to return all the prime numbers up to a certain number
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>>> prime_sieve(3)
[2]
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
"""
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
is_prime[2] = True
for i in range(3, int(n ** 0.5 + 1), 2):
index = i * 2
while index < n:
is_prime[index] = False
index = index + i
primes = [2]
for i in range(3, n, 2):
if is_prime[i]:
primes.append(i)
return primes
def digit_replacements(number: int) -> list[list[int]]:
"""
Returns all the possible families of digit replacements in a number which
contains at least one repeating digit
>>> digit_replacements(544)
[[500, 511, 522, 533, 544, 555, 566, 577, 588, 599]]
>>> digit_replacements(3112)
[[3002, 3112, 3222, 3332, 3442, 3552, 3662, 3772, 3882, 3992]]
"""
number_str = str(number)
replacements = []
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for duplicate in Counter(number_str) - Counter(set(number_str)):
family = [int(number_str.replace(duplicate, digit)) for digit in digits]
replacements.append(family)
return replacements
def solution(family_length: int = 8) -> int:
"""
Returns the solution of the problem
>>> solution(2)
229399
>>> solution(3)
221311
"""
numbers_checked = set()
# Filter primes with less than 3 replaceable digits
primes = {
x for x in set(prime_sieve(1_000_000)) if len(str(x)) - len(set(str(x))) >= 3
}
for prime in primes:
if prime in numbers_checked:
continue
replacements = digit_replacements(prime)
for family in replacements:
numbers_checked.update(family)
primes_in_family = primes.intersection(family)
if len(primes_in_family) != family_length:
continue
return min(primes_in_family)
return -1
if __name__ == "__main__":
print(solution())
| """
https://projecteuler.net/problem=51
Prime digit replacements
Problem 51
By replacing the 1st digit of the 2-digit number *3, it turns out that six of
the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit
number is the first example having seven primes among the ten generated numbers,
yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993.
Consequently 56003, being the first member of this family, is the smallest prime
with this property.
Find the smallest prime which, by replacing part of the number (not necessarily
adjacent digits) with the same digit, is part of an eight prime value family.
"""
from __future__ import annotations
from collections import Counter
def prime_sieve(n: int) -> list[int]:
"""
Sieve of Erotosthenes
Function to return all the prime numbers up to a certain number
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>>> prime_sieve(3)
[2]
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
"""
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
is_prime[2] = True
for i in range(3, int(n ** 0.5 + 1), 2):
index = i * 2
while index < n:
is_prime[index] = False
index = index + i
primes = [2]
for i in range(3, n, 2):
if is_prime[i]:
primes.append(i)
return primes
def digit_replacements(number: int) -> list[list[int]]:
"""
Returns all the possible families of digit replacements in a number which
contains at least one repeating digit
>>> digit_replacements(544)
[[500, 511, 522, 533, 544, 555, 566, 577, 588, 599]]
>>> digit_replacements(3112)
[[3002, 3112, 3222, 3332, 3442, 3552, 3662, 3772, 3882, 3992]]
"""
number_str = str(number)
replacements = []
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for duplicate in Counter(number_str) - Counter(set(number_str)):
family = [int(number_str.replace(duplicate, digit)) for digit in digits]
replacements.append(family)
return replacements
def solution(family_length: int = 8) -> int:
"""
Returns the solution of the problem
>>> solution(2)
229399
>>> solution(3)
221311
"""
numbers_checked = set()
# Filter primes with less than 3 replaceable digits
primes = {
x for x in set(prime_sieve(1_000_000)) if len(str(x)) - len(set(str(x))) >= 3
}
for prime in primes:
if prime in numbers_checked:
continue
replacements = digit_replacements(prime)
for family in replacements:
numbers_checked.update(family)
primes_in_family = primes.intersection(family)
if len(primes_in_family) != family_length:
continue
return min(primes_in_family)
return -1
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/python
"""
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a
finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random
def fisher_yates_shuffle(data: list) -> list:
for _ in range(len(list)):
a = random.randint(0, len(list) - 1)
b = random.randint(0, len(list) - 1)
list[a], list[b] = list[b], list[a]
return list
if __name__ == "__main__":
integers = [0, 1, 2, 3, 4, 5, 6, 7]
strings = ["python", "says", "hello", "!"]
print("Fisher-Yates Shuffle:")
print("List", integers, strings)
print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
| #!/usr/bin/python
"""
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a
finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random
def fisher_yates_shuffle(data: list) -> list:
for _ in range(len(list)):
a = random.randint(0, len(list) - 1)
b = random.randint(0, len(list) - 1)
list[a], list[b] = list[b], list[a]
return list
if __name__ == "__main__":
integers = [0, 1, 2, 3, 4, 5, 6, 7]
strings = ["python", "says", "hello", "!"]
print("Fisher-Yates Shuffle:")
print("List", integers, strings)
print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
import math
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = sum(i * i for i in range(1, n + 1))
square_of_sum = int(math.pow(sum(range(1, n + 1)), 2))
return square_of_sum - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
import math
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = sum(i * i for i in range(1, n + 1))
square_of_sum = int(math.pow(sum(range(1, n + 1)), 2))
return square_of_sum - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Numerical integration or quadrature for a smooth function f with known values at x_i
This method is the classical approach of suming 'Equally Spaced Abscissas'
method 2:
"Simpson Rule"
"""
def method_2(boundary, steps):
# "Simpson Rule"
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
h = (boundary[1] - boundary[0]) / steps
a = boundary[0]
b = boundary[1]
x_i = make_points(a, b, h)
y = 0.0
y += (h / 3.0) * f(a)
cnt = 2
for i in x_i:
y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i)
cnt += 1
y += (h / 3.0) * f(b)
return y
def make_points(a, b, h):
x = a + h
while x < (b - h):
yield x
x = x + h
def f(x): # enter your function here
y = (x - 0) * (x - 0)
return y
def main():
a = 0.0 # Lower bound of integration
b = 1.0 # Upper bound of integration
steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration
y = method_2(boundary, steps)
print(f"y = {y}")
if __name__ == "__main__":
main()
| """
Numerical integration or quadrature for a smooth function f with known values at x_i
This method is the classical approach of suming 'Equally Spaced Abscissas'
method 2:
"Simpson Rule"
"""
def method_2(boundary, steps):
# "Simpson Rule"
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
h = (boundary[1] - boundary[0]) / steps
a = boundary[0]
b = boundary[1]
x_i = make_points(a, b, h)
y = 0.0
y += (h / 3.0) * f(a)
cnt = 2
for i in x_i:
y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i)
cnt += 1
y += (h / 3.0) * f(b)
return y
def make_points(a, b, h):
x = a + h
while x < (b - h):
yield x
x = x + h
def f(x): # enter your function here
y = (x - 0) * (x - 0)
return y
def main():
a = 0.0 # Lower bound of integration
b = 1.0 # Upper bound of integration
steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration
y = method_2(boundary, steps)
print(f"y = {y}")
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
def hex_to_decimal(hex_string: str) -> int:
"""
Convert a hexadecimal value to its decimal equivalent
#https://www.programiz.com/python-programming/methods/built-in/hex
>>> hex_to_decimal("a")
10
>>> hex_to_decimal("12f")
303
>>> hex_to_decimal(" 12f ")
303
>>> hex_to_decimal("FfFf")
65535
>>> hex_to_decimal("-Ff")
-255
>>> hex_to_decimal("F-f")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
>>> hex_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> hex_to_decimal("12m")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
"""
hex_string = hex_string.strip().lower()
if not hex_string:
raise ValueError("Empty string was passed to the function")
is_negative = hex_string[0] == "-"
if is_negative:
hex_string = hex_string[1:]
if not all(char in hex_table for char in hex_string):
raise ValueError("Non-hexadecimal value was passed to the function")
decimal_number = 0
for char in hex_string:
decimal_number = 16 * decimal_number + hex_table[char]
return -decimal_number if is_negative else decimal_number
if __name__ == "__main__":
from doctest import testmod
testmod()
| hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
def hex_to_decimal(hex_string: str) -> int:
"""
Convert a hexadecimal value to its decimal equivalent
#https://www.programiz.com/python-programming/methods/built-in/hex
>>> hex_to_decimal("a")
10
>>> hex_to_decimal("12f")
303
>>> hex_to_decimal(" 12f ")
303
>>> hex_to_decimal("FfFf")
65535
>>> hex_to_decimal("-Ff")
-255
>>> hex_to_decimal("F-f")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
>>> hex_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> hex_to_decimal("12m")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
"""
hex_string = hex_string.strip().lower()
if not hex_string:
raise ValueError("Empty string was passed to the function")
is_negative = hex_string[0] == "-"
if is_negative:
hex_string = hex_string[1:]
if not all(char in hex_table for char in hex_string):
raise ValueError("Non-hexadecimal value was passed to the function")
decimal_number = 0
for char in hex_string:
decimal_number = 16 * decimal_number + hex_table[char]
return -decimal_number if is_negative else decimal_number
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Implementation of Basic Math in Python."""
import math
def prime_factors(n: int) -> list:
"""Find Prime Factors.
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(0)
Traceback (most recent call last):
...
ValueError: Only positive integers have prime factors
>>> prime_factors(-10)
Traceback (most recent call last):
...
ValueError: Only positive integers have prime factors
"""
if n <= 0:
raise ValueError("Only positive integers have prime factors")
pf = []
while n % 2 == 0:
pf.append(2)
n = int(n / 2)
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
pf.append(i)
n = int(n / i)
if n > 2:
pf.append(n)
return pf
def number_of_divisors(n: int) -> int:
"""Calculate Number of Divisors of an Integer.
>>> number_of_divisors(100)
9
>>> number_of_divisors(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> number_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
if n <= 0:
raise ValueError("Only positive numbers are accepted")
div = 1
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
div *= temp
for i in range(3, int(math.sqrt(n)) + 1, 2):
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
div *= temp
return div
def sum_of_divisors(n: int) -> int:
"""Calculate Sum of Divisors.
>>> sum_of_divisors(100)
217
>>> sum_of_divisors(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> sum_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
if n <= 0:
raise ValueError("Only positive numbers are accepted")
s = 1
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
if temp > 1:
s *= (2 ** temp - 1) / (2 - 1)
for i in range(3, int(math.sqrt(n)) + 1, 2):
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
if temp > 1:
s *= (i ** temp - 1) / (i - 1)
return int(s)
def euler_phi(n: int) -> int:
"""Calculate Euler's Phi Function.
>>> euler_phi(100)
40
"""
s = n
for x in set(prime_factors(n)):
s *= (x - 1) / x
return int(s)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """Implementation of Basic Math in Python."""
import math
def prime_factors(n: int) -> list:
"""Find Prime Factors.
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(0)
Traceback (most recent call last):
...
ValueError: Only positive integers have prime factors
>>> prime_factors(-10)
Traceback (most recent call last):
...
ValueError: Only positive integers have prime factors
"""
if n <= 0:
raise ValueError("Only positive integers have prime factors")
pf = []
while n % 2 == 0:
pf.append(2)
n = int(n / 2)
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
pf.append(i)
n = int(n / i)
if n > 2:
pf.append(n)
return pf
def number_of_divisors(n: int) -> int:
"""Calculate Number of Divisors of an Integer.
>>> number_of_divisors(100)
9
>>> number_of_divisors(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> number_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
if n <= 0:
raise ValueError("Only positive numbers are accepted")
div = 1
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
div *= temp
for i in range(3, int(math.sqrt(n)) + 1, 2):
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
div *= temp
return div
def sum_of_divisors(n: int) -> int:
"""Calculate Sum of Divisors.
>>> sum_of_divisors(100)
217
>>> sum_of_divisors(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> sum_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
if n <= 0:
raise ValueError("Only positive numbers are accepted")
s = 1
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
if temp > 1:
s *= (2 ** temp - 1) / (2 - 1)
for i in range(3, int(math.sqrt(n)) + 1, 2):
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
if temp > 1:
s *= (i ** temp - 1) / (i - 1)
return int(s)
def euler_phi(n: int) -> int:
"""Calculate Euler's Phi Function.
>>> euler_phi(100)
40
"""
s = n
for x in set(prime_factors(n)):
s *= (x - 1) / x
return int(s)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 75: https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form an
integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided
right angle triangle, and other lengths allow more than one solution to be found; for
example, using 120 cm it is possible to form exactly three different integer sided
right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can
exactly one integer sided right angle triangle be formed?
Solution: we generate all pythagorean triples using Euclid's formula and
keep track of the frequencies of the perimeters.
Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
"""
from collections import defaultdict
from math import gcd
from typing import DefaultDict
def solution(limit: int = 1500000) -> int:
"""
Return the number of values of L <= limit such that a wire of length L can be
formmed into an integer sided right angle triangle in exactly one way.
>>> solution(50)
6
>>> solution(1000)
112
>>> solution(50000)
5502
"""
frequencies: DefaultDict = defaultdict(int)
euclid_m = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2):
if gcd(euclid_m, euclid_n) > 1:
continue
primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 75: https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form an
integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided
right angle triangle, and other lengths allow more than one solution to be found; for
example, using 120 cm it is possible to form exactly three different integer sided
right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can
exactly one integer sided right angle triangle be formed?
Solution: we generate all pythagorean triples using Euclid's formula and
keep track of the frequencies of the perimeters.
Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
"""
from collections import defaultdict
from math import gcd
from typing import DefaultDict
def solution(limit: int = 1500000) -> int:
"""
Return the number of values of L <= limit such that a wire of length L can be
formmed into an integer sided right angle triangle in exactly one way.
>>> solution(50)
6
>>> solution(1000)
112
>>> solution(50000)
5502
"""
frequencies: DefaultDict = defaultdict(int)
euclid_m = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2):
if gcd(euclid_m, euclid_n) > 1:
continue
primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/python
"""
A Framework of Back Propagation Neural Network(BP) model
Easy to use:
* add many layers as you want !!!
* clearly see how the loss decreasing
Easy to expand:
* more activation functions
* more loss functions
* more optimization method
Author: Stephen Lee
Github : https://github.com/RiptideBo
Date: 2017.11.23
"""
import numpy as np
from matplotlib import pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-1 * x))
class DenseLayer:
"""
Layers of BP neural network
"""
def __init__(
self, units, activation=None, learning_rate=None, is_input_layer=False
):
"""
common connected layer of bp network
:param units: numbers of neural units
:param activation: activation function
:param learning_rate: learning rate for paras
:param is_input_layer: whether it is input layer or not
"""
self.units = units
self.weight = None
self.bias = None
self.activation = activation
if learning_rate is None:
learning_rate = 0.3
self.learn_rate = learning_rate
self.is_input_layer = is_input_layer
def initializer(self, back_units):
self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units)))
self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T
if self.activation is None:
self.activation = sigmoid
def cal_gradient(self):
# activation function may be sigmoid or linear
if self.activation == sigmoid:
gradient_mat = np.dot(self.output, (1 - self.output).T)
gradient_activation = np.diag(np.diag(gradient_mat))
else:
gradient_activation = 1
return gradient_activation
def forward_propagation(self, xdata):
self.xdata = xdata
if self.is_input_layer:
# input layer
self.wx_plus_b = xdata
self.output = xdata
return xdata
else:
self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias
self.output = self.activation(self.wx_plus_b)
return self.output
def back_propagation(self, gradient):
gradient_activation = self.cal_gradient() # i * i 维
gradient = np.asmatrix(np.dot(gradient.T, gradient_activation))
self._gradient_weight = np.asmatrix(self.xdata)
self._gradient_bias = -1
self._gradient_x = self.weight
self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T)
self.gradient_bias = gradient * self._gradient_bias
self.gradient = np.dot(gradient, self._gradient_x).T
# upgrade: the Negative gradient direction
self.weight = self.weight - self.learn_rate * self.gradient_weight
self.bias = self.bias - self.learn_rate * self.gradient_bias.T
# updates the weights and bias according to learning rate (0.3 if undefined)
return self.gradient
class BPNN:
"""
Back Propagation Neural Network model
"""
def __init__(self):
self.layers = []
self.train_mse = []
self.fig_loss = plt.figure()
self.ax_loss = self.fig_loss.add_subplot(1, 1, 1)
def add_layer(self, layer):
self.layers.append(layer)
def build(self):
for i, layer in enumerate(self.layers[:]):
if i < 1:
layer.is_input_layer = True
else:
layer.initializer(self.layers[i - 1].units)
def summary(self):
for i, layer in enumerate(self.layers[:]):
print("------- layer %d -------" % i)
print("weight.shape ", np.shape(layer.weight))
print("bias.shape ", np.shape(layer.bias))
def train(self, xdata, ydata, train_round, accuracy):
self.train_round = train_round
self.accuracy = accuracy
self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1)
x_shape = np.shape(xdata)
for round_i in range(train_round):
all_loss = 0
for row in range(x_shape[0]):
_xdata = np.asmatrix(xdata[row, :]).T
_ydata = np.asmatrix(ydata[row, :]).T
# forward propagation
for layer in self.layers:
_xdata = layer.forward_propagation(_xdata)
loss, gradient = self.cal_loss(_ydata, _xdata)
all_loss = all_loss + loss
# back propagation: the input_layer does not upgrade
for layer in self.layers[:0:-1]:
gradient = layer.back_propagation(gradient)
mse = all_loss / x_shape[0]
self.train_mse.append(mse)
self.plot_loss()
if mse < self.accuracy:
print("----达到精度----")
return mse
def cal_loss(self, ydata, ydata_):
self.loss = np.sum(np.power((ydata - ydata_), 2))
self.loss_gradient = 2 * (ydata_ - ydata)
# vector (shape is the same as _ydata.shape)
return self.loss, self.loss_gradient
def plot_loss(self):
if self.ax_loss.lines:
self.ax_loss.lines.remove(self.ax_loss.lines[0])
self.ax_loss.plot(self.train_mse, "r-")
plt.ion()
plt.xlabel("step")
plt.ylabel("loss")
plt.show()
plt.pause(0.1)
def example():
x = np.random.randn(10, 10)
y = np.asarray(
[
[0.8, 0.4],
[0.4, 0.3],
[0.34, 0.45],
[0.67, 0.32],
[0.88, 0.67],
[0.78, 0.77],
[0.55, 0.66],
[0.55, 0.43],
[0.54, 0.1],
[0.1, 0.5],
]
)
model = BPNN()
for i in (10, 20, 30, 2):
model.add_layer(DenseLayer(i))
model.build()
model.summary()
model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01)
if __name__ == "__main__":
example()
| #!/usr/bin/python
"""
A Framework of Back Propagation Neural Network(BP) model
Easy to use:
* add many layers as you want !!!
* clearly see how the loss decreasing
Easy to expand:
* more activation functions
* more loss functions
* more optimization method
Author: Stephen Lee
Github : https://github.com/RiptideBo
Date: 2017.11.23
"""
import numpy as np
from matplotlib import pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-1 * x))
class DenseLayer:
"""
Layers of BP neural network
"""
def __init__(
self, units, activation=None, learning_rate=None, is_input_layer=False
):
"""
common connected layer of bp network
:param units: numbers of neural units
:param activation: activation function
:param learning_rate: learning rate for paras
:param is_input_layer: whether it is input layer or not
"""
self.units = units
self.weight = None
self.bias = None
self.activation = activation
if learning_rate is None:
learning_rate = 0.3
self.learn_rate = learning_rate
self.is_input_layer = is_input_layer
def initializer(self, back_units):
self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units)))
self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T
if self.activation is None:
self.activation = sigmoid
def cal_gradient(self):
# activation function may be sigmoid or linear
if self.activation == sigmoid:
gradient_mat = np.dot(self.output, (1 - self.output).T)
gradient_activation = np.diag(np.diag(gradient_mat))
else:
gradient_activation = 1
return gradient_activation
def forward_propagation(self, xdata):
self.xdata = xdata
if self.is_input_layer:
# input layer
self.wx_plus_b = xdata
self.output = xdata
return xdata
else:
self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias
self.output = self.activation(self.wx_plus_b)
return self.output
def back_propagation(self, gradient):
gradient_activation = self.cal_gradient() # i * i 维
gradient = np.asmatrix(np.dot(gradient.T, gradient_activation))
self._gradient_weight = np.asmatrix(self.xdata)
self._gradient_bias = -1
self._gradient_x = self.weight
self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T)
self.gradient_bias = gradient * self._gradient_bias
self.gradient = np.dot(gradient, self._gradient_x).T
# upgrade: the Negative gradient direction
self.weight = self.weight - self.learn_rate * self.gradient_weight
self.bias = self.bias - self.learn_rate * self.gradient_bias.T
# updates the weights and bias according to learning rate (0.3 if undefined)
return self.gradient
class BPNN:
"""
Back Propagation Neural Network model
"""
def __init__(self):
self.layers = []
self.train_mse = []
self.fig_loss = plt.figure()
self.ax_loss = self.fig_loss.add_subplot(1, 1, 1)
def add_layer(self, layer):
self.layers.append(layer)
def build(self):
for i, layer in enumerate(self.layers[:]):
if i < 1:
layer.is_input_layer = True
else:
layer.initializer(self.layers[i - 1].units)
def summary(self):
for i, layer in enumerate(self.layers[:]):
print("------- layer %d -------" % i)
print("weight.shape ", np.shape(layer.weight))
print("bias.shape ", np.shape(layer.bias))
def train(self, xdata, ydata, train_round, accuracy):
self.train_round = train_round
self.accuracy = accuracy
self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1)
x_shape = np.shape(xdata)
for round_i in range(train_round):
all_loss = 0
for row in range(x_shape[0]):
_xdata = np.asmatrix(xdata[row, :]).T
_ydata = np.asmatrix(ydata[row, :]).T
# forward propagation
for layer in self.layers:
_xdata = layer.forward_propagation(_xdata)
loss, gradient = self.cal_loss(_ydata, _xdata)
all_loss = all_loss + loss
# back propagation: the input_layer does not upgrade
for layer in self.layers[:0:-1]:
gradient = layer.back_propagation(gradient)
mse = all_loss / x_shape[0]
self.train_mse.append(mse)
self.plot_loss()
if mse < self.accuracy:
print("----达到精度----")
return mse
def cal_loss(self, ydata, ydata_):
self.loss = np.sum(np.power((ydata - ydata_), 2))
self.loss_gradient = 2 * (ydata_ - ydata)
# vector (shape is the same as _ydata.shape)
return self.loss, self.loss_gradient
def plot_loss(self):
if self.ax_loss.lines:
self.ax_loss.lines.remove(self.ax_loss.lines[0])
self.ax_loss.plot(self.train_mse, "r-")
plt.ion()
plt.xlabel("step")
plt.ylabel("loss")
plt.show()
plt.pause(0.1)
def example():
x = np.random.randn(10, 10)
y = np.asarray(
[
[0.8, 0.4],
[0.4, 0.3],
[0.34, 0.45],
[0.67, 0.32],
[0.88, 0.67],
[0.78, 0.77],
[0.55, 0.66],
[0.55, 0.43],
[0.54, 0.1],
[0.1, 0.5],
]
)
model = BPNN()
for i in (10, 20, 30, 2):
model.add_layer(DenseLayer(i))
model.build()
model.summary()
model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01)
if __name__ == "__main__":
example()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 119: https://projecteuler.net/problem=119
Name: Digit power sum
The number 512 is interesting because it is equal to the sum of its digits
raised to some power: 5 + 1 + 2 = 8, and 8^3 = 512. Another example of a number
with this property is 614656 = 28^4. We shall define an to be the nth term of
this sequence and insist that a number must contain at least two digits to have a sum.
You are given that a2 = 512 and a10 = 614656. Find a30
"""
import math
def digit_sum(n: int) -> int:
"""
Returns the sum of the digits of the number.
>>> digit_sum(123)
6
>>> digit_sum(456)
15
>>> digit_sum(78910)
25
"""
return sum(int(digit) for digit in str(n))
def solution(n: int = 30) -> int:
"""
Returns the value of 30th digit power sum.
>>> solution(2)
512
>>> solution(5)
5832
>>> solution(10)
614656
"""
digit_to_powers = []
for digit in range(2, 100):
for power in range(2, 100):
number = int(math.pow(digit, power))
if digit == digit_sum(number):
digit_to_powers.append(number)
digit_to_powers.sort()
return digit_to_powers[n - 1]
if __name__ == "__main__":
print(solution())
| """
Problem 119: https://projecteuler.net/problem=119
Name: Digit power sum
The number 512 is interesting because it is equal to the sum of its digits
raised to some power: 5 + 1 + 2 = 8, and 8^3 = 512. Another example of a number
with this property is 614656 = 28^4. We shall define an to be the nth term of
this sequence and insist that a number must contain at least two digits to have a sum.
You are given that a2 = 512 and a10 = 614656. Find a30
"""
import math
def digit_sum(n: int) -> int:
"""
Returns the sum of the digits of the number.
>>> digit_sum(123)
6
>>> digit_sum(456)
15
>>> digit_sum(78910)
25
"""
return sum(int(digit) for digit in str(n))
def solution(n: int = 30) -> int:
"""
Returns the value of 30th digit power sum.
>>> solution(2)
512
>>> solution(5)
5832
>>> solution(10)
614656
"""
digit_to_powers = []
for digit in range(2, 100):
for power in range(2, 100):
number = int(math.pow(digit, power))
if digit == digit_sum(number):
digit_to_powers.append(number)
digit_to_powers.sort()
return digit_to_powers[n - 1]
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This program print the matrix in spiral form.
This problem has been solved through recursive way.
Matrix must satisfy below conditions
i) matrix should be only one or two dimensional
ii) number of column of all rows should be equal
"""
from collections.abc import Iterable
def check_matrix(matrix):
# must be
if matrix and isinstance(matrix, Iterable):
if isinstance(matrix[0], Iterable):
prev_len = 0
for row in matrix:
if prev_len == 0:
prev_len = len(row)
result = True
else:
result = prev_len == len(row)
else:
result = True
else:
result = False
return result
def spiralPrint(a):
if check_matrix(a) and len(a) > 0:
matRow = len(a)
if isinstance(a[0], Iterable):
matCol = len(a[0])
else:
for dat in a:
print(dat),
return
# horizotal printing increasing
for i in range(0, matCol):
print(a[0][i]),
# vertical printing down
for i in range(1, matRow):
print(a[i][matCol - 1]),
# horizotal printing decreasing
if matRow > 1:
for i in range(matCol - 2, -1, -1):
print(a[matRow - 1][i]),
# vertical printing up
for i in range(matRow - 2, 0, -1):
print(a[i][0]),
remainMat = [row[1 : matCol - 1] for row in a[1 : matRow - 1]]
if len(remainMat) > 0:
spiralPrint(remainMat)
else:
return
else:
print("Not a valid matrix")
return
# driver code
if __name__ == "__main__":
a = ([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
spiralPrint(a)
| """
This program print the matrix in spiral form.
This problem has been solved through recursive way.
Matrix must satisfy below conditions
i) matrix should be only one or two dimensional
ii) number of column of all rows should be equal
"""
from collections.abc import Iterable
def check_matrix(matrix):
# must be
if matrix and isinstance(matrix, Iterable):
if isinstance(matrix[0], Iterable):
prev_len = 0
for row in matrix:
if prev_len == 0:
prev_len = len(row)
result = True
else:
result = prev_len == len(row)
else:
result = True
else:
result = False
return result
def spiralPrint(a):
if check_matrix(a) and len(a) > 0:
matRow = len(a)
if isinstance(a[0], Iterable):
matCol = len(a[0])
else:
for dat in a:
print(dat),
return
# horizotal printing increasing
for i in range(0, matCol):
print(a[0][i]),
# vertical printing down
for i in range(1, matRow):
print(a[i][matCol - 1]),
# horizotal printing decreasing
if matRow > 1:
for i in range(matCol - 2, -1, -1):
print(a[matRow - 1][i]),
# vertical printing up
for i in range(matRow - 2, 0, -1):
print(a[i][0]),
remainMat = [row[1 : matCol - 1] for row in a[1 : matRow - 1]]
if len(remainMat) > 0:
spiralPrint(remainMat)
else:
return
else:
print("Not a valid matrix")
return
# driver code
if __name__ == "__main__":
a = ([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
spiralPrint(a)
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
this is code for forecasting
but i modified it and used it for safety checker of data
for ex: you have a online shop and for some reason some data are
missing (the amount of data that u expected are not supposed to be)
then we can use it
*ps : 1. ofc we can use normal statistic method but in this case
the data is quite absurd and only a little^^
2. ofc u can use this and modified it for forecasting purpose
for the next 3 months sales or something,
u can just adjust it for ur own purpose
"""
import numpy as np
import pandas as pd
from sklearn.preprocessing import Normalizer
from sklearn.svm import SVR
from statsmodels.tsa.statespace.sarimax import SARIMAX
def linear_regression_prediction(
train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list
) -> float:
"""
First method: linear regression
input : training data (date, total_user, total_event) in list of float
output : list of total user prediction in float
>>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2])
>>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors
True
"""
x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)])
y = np.array(train_usr)
beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y)
return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2])
def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float:
"""
second method: Sarimax
sarimax is a statistic method which using previous input
and learn its pattern to predict future data
input : training data (total_user, with exog data = total_event) in list of float
output : list of total user prediction in float
>>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2])
6.6666671111109626
"""
order = (1, 2, 1)
seasonal_order = (1, 1, 0, 7)
model = SARIMAX(
train_user, exog=train_match, order=order, seasonal_order=seasonal_order
)
model_fit = model.fit(disp=False, maxiter=600, method="nm")
result = model_fit.predict(1, len(test_match), exog=[test_match])
return result[0]
def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:
"""
Third method: Support vector regressor
svr is quite the same with svm(support vector machine)
it uses the same principles as the SVM for classification,
with only a few minor differences and the only different is that
it suits better for regression purpose
input : training data (date, total_user, total_event) in list of float
where x = list of set (date and total event)
output : list of total user prediction in float
>>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4])
1.634932078116079
"""
regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1)
regressor.fit(x_train, train_user)
y_pred = regressor.predict(x_test)
return y_pred[0]
def interquartile_range_checker(train_user: list) -> float:
"""
Optional method: interquatile range
input : list of total user in float
output : low limit of input in float
this method can be used to check whether some data is outlier or not
>>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10])
2.8
"""
train_user.sort()
q1 = np.percentile(train_user, 25)
q3 = np.percentile(train_user, 75)
iqr = q3 - q1
low_lim = q1 - (iqr * 0.1)
return low_lim
def data_safety_checker(list_vote: list, actual_result: float) -> None:
"""
Used to review all the votes (list result prediction)
and compare it to the actual result.
input : list of predictions
output : print whether it's safe or not
>>> data_safety_checker([2,3,4],5.0)
Today's data is not safe.
"""
safe = 0
not_safe = 0
for i in list_vote:
if i > actual_result:
safe = not_safe + 1
else:
if abs(abs(i) - abs(actual_result)) <= 0.1:
safe = safe + 1
else:
not_safe = not_safe + 1
print(f"Today's data is {'not ' if safe <= not_safe else ''}safe.")
# data_input_df = pd.read_csv("ex_data.csv", header=None)
data_input = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]]
data_input_df = pd.DataFrame(data_input, columns=["total_user", "total_even", "days"])
"""
data column = total user in a day, how much online event held in one day,
what day is that(sunday-saturday)
"""
# start normalization
normalize_df = Normalizer().fit_transform(data_input_df.values)
# split data
total_date = normalize_df[:, 2].tolist()
total_user = normalize_df[:, 0].tolist()
total_match = normalize_df[:, 1].tolist()
# for svr (input variable = total date and total match)
x = normalize_df[:, [1, 2]].tolist()
x_train = x[: len(x) - 1]
x_test = x[len(x) - 1 :]
# for linear reression & sarimax
trn_date = total_date[: len(total_date) - 1]
trn_user = total_user[: len(total_user) - 1]
trn_match = total_match[: len(total_match) - 1]
tst_date = total_date[len(total_date) - 1 :]
tst_user = total_user[len(total_user) - 1 :]
tst_match = total_match[len(total_match) - 1 :]
# voting system with forecasting
res_vote = []
res_vote.append(
linear_regression_prediction(trn_date, trn_user, trn_match, tst_date, tst_match)
)
res_vote.append(sarimax_predictor(trn_user, trn_match, tst_match))
res_vote.append(support_vector_regressor(x_train, x_test, trn_user))
# check the safety of todays'data^^
data_safety_checker(res_vote, tst_user)
| """
this is code for forecasting
but i modified it and used it for safety checker of data
for ex: you have a online shop and for some reason some data are
missing (the amount of data that u expected are not supposed to be)
then we can use it
*ps : 1. ofc we can use normal statistic method but in this case
the data is quite absurd and only a little^^
2. ofc u can use this and modified it for forecasting purpose
for the next 3 months sales or something,
u can just adjust it for ur own purpose
"""
import numpy as np
import pandas as pd
from sklearn.preprocessing import Normalizer
from sklearn.svm import SVR
from statsmodels.tsa.statespace.sarimax import SARIMAX
def linear_regression_prediction(
train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list
) -> float:
"""
First method: linear regression
input : training data (date, total_user, total_event) in list of float
output : list of total user prediction in float
>>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2])
>>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors
True
"""
x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)])
y = np.array(train_usr)
beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y)
return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2])
def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float:
"""
second method: Sarimax
sarimax is a statistic method which using previous input
and learn its pattern to predict future data
input : training data (total_user, with exog data = total_event) in list of float
output : list of total user prediction in float
>>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2])
6.6666671111109626
"""
order = (1, 2, 1)
seasonal_order = (1, 1, 0, 7)
model = SARIMAX(
train_user, exog=train_match, order=order, seasonal_order=seasonal_order
)
model_fit = model.fit(disp=False, maxiter=600, method="nm")
result = model_fit.predict(1, len(test_match), exog=[test_match])
return result[0]
def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:
"""
Third method: Support vector regressor
svr is quite the same with svm(support vector machine)
it uses the same principles as the SVM for classification,
with only a few minor differences and the only different is that
it suits better for regression purpose
input : training data (date, total_user, total_event) in list of float
where x = list of set (date and total event)
output : list of total user prediction in float
>>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4])
1.634932078116079
"""
regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1)
regressor.fit(x_train, train_user)
y_pred = regressor.predict(x_test)
return y_pred[0]
def interquartile_range_checker(train_user: list) -> float:
"""
Optional method: interquatile range
input : list of total user in float
output : low limit of input in float
this method can be used to check whether some data is outlier or not
>>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10])
2.8
"""
train_user.sort()
q1 = np.percentile(train_user, 25)
q3 = np.percentile(train_user, 75)
iqr = q3 - q1
low_lim = q1 - (iqr * 0.1)
return low_lim
def data_safety_checker(list_vote: list, actual_result: float) -> None:
"""
Used to review all the votes (list result prediction)
and compare it to the actual result.
input : list of predictions
output : print whether it's safe or not
>>> data_safety_checker([2,3,4],5.0)
Today's data is not safe.
"""
safe = 0
not_safe = 0
for i in list_vote:
if i > actual_result:
safe = not_safe + 1
else:
if abs(abs(i) - abs(actual_result)) <= 0.1:
safe = safe + 1
else:
not_safe = not_safe + 1
print(f"Today's data is {'not ' if safe <= not_safe else ''}safe.")
# data_input_df = pd.read_csv("ex_data.csv", header=None)
data_input = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]]
data_input_df = pd.DataFrame(data_input, columns=["total_user", "total_even", "days"])
"""
data column = total user in a day, how much online event held in one day,
what day is that(sunday-saturday)
"""
# start normalization
normalize_df = Normalizer().fit_transform(data_input_df.values)
# split data
total_date = normalize_df[:, 2].tolist()
total_user = normalize_df[:, 0].tolist()
total_match = normalize_df[:, 1].tolist()
# for svr (input variable = total date and total match)
x = normalize_df[:, [1, 2]].tolist()
x_train = x[: len(x) - 1]
x_test = x[len(x) - 1 :]
# for linear reression & sarimax
trn_date = total_date[: len(total_date) - 1]
trn_user = total_user[: len(total_user) - 1]
trn_match = total_match[: len(total_match) - 1]
tst_date = total_date[len(total_date) - 1 :]
tst_user = total_user[len(total_user) - 1 :]
tst_match = total_match[len(total_match) - 1 :]
# voting system with forecasting
res_vote = []
res_vote.append(
linear_regression_prediction(trn_date, trn_user, trn_match, tst_date, tst_match)
)
res_vote.append(sarimax_predictor(trn_user, trn_match, tst_match))
res_vote.append(support_vector_regressor(x_train, x_test, trn_user))
# check the safety of todays'data^^
data_safety_checker(res_vote, tst_user)
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| a b 20
a c 18
a d 22
a e 26
b c 10
b d 11
b e 12
c d 23
c e 24
d e 40
| a b 20
a c 18
a d 22
a e 26
b c 10
b d 11
b e 12
c d 23
c e 24
d e 40
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Breath First Search (BFS) can be used when finding the shortest path
from a given source node to a target node in an unweighted graph.
"""
from __future__ import annotations
graph = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
class Graph:
def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None:
"""
Graph is implemented as dictionary of adjacency lists. Also,
Source vertex have to be defined upon initialization.
"""
self.graph = graph
# mapping node to its parent in resulting breadth first tree
self.parent: dict[str, str | None] = {}
self.source_vertex = source_vertex
def breath_first_search(self) -> None:
"""
This function is a helper for running breath first search on this graph.
>>> g = Graph(graph, "G")
>>> g.breath_first_search()
>>> g.parent
{'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'}
"""
visited = {self.source_vertex}
self.parent[self.source_vertex] = None
queue = [self.source_vertex] # first in first out queue
while queue:
vertex = queue.pop(0)
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(adjacent_vertex)
self.parent[adjacent_vertex] = vertex
queue.append(adjacent_vertex)
def shortest_path(self, target_vertex: str) -> str:
"""
This shortest path function returns a string, describing the result:
1.) No path is found. The string is a human readable message to indicate this.
2.) The shortest path is found. The string is in the form
`v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target
vertex, if it exists separately.
>>> g = Graph(graph, "G")
>>> g.breath_first_search()
Case 1 - No path is found.
>>> g.shortest_path("Foo")
'No path from vertex:G to vertex:Foo'
Case 2 - The path is found.
>>> g.shortest_path("D")
'G->C->A->B->D'
>>> g.shortest_path("G")
'G'
"""
if target_vertex == self.source_vertex:
return self.source_vertex
target_vertex_parent = self.parent.get(target_vertex)
if target_vertex_parent is None:
return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}"
return self.shortest_path(target_vertex_parent) + f"->{target_vertex}"
if __name__ == "__main__":
g = Graph(graph, "G")
g.breath_first_search()
print(g.shortest_path("D"))
print(g.shortest_path("G"))
print(g.shortest_path("Foo"))
| """Breath First Search (BFS) can be used when finding the shortest path
from a given source node to a target node in an unweighted graph.
"""
from __future__ import annotations
graph = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
class Graph:
def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None:
"""
Graph is implemented as dictionary of adjacency lists. Also,
Source vertex have to be defined upon initialization.
"""
self.graph = graph
# mapping node to its parent in resulting breadth first tree
self.parent: dict[str, str | None] = {}
self.source_vertex = source_vertex
def breath_first_search(self) -> None:
"""
This function is a helper for running breath first search on this graph.
>>> g = Graph(graph, "G")
>>> g.breath_first_search()
>>> g.parent
{'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'}
"""
visited = {self.source_vertex}
self.parent[self.source_vertex] = None
queue = [self.source_vertex] # first in first out queue
while queue:
vertex = queue.pop(0)
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(adjacent_vertex)
self.parent[adjacent_vertex] = vertex
queue.append(adjacent_vertex)
def shortest_path(self, target_vertex: str) -> str:
"""
This shortest path function returns a string, describing the result:
1.) No path is found. The string is a human readable message to indicate this.
2.) The shortest path is found. The string is in the form
`v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target
vertex, if it exists separately.
>>> g = Graph(graph, "G")
>>> g.breath_first_search()
Case 1 - No path is found.
>>> g.shortest_path("Foo")
'No path from vertex:G to vertex:Foo'
Case 2 - The path is found.
>>> g.shortest_path("D")
'G->C->A->B->D'
>>> g.shortest_path("G")
'G'
"""
if target_vertex == self.source_vertex:
return self.source_vertex
target_vertex_parent = self.parent.get(target_vertex)
if target_vertex_parent is None:
return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}"
return self.shortest_path(target_vertex_parent) + f"->{target_vertex}"
if __name__ == "__main__":
g = Graph(graph, "G")
g.breath_first_search()
print(g.shortest_path("D"))
print(g.shortest_path("G"))
print(g.shortest_path("Foo"))
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Pandigital prime
Problem 41: https://projecteuler.net/problem=41
We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
So we will check only 7 digit pandigital numbers to obtain the largest possible
pandigital prime.
"""
from __future__ import annotations
from itertools import permutations
from math import sqrt
def is_prime(n: int) -> bool:
"""
Returns True if n is prime,
False otherwise.
>>> is_prime(67483)
False
>>> is_prime(563)
True
>>> is_prime(87)
False
"""
if n % 2 == 0:
return False
for i in range(3, int(sqrt(n) + 1), 2):
if n % i == 0:
return False
return True
def solution(n: int = 7) -> int:
"""
Returns the maximum pandigital prime number of length n.
If there are none, then it will return 0.
>>> solution(2)
0
>>> solution(4)
4231
>>> solution(7)
7652413
"""
pandigital_str = "".join(str(i) for i in range(1, n + 1))
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
pandigitals = [num for num in perm_list if is_prime(num)]
return max(pandigitals) if pandigitals else 0
if __name__ == "__main__":
print(f"{solution() = }")
| """
Pandigital prime
Problem 41: https://projecteuler.net/problem=41
We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
So we will check only 7 digit pandigital numbers to obtain the largest possible
pandigital prime.
"""
from __future__ import annotations
from itertools import permutations
from math import sqrt
def is_prime(n: int) -> bool:
"""
Returns True if n is prime,
False otherwise.
>>> is_prime(67483)
False
>>> is_prime(563)
True
>>> is_prime(87)
False
"""
if n % 2 == 0:
return False
for i in range(3, int(sqrt(n) + 1), 2):
if n % i == 0:
return False
return True
def solution(n: int = 7) -> int:
"""
Returns the maximum pandigital prime number of length n.
If there are none, then it will return 0.
>>> solution(2)
0
>>> solution(4)
4231
>>> solution(7)
7652413
"""
pandigital_str = "".join(str(i) for i in range(1, n + 1))
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
pandigitals = [num for num in perm_list if is_prime(num)]
return max(pandigitals) if pandigitals else 0
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Minimalist file that allows pytest to find and run the Test unittest. For details, see:
http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery
"""
from .prime_check import Test
Test()
| """
Minimalist file that allows pytest to find and run the Test unittest. For details, see:
http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery
"""
from .prime_check import Test
Test()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Queue represented by a pseudo stack (represented by a list with pop and append)"""
class Queue:
def __init__(self):
self.stack = []
self.length = 0
def __str__(self):
printed = "<" + str(self.stack)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.stack.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.rotate(1)
dequeued = self.stack[self.length - 1]
self.stack = self.stack[:-1]
self.rotate(self.length - 1)
self.length = self.length - 1
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
temp = self.stack[0]
self.stack = self.stack[1:]
self.put(temp)
self.length = self.length - 1
"""Reports item at the front of self
@return item at front of self.stack"""
def front(self):
front = self.get()
self.put(front)
self.rotate(self.length - 1)
return front
"""Returns the length of this.stack"""
def size(self):
return self.length
| """Queue represented by a pseudo stack (represented by a list with pop and append)"""
class Queue:
def __init__(self):
self.stack = []
self.length = 0
def __str__(self):
printed = "<" + str(self.stack)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.stack.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.rotate(1)
dequeued = self.stack[self.length - 1]
self.stack = self.stack[:-1]
self.rotate(self.length - 1)
self.length = self.length - 1
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
temp = self.stack[0]
self.stack = self.stack[1:]
self.put(temp)
self.length = self.length - 1
"""Reports item at the front of self
@return item at front of self.stack"""
def front(self):
front = self.get()
self.put(front)
self.rotate(self.length - 1)
return front
"""Returns the length of this.stack"""
def size(self):
return self.length
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Python3 program to evaluate a prefix expression.
"""
calc = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
}
def is_operand(c):
"""
Return True if the given char c is an operand, e.g. it is a number
>>> is_operand("1")
True
>>> is_operand("+")
False
"""
return c.isdigit()
def evaluate(expression):
"""
Evaluate a given expression in prefix notation.
Asserts that the given expression is valid.
>>> evaluate("+ 9 * 2 6")
21
>>> evaluate("/ * 10 2 + 4 1 ")
4.0
"""
stack = []
# iterate over the string in reverse order
for c in expression.split()[::-1]:
# push operand to stack
if is_operand(c):
stack.append(int(c))
else:
# pop values from stack can calculate the result
# push the result onto the stack again
o1 = stack.pop()
o2 = stack.pop()
stack.append(calc[c](o1, o2))
return stack.pop()
# Driver code
if __name__ == "__main__":
test_expression = "+ 9 * 2 6"
print(evaluate(test_expression))
test_expression = "/ * 10 2 + 4 1 "
print(evaluate(test_expression))
| """
Python3 program to evaluate a prefix expression.
"""
calc = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
}
def is_operand(c):
"""
Return True if the given char c is an operand, e.g. it is a number
>>> is_operand("1")
True
>>> is_operand("+")
False
"""
return c.isdigit()
def evaluate(expression):
"""
Evaluate a given expression in prefix notation.
Asserts that the given expression is valid.
>>> evaluate("+ 9 * 2 6")
21
>>> evaluate("/ * 10 2 + 4 1 ")
4.0
"""
stack = []
# iterate over the string in reverse order
for c in expression.split()[::-1]:
# push operand to stack
if is_operand(c):
stack.append(int(c))
else:
# pop values from stack can calculate the result
# push the result onto the stack again
o1 = stack.pop()
o2 = stack.pop()
stack.append(calc[c](o1, o2))
return stack.pop()
# Driver code
if __name__ == "__main__":
test_expression = "+ 9 * 2 6"
print(evaluate(test_expression))
test_expression = "/ * 10 2 + 4 1 "
print(evaluate(test_expression))
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Wavelet tree is a data-structure designed to efficiently answer various range queries
for arrays. Wavelets trees are different from other binary trees in the sense that
the nodes are split based on the actual values of the elements and not on indices,
such as the with segment trees or fenwick trees. You can read more about them here:
1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf
2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s
3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s
"""
from __future__ import annotations
test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
class Node:
def __init__(self, length: int) -> None:
self.minn: int = -1
self.maxx: int = -1
self.map_left: list[int] = [-1] * length
self.left: Node | None = None
self.right: Node | None = None
def __repr__(self) -> str:
"""
>>> node = Node(length=27)
>>> repr(node)
'min_value: -1, max_value: -1'
>>> repr(node) == str(node)
True
"""
return f"min_value: {self.minn}, max_value: {self.maxx}"
def build_tree(arr: list[int]) -> Node:
"""
Builds the tree for arr and returns the root
of the constructed tree
>>> build_tree(test_array)
min_value: 0, max_value: 9
"""
root = Node(len(arr))
root.minn, root.maxx = min(arr), max(arr)
# Leaf node case where the node contains only one unique value
if root.minn == root.maxx:
return root
"""
Take the mean of min and max element of arr as the pivot and
partition arr into left_arr and right_arr with all elements <= pivot in the
left_arr and the rest in right_arr, maintaining the order of the elements,
then recursively build trees for left_arr and right_arr
"""
pivot = (root.minn + root.maxx) // 2
left_arr, right_arr = [], []
for index, num in enumerate(arr):
if num <= pivot:
left_arr.append(num)
else:
right_arr.append(num)
root.map_left[index] = len(left_arr)
root.left = build_tree(left_arr)
root.right = build_tree(right_arr)
return root
def rank_till_index(node: Node, num: int, index: int) -> int:
"""
Returns the number of occurrences of num in interval [0, index] in the list
>>> root = build_tree(test_array)
>>> rank_till_index(root, 6, 6)
1
>>> rank_till_index(root, 2, 0)
1
>>> rank_till_index(root, 1, 10)
2
>>> rank_till_index(root, 17, 7)
0
>>> rank_till_index(root, 0, 9)
1
"""
if index < 0:
return 0
# Leaf node cases
if node.minn == node.maxx:
return index + 1 if node.minn == num else 0
pivot = (node.minn + node.maxx) // 2
if num <= pivot:
# go the left subtree and map index to the left subtree
return rank_till_index(node.left, num, node.map_left[index] - 1)
else:
# go to the right subtree and map index to the right subtree
return rank_till_index(node.right, num, index - node.map_left[index])
def rank(node: Node, num: int, start: int, end: int) -> int:
"""
Returns the number of occurrences of num in interval [start, end] in the list
>>> root = build_tree(test_array)
>>> rank(root, 6, 3, 13)
2
>>> rank(root, 2, 0, 19)
4
>>> rank(root, 9, 2 ,2)
0
>>> rank(root, 0, 5, 10)
2
"""
if start > end:
return 0
rank_till_end = rank_till_index(node, num, end)
rank_before_start = rank_till_index(node, num, start - 1)
return rank_till_end - rank_before_start
def quantile(node: Node, index: int, start: int, end: int) -> int:
"""
Returns the index'th smallest element in interval [start, end] in the list
index is 0-indexed
>>> root = build_tree(test_array)
>>> quantile(root, 2, 2, 5)
5
>>> quantile(root, 5, 2, 13)
4
>>> quantile(root, 0, 6, 6)
8
>>> quantile(root, 4, 2, 5)
-1
"""
if index > (end - start) or start > end:
return -1
# Leaf node case
if node.minn == node.maxx:
return node.minn
# Number of elements in the left subtree in interval [start, end]
num_elements_in_left_tree = node.map_left[end] - (
node.map_left[start - 1] if start else 0
)
if num_elements_in_left_tree > index:
return quantile(
node.left,
index,
(node.map_left[start - 1] if start else 0),
node.map_left[end] - 1,
)
else:
return quantile(
node.right,
index - num_elements_in_left_tree,
start - (node.map_left[start - 1] if start else 0),
end - node.map_left[end],
)
def range_counting(
node: Node, start: int, end: int, start_num: int, end_num: int
) -> int:
"""
Returns the number of elememts in range [start_num, end_num]
in interval [start, end] in the list
>>> root = build_tree(test_array)
>>> range_counting(root, 1, 10, 3, 7)
3
>>> range_counting(root, 2, 2, 1, 4)
1
>>> range_counting(root, 0, 19, 0, 100)
20
>>> range_counting(root, 1, 0, 1, 100)
0
>>> range_counting(root, 0, 17, 100, 1)
0
"""
if (
start > end
or start_num > end_num
or node.minn > end_num
or node.maxx < start_num
):
return 0
if start_num <= node.minn and node.maxx <= end_num:
return end - start + 1
left = range_counting(
node.left,
(node.map_left[start - 1] if start else 0),
node.map_left[end] - 1,
start_num,
end_num,
)
right = range_counting(
node.right,
start - (node.map_left[start - 1] if start else 0),
end - node.map_left[end],
start_num,
end_num,
)
return left + right
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Wavelet tree is a data-structure designed to efficiently answer various range queries
for arrays. Wavelets trees are different from other binary trees in the sense that
the nodes are split based on the actual values of the elements and not on indices,
such as the with segment trees or fenwick trees. You can read more about them here:
1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf
2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s
3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s
"""
from __future__ import annotations
test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
class Node:
def __init__(self, length: int) -> None:
self.minn: int = -1
self.maxx: int = -1
self.map_left: list[int] = [-1] * length
self.left: Node | None = None
self.right: Node | None = None
def __repr__(self) -> str:
"""
>>> node = Node(length=27)
>>> repr(node)
'min_value: -1, max_value: -1'
>>> repr(node) == str(node)
True
"""
return f"min_value: {self.minn}, max_value: {self.maxx}"
def build_tree(arr: list[int]) -> Node:
"""
Builds the tree for arr and returns the root
of the constructed tree
>>> build_tree(test_array)
min_value: 0, max_value: 9
"""
root = Node(len(arr))
root.minn, root.maxx = min(arr), max(arr)
# Leaf node case where the node contains only one unique value
if root.minn == root.maxx:
return root
"""
Take the mean of min and max element of arr as the pivot and
partition arr into left_arr and right_arr with all elements <= pivot in the
left_arr and the rest in right_arr, maintaining the order of the elements,
then recursively build trees for left_arr and right_arr
"""
pivot = (root.minn + root.maxx) // 2
left_arr, right_arr = [], []
for index, num in enumerate(arr):
if num <= pivot:
left_arr.append(num)
else:
right_arr.append(num)
root.map_left[index] = len(left_arr)
root.left = build_tree(left_arr)
root.right = build_tree(right_arr)
return root
def rank_till_index(node: Node, num: int, index: int) -> int:
"""
Returns the number of occurrences of num in interval [0, index] in the list
>>> root = build_tree(test_array)
>>> rank_till_index(root, 6, 6)
1
>>> rank_till_index(root, 2, 0)
1
>>> rank_till_index(root, 1, 10)
2
>>> rank_till_index(root, 17, 7)
0
>>> rank_till_index(root, 0, 9)
1
"""
if index < 0:
return 0
# Leaf node cases
if node.minn == node.maxx:
return index + 1 if node.minn == num else 0
pivot = (node.minn + node.maxx) // 2
if num <= pivot:
# go the left subtree and map index to the left subtree
return rank_till_index(node.left, num, node.map_left[index] - 1)
else:
# go to the right subtree and map index to the right subtree
return rank_till_index(node.right, num, index - node.map_left[index])
def rank(node: Node, num: int, start: int, end: int) -> int:
"""
Returns the number of occurrences of num in interval [start, end] in the list
>>> root = build_tree(test_array)
>>> rank(root, 6, 3, 13)
2
>>> rank(root, 2, 0, 19)
4
>>> rank(root, 9, 2 ,2)
0
>>> rank(root, 0, 5, 10)
2
"""
if start > end:
return 0
rank_till_end = rank_till_index(node, num, end)
rank_before_start = rank_till_index(node, num, start - 1)
return rank_till_end - rank_before_start
def quantile(node: Node, index: int, start: int, end: int) -> int:
"""
Returns the index'th smallest element in interval [start, end] in the list
index is 0-indexed
>>> root = build_tree(test_array)
>>> quantile(root, 2, 2, 5)
5
>>> quantile(root, 5, 2, 13)
4
>>> quantile(root, 0, 6, 6)
8
>>> quantile(root, 4, 2, 5)
-1
"""
if index > (end - start) or start > end:
return -1
# Leaf node case
if node.minn == node.maxx:
return node.minn
# Number of elements in the left subtree in interval [start, end]
num_elements_in_left_tree = node.map_left[end] - (
node.map_left[start - 1] if start else 0
)
if num_elements_in_left_tree > index:
return quantile(
node.left,
index,
(node.map_left[start - 1] if start else 0),
node.map_left[end] - 1,
)
else:
return quantile(
node.right,
index - num_elements_in_left_tree,
start - (node.map_left[start - 1] if start else 0),
end - node.map_left[end],
)
def range_counting(
node: Node, start: int, end: int, start_num: int, end_num: int
) -> int:
"""
Returns the number of elememts in range [start_num, end_num]
in interval [start, end] in the list
>>> root = build_tree(test_array)
>>> range_counting(root, 1, 10, 3, 7)
3
>>> range_counting(root, 2, 2, 1, 4)
1
>>> range_counting(root, 0, 19, 0, 100)
20
>>> range_counting(root, 1, 0, 1, 100)
0
>>> range_counting(root, 0, 17, 100, 1)
0
"""
if (
start > end
or start_num > end_num
or node.minn > end_num
or node.maxx < start_num
):
return 0
if start_num <= node.minn and node.maxx <= end_num:
return end - start + 1
left = range_counting(
node.left,
(node.map_left[start - 1] if start else 0),
node.map_left[end] - 1,
start_num,
end_num,
)
right = range_counting(
node.right,
start - (node.map_left[start - 1] if start else 0),
end - node.map_left[end],
start_num,
end_num,
)
return left + right
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,558 | mandelbrot.py: Commenting out long running tests | ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cclauss | "2021-10-23T13:24:39Z" | "2021-10-23T16:15:31Z" | 218d8921dbb264c9636bef5bd10e23acafd032eb | bd9464e4ac6ccccd4699bf52bddefa2bfb1dafea | mandelbrot.py: Commenting out long running tests. ### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is pure Python implementation of sentinel linear search algorithm
For doctests run following command:
python -m doctest -v sentinel_linear_search.py
or
python3 -m doctest -v sentinel_linear_search.py
For manual testing run:
python sentinel_linear_search.py
"""
def sentinel_linear_search(sequence, target):
"""Pure implementation of sentinel linear search algorithm in Python
:param sequence: some sequence with comparable items
:param target: item value to search
:return: index of found item or None if item is not found
Examples:
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
0
>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
4
>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
1
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
"""
sequence.append(target)
index = 0
while sequence[index] != target:
index += 1
sequence.pop()
if index == len(sequence):
return None
return index
if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item) for item in user_input.split(",")]
target_input = input("Enter a single number to be found in the list:\n")
target = int(target_input)
result = sentinel_linear_search(sequence, target)
if result is not None:
print(f"{target} found at positions: {result}")
else:
print("Not found")
| """
This is pure Python implementation of sentinel linear search algorithm
For doctests run following command:
python -m doctest -v sentinel_linear_search.py
or
python3 -m doctest -v sentinel_linear_search.py
For manual testing run:
python sentinel_linear_search.py
"""
def sentinel_linear_search(sequence, target):
"""Pure implementation of sentinel linear search algorithm in Python
:param sequence: some sequence with comparable items
:param target: item value to search
:return: index of found item or None if item is not found
Examples:
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
0
>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
4
>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
1
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
"""
sequence.append(target)
index = 0
while sequence[index] != target:
index += 1
sequence.pop()
if index == len(sequence):
return None
return index
if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item) for item in user_input.split(",")]
target_input = input("Enter a single number to be found in the list:\n")
target = int(target_input)
result = sentinel_linear_search(sequence, target)
if result is not None:
print(f"{target} found at positions: {result}")
else:
print("Not found")
| -1 |
TheAlgorithms/Python | 5,518 | [mypy] Fix type annotations in `data_structures/binary_tree` | ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| shermanhui | "2021-10-22T04:43:40Z" | "2021-10-22T14:07:05Z" | d82cf5292fbd0ffe1764a1da5c96a39b244618eb | 629848e3721d9354d25fad6cb4729e6afdbbf799 | [mypy] Fix type annotations in `data_structures/binary_tree`. ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
|
## Arithmetic Analysis
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py)
* [Gaussian Elimination](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py)
* [Lu Decomposition](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_raphson.py)
* [Secant Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/secant_method.py)
## Backtracking
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Hamiltonian Cycle](https://github.com/TheAlgorithms/Python/blob/master/backtracking/hamiltonian_cycle.py)
* [Knight Tour](https://github.com/TheAlgorithms/Python/blob/master/backtracking/knight_tour.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [N Queens Math](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens_math.py)
* [Rat In Maze](https://github.com/TheAlgorithms/Python/blob/master/backtracking/rat_in_maze.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
* [Binary Shifts](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_number_of_one_bits.py)
* [Reverse Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/reverse_bits.py)
* [Single Bit Manipulation Operations](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/single_bit_manipulation_operations.py)
## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
* [Modular Division](https://github.com/TheAlgorithms/Python/blob/master/blockchain/modular_division.py)
## Boolean Algebra
* [Quine Mc Cluskey](https://github.com/TheAlgorithms/Python/blob/master/boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/conways_game_of_life.py)
* [Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/game_of_life.py)
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Baconian Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/baconian_cipher.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64 Encoding](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64_encoding.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/caesar_cipher.py)
* [Cryptomath Module](https://github.com/TheAlgorithms/Python/blob/master/ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](https://github.com/TheAlgorithms/Python/blob/master/ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Diffie Hellman](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie_hellman.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
* [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
* [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
* [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
* [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
* [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
* [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
* [Rot13](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rot13.py)
* [Rsa Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_cipher.py)
* [Rsa Factorization](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_factorization.py)
* [Rsa Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/trafid_cipher.py)
* [Transposition Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/vigenere_cipher.py)
* [Xor Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](https://github.com/TheAlgorithms/Python/blob/master/compression/burrows_wheeler.py)
* [Huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py)
* [Lempel Ziv](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv.py)
* [Lempel Ziv Decompress](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](https://github.com/TheAlgorithms/Python/blob/master/compression/peak_signal_to_noise_ratio.py)
## Computer Vision
* [Cnn Classification](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/cnn_classification.py)
* [Harris Corner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harris_corner.py)
* [Mean Threshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mean_threshold.py)
## Conversions
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)
* [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_hexadecimal.py)
* [Decimal To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_octal.py)
* [Hex To Bin](https://github.com/TheAlgorithms/Python/blob/master/conversions/hex_to_bin.py)
* [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.py)
* [Length Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/length_conversion.py)
* [Molecular Chemistry](https://github.com/TheAlgorithms/Python/blob/master/conversions/molecular_chemistry.py)
* [Octal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/octal_to_decimal.py)
* [Prefix Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/prefix_conversions.py)
* [Rgb Hsv Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/rgb_hsv_conversion.py)
* [Roman Numerals](https://github.com/TheAlgorithms/Python/blob/master/conversions/roman_numerals.py)
* [Temperature Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/temperature_conversions.py)
* [Weight Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* [Wavelet Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
* [Hash Table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/binomial_heap.py)
* [Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap.py)
* [Heap Generic](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap_generic.py)
* [Max Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/max_heap.py)
* [Min Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/min_heap.py)
* [Randomized Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/randomized_heap.py)
* [Skew Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
* [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/print_reverse.py)
* [Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/singly_linked_list.py)
* [Skip List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/skip_list.py)
* [Swap Nodes](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue.py)
* [Double Ended Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/double_ended_queue.py)
* [Linked Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/linked_queue.py)
* [Priority Queue Using List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/priority_queue_using_list.py)
* [Queue On List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
* [Linked Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/linked_stack.py)
* [Next Greater Element](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/prefix_evaluation.py)
* [Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack.py)
* [Stack Using Dll](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_using_dll.py)
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_brightness.py)
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py)
* [Convolve](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/convolve.py)
* [Gaussian Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/median_filter.py)
* [Sobel Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/rotation/rotation.py)
* [Sepia](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/sepia.py)
* [Test Digital Image Processing](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/inversions.py)
* [Kth Order Statistic](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_subarray_sum.py)
* [Mergesort](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/mergesort.py)
* [Peak](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/peak.py)
* [Power](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/abbreviation.py)
* [Bitmask](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/bitmask.py)
* [Catalan Numbers](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/climbing_stairs.py)
* [Edit Distance](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py)
* [Factorial](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/factorial.py)
* [Fast Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fast_fibonacci.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fibonacci.py)
* [Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/iterating_through_submasks.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/knapsack.py)
* [Longest Common Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](https://github.com/TheAlgorithms/Python/blob/master/electronics/carrier_concentration.py)
* [Electric Power](https://github.com/TheAlgorithms/Python/blob/master/electronics/electric_power.py)
* [Ohms Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/ohms_law.py)
## File Transfer
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
* Tests
* [Test Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/tests/test_send_file.py)
## Fractals
* [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py)
* [Koch Snowflake](https://github.com/TheAlgorithms/Python/blob/master/fractals/koch_snowflake.py)
* [Mandelbrot](https://github.com/TheAlgorithms/Python/blob/master/fractals/mandelbrot.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](https://github.com/TheAlgorithms/Python/blob/master/fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](https://github.com/TheAlgorithms/Python/blob/master/graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](https://github.com/TheAlgorithms/Python/blob/master/graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/a_star.py)
* [Articulation Points](https://github.com/TheAlgorithms/Python/blob/master/graphs/articulation_points.py)
* [Basic Graphs](https://github.com/TheAlgorithms/Python/blob/master/graphs/basic_graphs.py)
* [Bellman Ford](https://github.com/TheAlgorithms/Python/blob/master/graphs/bellman_ford.py)
* [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_breadth_first_search.py)
* [Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/boruvka.py)
* [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
* [Breadth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
* [Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/connected_components.py)
* [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
* [Depth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search_2.py)
* [Dijkstra](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra.py)
* [Dijkstra 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_2.py)
* [Dijkstra Algorithm](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_algorithm.py)
* [Dinic](https://github.com/TheAlgorithms/Python/blob/master/graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](https://github.com/TheAlgorithms/Python/blob/master/graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](https://github.com/TheAlgorithms/Python/blob/master/graphs/even_tree.py)
* [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py)
* [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py)
* [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py)
* [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py)
* [Greedy Best First](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
* [Karger](https://github.com/TheAlgorithms/Python/blob/master/graphs/karger.py)
* [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/graphs/markov_chain.py)
* [Matching Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/matching_min_vertex_cover.py)
* [Minimum Spanning Tree Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
* [Strongly Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/strongly_connected_components.py)
* [Tarjans Scc](https://github.com/TheAlgorithms/Python/blob/master/graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](https://github.com/TheAlgorithms/Python/blob/master/greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](https://github.com/TheAlgorithms/Python/blob/master/hashes/adler32.py)
* [Chaos Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/chaos_machine.py)
* [Djb2](https://github.com/TheAlgorithms/Python/blob/master/hashes/djb2.py)
* [Enigma Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/enigma_machine.py)
* [Hamming Code](https://github.com/TheAlgorithms/Python/blob/master/hashes/hamming_code.py)
* [Luhn](https://github.com/TheAlgorithms/Python/blob/master/hashes/luhn.py)
* [Md5](https://github.com/TheAlgorithms/Python/blob/master/hashes/md5.py)
* [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py)
* [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py)
## Knapsack
* [Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/greedy_knapsack.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/conjugate_gradient.py)
* [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py)
* [Polynom For Points](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/polynom_for_points.py)
* [Power Iteration](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/astar.py)
* [Data Transformations](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/data_transformations.py)
* [Decision Tree](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/decision_tree.py)
* Forecasting
* [Run](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_descent.py)
* [K Means Clust](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_means_clust.py)
* [K Nearest Neighbours](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_regression.py)
* [Logistic Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/polymonial_regression.py)
* [Random Forest Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_regressor.py)
* [Scoring Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/similarity_search.py)
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
* [Word Frequency Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)
* [Add](https://github.com/TheAlgorithms/Python/blob/master/maths/add.py)
* [Aliquot Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/aliquot_sum.py)
* [Allocation Number](https://github.com/TheAlgorithms/Python/blob/master/maths/allocation_number.py)
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)
* [Bailey Borwein Plouffe](https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py)
* [Basic Maths](https://github.com/TheAlgorithms/Python/blob/master/maths/basic_maths.py)
* [Binary Exp Mod](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py)
* [Binary Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py)
* [Binary Exponentiation 2](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_3.py)
* [Binomial Coefficient](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_coefficient.py)
* [Binomial Distribution](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_distribution.py)
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/maths/bisection.py)
* [Ceil](https://github.com/TheAlgorithms/Python/blob/master/maths/ceil.py)
* [Check Polygon](https://github.com/TheAlgorithms/Python/blob/master/maths/check_polygon.py)
* [Chudnovsky Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/chudnovsky_algorithm.py)
* [Collatz Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/collatz_sequence.py)
* [Combinations](https://github.com/TheAlgorithms/Python/blob/master/maths/combinations.py)
* [Decimal Isolate](https://github.com/TheAlgorithms/Python/blob/master/maths/decimal_isolate.py)
* [Double Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_iterative.py)
* [Double Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_recursive.py)
* [Entropy](https://github.com/TheAlgorithms/Python/blob/master/maths/entropy.py)
* [Euclidean Distance](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_distance.py)
* [Euclidean Gcd](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_gcd.py)
* [Euler Method](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_method.py)
* [Euler Modified](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_modified.py)
* [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
* [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
* [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
* [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
* [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci.py)
* [Fibonacci Sequence Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci_sequence_recursion.py)
* [Find Max](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max.py)
* [Find Max Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max_recursion.py)
* [Find Min](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min.py)
* [Find Min Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min_recursion.py)
* [Floor](https://github.com/TheAlgorithms/Python/blob/master/maths/floor.py)
* [Gamma](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma.py)
* [Gamma Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma_recursive.py)
* [Gaussian](https://github.com/TheAlgorithms/Python/blob/master/maths/gaussian.py)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/Python/blob/master/maths/greatest_common_divisor.py)
* [Greedy Coin Change](https://github.com/TheAlgorithms/Python/blob/master/maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](https://github.com/TheAlgorithms/Python/blob/master/maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](https://github.com/TheAlgorithms/Python/blob/master/maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](https://github.com/TheAlgorithms/Python/blob/master/maths/is_ip_v4_address_valid.py)
* [Is Square Free](https://github.com/TheAlgorithms/Python/blob/master/maths/is_square_free.py)
* [Jaccard Similarity](https://github.com/TheAlgorithms/Python/blob/master/maths/jaccard_similarity.py)
* [Kadanes](https://github.com/TheAlgorithms/Python/blob/master/maths/kadanes.py)
* [Karatsuba](https://github.com/TheAlgorithms/Python/blob/master/maths/karatsuba.py)
* [Krishnamurthy Number](https://github.com/TheAlgorithms/Python/blob/master/maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](https://github.com/TheAlgorithms/Python/blob/master/maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_subarray_sum.py)
* [Least Common Multiple](https://github.com/TheAlgorithms/Python/blob/master/maths/least_common_multiple.py)
* [Line Length](https://github.com/TheAlgorithms/Python/blob/master/maths/line_length.py)
* [Lucas Lehmer Primality Test](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py)
* [Lucas Series](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_series.py)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/maths/median_of_two_arrays.py)
* [Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py)
* [Mobius Function](https://github.com/TheAlgorithms/Python/blob/master/maths/mobius_function.py)
* [Modular Exponential](https://github.com/TheAlgorithms/Python/blob/master/maths/modular_exponential.py)
* [Monte Carlo](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo.py)
* [Monte Carlo Dice](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo_dice.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/maths/newton_raphson.py)
* [Number Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/number_of_digits.py)
* [Numerical Integration](https://github.com/TheAlgorithms/Python/blob/master/maths/numerical_integration.py)
* [Perfect Cube](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_cube.py)
* [Perfect Number](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_number.py)
* [Perfect Square](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_square.py)
* [Pi Monte Carlo Estimation](https://github.com/TheAlgorithms/Python/blob/master/maths/pi_monte_carlo_estimation.py)
* [Polynomial Evaluation](https://github.com/TheAlgorithms/Python/blob/master/maths/polynomial_evaluation.py)
* [Power Using Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/power_using_recursion.py)
* [Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py)
* [Prime Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py)
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_sieve_eratosthenes.py)
* [Primelib](https://github.com/TheAlgorithms/Python/blob/master/maths/primelib.py)
* [Proth Number](https://github.com/TheAlgorithms/Python/blob/master/maths/proth_number.py)
* [Pythagoras](https://github.com/TheAlgorithms/Python/blob/master/maths/pythagoras.py)
* [Qr Decomposition](https://github.com/TheAlgorithms/Python/blob/master/maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/quadratic_equations_complex_numbers.py)
* [Radians](https://github.com/TheAlgorithms/Python/blob/master/maths/radians.py)
* [Radix2 Fft](https://github.com/TheAlgorithms/Python/blob/master/maths/radix2_fft.py)
* [Relu](https://github.com/TheAlgorithms/Python/blob/master/maths/relu.py)
* [Runge Kutta](https://github.com/TheAlgorithms/Python/blob/master/maths/runge_kutta.py)
* [Segmented Sieve](https://github.com/TheAlgorithms/Python/blob/master/maths/segmented_sieve.py)
* Series
* [Arithmetic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic.py)
* [Geometric](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric.py)
* [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.py)
* [Harmonic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic.py)
* [Harmonic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic_series.py)
* [P Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/p_series.py)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/sieve_of_eratosthenes.py)
* [Sigmoid](https://github.com/TheAlgorithms/Python/blob/master/maths/sigmoid.py)
* [Simpson Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/simpson_rule.py)
* [Softmax](https://github.com/TheAlgorithms/Python/blob/master/maths/softmax.py)
* [Square Root](https://github.com/TheAlgorithms/Python/blob/master/maths/square_root.py)
* [Sum Of Arithmetic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_digits.py)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/sylvester_sequence.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/maths/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/two_sum.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/inverse_of_matrix.py)
* [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py)
* [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](https://github.com/TheAlgorithms/Python/blob/master/matrix/sherman_morrison.py)
* [Spiral Print](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py)
* [Minimum Cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/convolution_neural_network.py)
* [Perceptron](https://github.com/TheAlgorithms/Python/blob/master/neural_network/perceptron.py)
## Other
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
* [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
* [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
* [Gauss Easter](https://github.com/TheAlgorithms/Python/blob/master/other/gauss_easter.py)
* [Graham Scan](https://github.com/TheAlgorithms/Python/blob/master/other/graham_scan.py)
* [Greedy](https://github.com/TheAlgorithms/Python/blob/master/other/greedy.py)
* [Least Recently Used](https://github.com/TheAlgorithms/Python/blob/master/other/least_recently_used.py)
* [Lfu Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lfu_cache.py)
* [Linear Congruential Generator](https://github.com/TheAlgorithms/Python/blob/master/other/linear_congruential_generator.py)
* [Lru Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lru_cache.py)
* [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py)
* [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py)
* [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py)
* [Scoring Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/scoring_algorithm.py)
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
## Physics
* [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py)
## Project Euler
* Problem 001
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol5.py)
* [Sol6](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol6.py)
* [Sol7](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/sol1.py)
* [Test Poker Hand](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
* Problem 069
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_077/sol1.py)
* Problem 080
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_102/sol1.py)
* Problem 107
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_107/sol1.py)
* Problem 109
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_109/sol1.py)
* Problem 112
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_112/sol1.py)
* Problem 113
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_113/sol1.py)
* Problem 119
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_203/sol1.py)
* Problem 206
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_301/sol1.py)
* Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
## Quantum
* [Deutsch Jozsa](https://github.com/TheAlgorithms/Python/blob/master/quantum/deutsch_jozsa.py)
* [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
* [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
* [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
* [Ripple Adder Classic](https://github.com/TheAlgorithms/Python/blob/master/quantum/ripple_adder_classic.py)
* [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](https://github.com/TheAlgorithms/Python/blob/master/scheduling/first_come_first_served.py)
* [Round Robin](https://github.com/TheAlgorithms/Python/blob/master/scheduling/round_robin.py)
* [Shortest Job First](https://github.com/TheAlgorithms/Python/blob/master/scheduling/shortest_job_first.py)
## Searches
* [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py)
* [Binary Tree Traversal](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_tree_traversal.py)
* [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py)
* [Double Linear Search Recursion](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search_recursion.py)
* [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py)
* [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py)
* [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py)
* [Jump Search](https://github.com/TheAlgorithms/Python/blob/master/searches/jump_search.py)
* [Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/linear_search.py)
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
* [Simple Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple_binary_search.py)
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
## Sorts
* [Bead Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bead_sort.py)
* [Bitonic Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bitonic_sort.py)
* [Bogo Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bogo_sort.py)
* [Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py)
* [Bucket Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bucket_sort.py)
* [Cocktail Shaker Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py)
* [Comb Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/comb_sort.py)
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
* [Heap Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/heap_sort.py)
* [Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/insertion_sort.py)
* [Intro Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/intro_sort.py)
* [Iterative Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/iterative_merge_sort.py)
* [Merge Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_insertion_sort.py)
* [Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_sort.py)
* [Msd Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/msd_radix_sort.py)
* [Natural Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/natural_sort.py)
* [Odd Even Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_sort.py)
* [Odd Even Transposition Parallel](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_parallel.py)
* [Odd Even Transposition Single Threaded](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_single_threaded.py)
* [Pancake Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pancake_sort.py)
* [Patience Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/patience_sort.py)
* [Pigeon Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeon_sort.py)
* [Pigeonhole Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeonhole_sort.py)
* [Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py)
* [Quick Sort 3 Partition](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort_3_partition.py)
* [Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/radix_sort.py)
* [Random Normal Distribution Quicksort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_normal_distribution_quicksort.py)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_pivot_quick_sort.py)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_bubble_sort.py)
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Recursive Mergesort Array](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_mergesort_array.py)
* [Recursive Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_quick_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Slowsort](https://github.com/TheAlgorithms/Python/blob/master/sorts/slowsort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
* [Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/topological_sort.py)
* [Tree Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tree_sort.py)
* [Unknown Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/unknown_sort.py)
* [Wiggle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/wiggle_sort.py)
## Strings
* [Aho Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho_corasick.py)
* [Alternative String Arrange](https://github.com/TheAlgorithms/Python/blob/master/strings/alternative_string_arrange.py)
* [Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/anagrams.py)
* [Autocomplete Using Trie](https://github.com/TheAlgorithms/Python/blob/master/strings/autocomplete_using_trie.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Can String Be Rearranged As Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Detecting English Programmatically](https://github.com/TheAlgorithms/Python/blob/master/strings/detecting_english_programmatically.py)
* [Frequency Finder](https://github.com/TheAlgorithms/Python/blob/master/strings/frequency_finder.py)
* [Indian Phone Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/indian_phone_validator.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
* [Jaro Winkler](https://github.com/TheAlgorithms/Python/blob/master/strings/jaro_winkler.py)
* [Join](https://github.com/TheAlgorithms/Python/blob/master/strings/join.py)
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/Python/blob/master/strings/knuth_morris_pratt.py)
* [Levenshtein Distance](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py)
* [Lower](https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py)
* [Manacher](https://github.com/TheAlgorithms/Python/blob/master/strings/manacher.py)
* [Min Cost String Conversion](https://github.com/TheAlgorithms/Python/blob/master/strings/min_cost_string_conversion.py)
* [Naive String Search](https://github.com/TheAlgorithms/Python/blob/master/strings/naive_string_search.py)
* [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/palindrome.py)
* [Prefix Function](https://github.com/TheAlgorithms/Python/blob/master/strings/prefix_function.py)
* [Rabin Karp](https://github.com/TheAlgorithms/Python/blob/master/strings/rabin_karp.py)
* [Remove Duplicate](https://github.com/TheAlgorithms/Python/blob/master/strings/remove_duplicate.py)
* [Reverse Letters](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_letters.py)
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
* [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
* [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
## Web Programming
* [Co2 Emission](https://github.com/TheAlgorithms/Python/blob/master/web_programming/co2_emission.py)
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
* [Download Images From Google Query](https://github.com/TheAlgorithms/Python/blob/master/web_programming/download_images_from_google_query.py)
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Giphy](https://github.com/TheAlgorithms/Python/blob/master/web_programming/giphy.py)
* [Instagram Crawler](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_crawler.py)
* [Instagram Pic](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_pic.py)
* [Instagram Video](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_video.py)
* [Random Anime Character](https://github.com/TheAlgorithms/Python/blob/master/web_programming/random_anime_character.py)
* [Recaptcha Verification](https://github.com/TheAlgorithms/Python/blob/master/web_programming/recaptcha_verification.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)
* [Test Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/test_fetch_github_info.py)
* [World Covid19 Stats](https://github.com/TheAlgorithms/Python/blob/master/web_programming/world_covid19_stats.py)
|
## Arithmetic Analysis
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py)
* [Gaussian Elimination](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py)
* [Lu Decomposition](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_raphson.py)
* [Secant Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/secant_method.py)
## Backtracking
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Hamiltonian Cycle](https://github.com/TheAlgorithms/Python/blob/master/backtracking/hamiltonian_cycle.py)
* [Knight Tour](https://github.com/TheAlgorithms/Python/blob/master/backtracking/knight_tour.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [N Queens Math](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens_math.py)
* [Rat In Maze](https://github.com/TheAlgorithms/Python/blob/master/backtracking/rat_in_maze.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
* [Binary Shifts](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_number_of_one_bits.py)
* [Reverse Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/reverse_bits.py)
* [Single Bit Manipulation Operations](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/single_bit_manipulation_operations.py)
## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
* [Modular Division](https://github.com/TheAlgorithms/Python/blob/master/blockchain/modular_division.py)
## Boolean Algebra
* [Quine Mc Cluskey](https://github.com/TheAlgorithms/Python/blob/master/boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/conways_game_of_life.py)
* [Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/game_of_life.py)
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Baconian Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/baconian_cipher.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64 Encoding](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64_encoding.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/caesar_cipher.py)
* [Cryptomath Module](https://github.com/TheAlgorithms/Python/blob/master/ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](https://github.com/TheAlgorithms/Python/blob/master/ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Diffie Hellman](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie_hellman.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
* [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
* [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
* [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
* [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
* [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
* [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
* [Rot13](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rot13.py)
* [Rsa Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_cipher.py)
* [Rsa Factorization](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_factorization.py)
* [Rsa Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/trafid_cipher.py)
* [Transposition Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/vigenere_cipher.py)
* [Xor Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](https://github.com/TheAlgorithms/Python/blob/master/compression/burrows_wheeler.py)
* [Huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py)
* [Lempel Ziv](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv.py)
* [Lempel Ziv Decompress](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](https://github.com/TheAlgorithms/Python/blob/master/compression/peak_signal_to_noise_ratio.py)
## Computer Vision
* [Cnn Classification](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/cnn_classification.py)
* [Harris Corner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harris_corner.py)
* [Mean Threshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mean_threshold.py)
## Conversions
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)
* [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_hexadecimal.py)
* [Decimal To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_octal.py)
* [Hex To Bin](https://github.com/TheAlgorithms/Python/blob/master/conversions/hex_to_bin.py)
* [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.py)
* [Length Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/length_conversion.py)
* [Molecular Chemistry](https://github.com/TheAlgorithms/Python/blob/master/conversions/molecular_chemistry.py)
* [Octal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/octal_to_decimal.py)
* [Prefix Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/prefix_conversions.py)
* [Rgb Hsv Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/rgb_hsv_conversion.py)
* [Roman Numerals](https://github.com/TheAlgorithms/Python/blob/master/conversions/roman_numerals.py)
* [Temperature Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/temperature_conversions.py)
* [Weight Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* [Wavelet Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
* [Hash Table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/binomial_heap.py)
* [Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap.py)
* [Heap Generic](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap_generic.py)
* [Max Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/max_heap.py)
* [Min Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/min_heap.py)
* [Randomized Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/randomized_heap.py)
* [Skew Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
* [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/print_reverse.py)
* [Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/singly_linked_list.py)
* [Skip List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/skip_list.py)
* [Swap Nodes](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue.py)
* [Double Ended Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/double_ended_queue.py)
* [Linked Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/linked_queue.py)
* [Priority Queue Using List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/priority_queue_using_list.py)
* [Queue On List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
* [Linked Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/linked_stack.py)
* [Next Greater Element](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/prefix_evaluation.py)
* [Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack.py)
* [Stack Using Dll](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_using_dll.py)
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_brightness.py)
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py)
* [Convolve](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/convolve.py)
* [Gaussian Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/median_filter.py)
* [Sobel Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/rotation/rotation.py)
* [Sepia](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/sepia.py)
* [Test Digital Image Processing](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/inversions.py)
* [Kth Order Statistic](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_subarray_sum.py)
* [Mergesort](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/mergesort.py)
* [Peak](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/peak.py)
* [Power](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/abbreviation.py)
* [Bitmask](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/bitmask.py)
* [Catalan Numbers](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/climbing_stairs.py)
* [Edit Distance](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py)
* [Factorial](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/factorial.py)
* [Fast Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fast_fibonacci.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fibonacci.py)
* [Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/iterating_through_submasks.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/knapsack.py)
* [Longest Common Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](https://github.com/TheAlgorithms/Python/blob/master/electronics/carrier_concentration.py)
* [Coulombs Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/coulombs_law.py)
* [Electric Power](https://github.com/TheAlgorithms/Python/blob/master/electronics/electric_power.py)
* [Ohms Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/ohms_law.py)
## File Transfer
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
* Tests
* [Test Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/tests/test_send_file.py)
## Fractals
* [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py)
* [Koch Snowflake](https://github.com/TheAlgorithms/Python/blob/master/fractals/koch_snowflake.py)
* [Mandelbrot](https://github.com/TheAlgorithms/Python/blob/master/fractals/mandelbrot.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](https://github.com/TheAlgorithms/Python/blob/master/fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](https://github.com/TheAlgorithms/Python/blob/master/graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](https://github.com/TheAlgorithms/Python/blob/master/graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/a_star.py)
* [Articulation Points](https://github.com/TheAlgorithms/Python/blob/master/graphs/articulation_points.py)
* [Basic Graphs](https://github.com/TheAlgorithms/Python/blob/master/graphs/basic_graphs.py)
* [Bellman Ford](https://github.com/TheAlgorithms/Python/blob/master/graphs/bellman_ford.py)
* [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_breadth_first_search.py)
* [Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/boruvka.py)
* [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
* [Breadth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
* [Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/connected_components.py)
* [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
* [Depth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search_2.py)
* [Dijkstra](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra.py)
* [Dijkstra 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_2.py)
* [Dijkstra Algorithm](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_algorithm.py)
* [Dinic](https://github.com/TheAlgorithms/Python/blob/master/graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](https://github.com/TheAlgorithms/Python/blob/master/graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](https://github.com/TheAlgorithms/Python/blob/master/graphs/even_tree.py)
* [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py)
* [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py)
* [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py)
* [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py)
* [Greedy Best First](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
* [Karger](https://github.com/TheAlgorithms/Python/blob/master/graphs/karger.py)
* [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/graphs/markov_chain.py)
* [Matching Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/matching_min_vertex_cover.py)
* [Minimum Spanning Tree Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
* [Strongly Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/strongly_connected_components.py)
* [Tarjans Scc](https://github.com/TheAlgorithms/Python/blob/master/graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](https://github.com/TheAlgorithms/Python/blob/master/greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](https://github.com/TheAlgorithms/Python/blob/master/hashes/adler32.py)
* [Chaos Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/chaos_machine.py)
* [Djb2](https://github.com/TheAlgorithms/Python/blob/master/hashes/djb2.py)
* [Enigma Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/enigma_machine.py)
* [Hamming Code](https://github.com/TheAlgorithms/Python/blob/master/hashes/hamming_code.py)
* [Luhn](https://github.com/TheAlgorithms/Python/blob/master/hashes/luhn.py)
* [Md5](https://github.com/TheAlgorithms/Python/blob/master/hashes/md5.py)
* [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py)
* [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py)
## Knapsack
* [Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/greedy_knapsack.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/conjugate_gradient.py)
* [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py)
* [Polynom For Points](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/polynom_for_points.py)
* [Power Iteration](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/astar.py)
* [Data Transformations](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/data_transformations.py)
* [Decision Tree](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/decision_tree.py)
* Forecasting
* [Run](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_descent.py)
* [K Means Clust](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_means_clust.py)
* [K Nearest Neighbours](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_regression.py)
* [Logistic Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/polymonial_regression.py)
* [Random Forest Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_regressor.py)
* [Scoring Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/similarity_search.py)
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
* [Word Frequency Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)
* [Add](https://github.com/TheAlgorithms/Python/blob/master/maths/add.py)
* [Aliquot Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/aliquot_sum.py)
* [Allocation Number](https://github.com/TheAlgorithms/Python/blob/master/maths/allocation_number.py)
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)
* [Bailey Borwein Plouffe](https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py)
* [Basic Maths](https://github.com/TheAlgorithms/Python/blob/master/maths/basic_maths.py)
* [Binary Exp Mod](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py)
* [Binary Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py)
* [Binary Exponentiation 2](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_3.py)
* [Binomial Coefficient](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_coefficient.py)
* [Binomial Distribution](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_distribution.py)
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/maths/bisection.py)
* [Ceil](https://github.com/TheAlgorithms/Python/blob/master/maths/ceil.py)
* [Check Polygon](https://github.com/TheAlgorithms/Python/blob/master/maths/check_polygon.py)
* [Chudnovsky Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/chudnovsky_algorithm.py)
* [Collatz Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/collatz_sequence.py)
* [Combinations](https://github.com/TheAlgorithms/Python/blob/master/maths/combinations.py)
* [Decimal Isolate](https://github.com/TheAlgorithms/Python/blob/master/maths/decimal_isolate.py)
* [Double Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_iterative.py)
* [Double Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_recursive.py)
* [Entropy](https://github.com/TheAlgorithms/Python/blob/master/maths/entropy.py)
* [Euclidean Distance](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_distance.py)
* [Euclidean Gcd](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_gcd.py)
* [Euler Method](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_method.py)
* [Euler Modified](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_modified.py)
* [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
* [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
* [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
* [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
* [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci.py)
* [Fibonacci Sequence Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci_sequence_recursion.py)
* [Find Max](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max.py)
* [Find Max Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max_recursion.py)
* [Find Min](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min.py)
* [Find Min Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min_recursion.py)
* [Floor](https://github.com/TheAlgorithms/Python/blob/master/maths/floor.py)
* [Gamma](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma.py)
* [Gamma Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma_recursive.py)
* [Gaussian](https://github.com/TheAlgorithms/Python/blob/master/maths/gaussian.py)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/Python/blob/master/maths/greatest_common_divisor.py)
* [Greedy Coin Change](https://github.com/TheAlgorithms/Python/blob/master/maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](https://github.com/TheAlgorithms/Python/blob/master/maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](https://github.com/TheAlgorithms/Python/blob/master/maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](https://github.com/TheAlgorithms/Python/blob/master/maths/is_ip_v4_address_valid.py)
* [Is Square Free](https://github.com/TheAlgorithms/Python/blob/master/maths/is_square_free.py)
* [Jaccard Similarity](https://github.com/TheAlgorithms/Python/blob/master/maths/jaccard_similarity.py)
* [Kadanes](https://github.com/TheAlgorithms/Python/blob/master/maths/kadanes.py)
* [Karatsuba](https://github.com/TheAlgorithms/Python/blob/master/maths/karatsuba.py)
* [Krishnamurthy Number](https://github.com/TheAlgorithms/Python/blob/master/maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](https://github.com/TheAlgorithms/Python/blob/master/maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_subarray_sum.py)
* [Least Common Multiple](https://github.com/TheAlgorithms/Python/blob/master/maths/least_common_multiple.py)
* [Line Length](https://github.com/TheAlgorithms/Python/blob/master/maths/line_length.py)
* [Lucas Lehmer Primality Test](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py)
* [Lucas Series](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_series.py)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/maths/median_of_two_arrays.py)
* [Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py)
* [Mobius Function](https://github.com/TheAlgorithms/Python/blob/master/maths/mobius_function.py)
* [Modular Exponential](https://github.com/TheAlgorithms/Python/blob/master/maths/modular_exponential.py)
* [Monte Carlo](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo.py)
* [Monte Carlo Dice](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo_dice.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/maths/newton_raphson.py)
* [Number Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/number_of_digits.py)
* [Numerical Integration](https://github.com/TheAlgorithms/Python/blob/master/maths/numerical_integration.py)
* [Perfect Cube](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_cube.py)
* [Perfect Number](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_number.py)
* [Perfect Square](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_square.py)
* [Pi Monte Carlo Estimation](https://github.com/TheAlgorithms/Python/blob/master/maths/pi_monte_carlo_estimation.py)
* [Polynomial Evaluation](https://github.com/TheAlgorithms/Python/blob/master/maths/polynomial_evaluation.py)
* [Power Using Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/power_using_recursion.py)
* [Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py)
* [Prime Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py)
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_sieve_eratosthenes.py)
* [Primelib](https://github.com/TheAlgorithms/Python/blob/master/maths/primelib.py)
* [Proth Number](https://github.com/TheAlgorithms/Python/blob/master/maths/proth_number.py)
* [Pythagoras](https://github.com/TheAlgorithms/Python/blob/master/maths/pythagoras.py)
* [Qr Decomposition](https://github.com/TheAlgorithms/Python/blob/master/maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/quadratic_equations_complex_numbers.py)
* [Radians](https://github.com/TheAlgorithms/Python/blob/master/maths/radians.py)
* [Radix2 Fft](https://github.com/TheAlgorithms/Python/blob/master/maths/radix2_fft.py)
* [Relu](https://github.com/TheAlgorithms/Python/blob/master/maths/relu.py)
* [Runge Kutta](https://github.com/TheAlgorithms/Python/blob/master/maths/runge_kutta.py)
* [Segmented Sieve](https://github.com/TheAlgorithms/Python/blob/master/maths/segmented_sieve.py)
* Series
* [Arithmetic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic.py)
* [Geometric](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric.py)
* [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.py)
* [Harmonic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic.py)
* [Harmonic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic_series.py)
* [P Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/p_series.py)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/sieve_of_eratosthenes.py)
* [Sigmoid](https://github.com/TheAlgorithms/Python/blob/master/maths/sigmoid.py)
* [Simpson Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/simpson_rule.py)
* [Softmax](https://github.com/TheAlgorithms/Python/blob/master/maths/softmax.py)
* [Square Root](https://github.com/TheAlgorithms/Python/blob/master/maths/square_root.py)
* [Sum Of Arithmetic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_digits.py)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/sylvester_sequence.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/maths/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/two_sum.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/inverse_of_matrix.py)
* [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py)
* [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](https://github.com/TheAlgorithms/Python/blob/master/matrix/sherman_morrison.py)
* [Spiral Print](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py)
* [Minimum Cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/convolution_neural_network.py)
* [Perceptron](https://github.com/TheAlgorithms/Python/blob/master/neural_network/perceptron.py)
## Other
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
* [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
* [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
* [Gauss Easter](https://github.com/TheAlgorithms/Python/blob/master/other/gauss_easter.py)
* [Graham Scan](https://github.com/TheAlgorithms/Python/blob/master/other/graham_scan.py)
* [Greedy](https://github.com/TheAlgorithms/Python/blob/master/other/greedy.py)
* [Least Recently Used](https://github.com/TheAlgorithms/Python/blob/master/other/least_recently_used.py)
* [Lfu Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lfu_cache.py)
* [Linear Congruential Generator](https://github.com/TheAlgorithms/Python/blob/master/other/linear_congruential_generator.py)
* [Lru Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lru_cache.py)
* [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py)
* [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py)
* [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py)
* [Scoring Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/scoring_algorithm.py)
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
## Physics
* [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py)
## Project Euler
* Problem 001
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol5.py)
* [Sol6](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol6.py)
* [Sol7](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/sol1.py)
* [Test Poker Hand](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
* Problem 069
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_077/sol1.py)
* Problem 080
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_102/sol1.py)
* Problem 107
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_107/sol1.py)
* Problem 109
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_109/sol1.py)
* Problem 112
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_112/sol1.py)
* Problem 113
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_113/sol1.py)
* Problem 119
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_203/sol1.py)
* Problem 206
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_301/sol1.py)
* Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
## Quantum
* [Deutsch Jozsa](https://github.com/TheAlgorithms/Python/blob/master/quantum/deutsch_jozsa.py)
* [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
* [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
* [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
* [Ripple Adder Classic](https://github.com/TheAlgorithms/Python/blob/master/quantum/ripple_adder_classic.py)
* [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](https://github.com/TheAlgorithms/Python/blob/master/scheduling/first_come_first_served.py)
* [Round Robin](https://github.com/TheAlgorithms/Python/blob/master/scheduling/round_robin.py)
* [Shortest Job First](https://github.com/TheAlgorithms/Python/blob/master/scheduling/shortest_job_first.py)
## Searches
* [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py)
* [Binary Tree Traversal](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_tree_traversal.py)
* [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py)
* [Double Linear Search Recursion](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search_recursion.py)
* [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py)
* [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py)
* [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py)
* [Jump Search](https://github.com/TheAlgorithms/Python/blob/master/searches/jump_search.py)
* [Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/linear_search.py)
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
* [Simple Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple_binary_search.py)
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
## Sorts
* [Bead Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bead_sort.py)
* [Bitonic Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bitonic_sort.py)
* [Bogo Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bogo_sort.py)
* [Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py)
* [Bucket Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bucket_sort.py)
* [Cocktail Shaker Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py)
* [Comb Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/comb_sort.py)
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
* [Heap Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/heap_sort.py)
* [Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/insertion_sort.py)
* [Intro Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/intro_sort.py)
* [Iterative Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/iterative_merge_sort.py)
* [Merge Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_insertion_sort.py)
* [Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_sort.py)
* [Msd Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/msd_radix_sort.py)
* [Natural Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/natural_sort.py)
* [Odd Even Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_sort.py)
* [Odd Even Transposition Parallel](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_parallel.py)
* [Odd Even Transposition Single Threaded](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_single_threaded.py)
* [Pancake Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pancake_sort.py)
* [Patience Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/patience_sort.py)
* [Pigeon Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeon_sort.py)
* [Pigeonhole Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeonhole_sort.py)
* [Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py)
* [Quick Sort 3 Partition](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort_3_partition.py)
* [Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/radix_sort.py)
* [Random Normal Distribution Quicksort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_normal_distribution_quicksort.py)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_pivot_quick_sort.py)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_bubble_sort.py)
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Recursive Mergesort Array](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_mergesort_array.py)
* [Recursive Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_quick_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Slowsort](https://github.com/TheAlgorithms/Python/blob/master/sorts/slowsort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
* [Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/topological_sort.py)
* [Tree Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tree_sort.py)
* [Unknown Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/unknown_sort.py)
* [Wiggle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/wiggle_sort.py)
## Strings
* [Aho Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho_corasick.py)
* [Alternative String Arrange](https://github.com/TheAlgorithms/Python/blob/master/strings/alternative_string_arrange.py)
* [Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/anagrams.py)
* [Autocomplete Using Trie](https://github.com/TheAlgorithms/Python/blob/master/strings/autocomplete_using_trie.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Can String Be Rearranged As Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Detecting English Programmatically](https://github.com/TheAlgorithms/Python/blob/master/strings/detecting_english_programmatically.py)
* [Frequency Finder](https://github.com/TheAlgorithms/Python/blob/master/strings/frequency_finder.py)
* [Indian Phone Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/indian_phone_validator.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
* [Jaro Winkler](https://github.com/TheAlgorithms/Python/blob/master/strings/jaro_winkler.py)
* [Join](https://github.com/TheAlgorithms/Python/blob/master/strings/join.py)
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/Python/blob/master/strings/knuth_morris_pratt.py)
* [Levenshtein Distance](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py)
* [Lower](https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py)
* [Manacher](https://github.com/TheAlgorithms/Python/blob/master/strings/manacher.py)
* [Min Cost String Conversion](https://github.com/TheAlgorithms/Python/blob/master/strings/min_cost_string_conversion.py)
* [Naive String Search](https://github.com/TheAlgorithms/Python/blob/master/strings/naive_string_search.py)
* [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/palindrome.py)
* [Prefix Function](https://github.com/TheAlgorithms/Python/blob/master/strings/prefix_function.py)
* [Rabin Karp](https://github.com/TheAlgorithms/Python/blob/master/strings/rabin_karp.py)
* [Remove Duplicate](https://github.com/TheAlgorithms/Python/blob/master/strings/remove_duplicate.py)
* [Reverse Letters](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_letters.py)
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
* [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
* [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
## Web Programming
* [Co2 Emission](https://github.com/TheAlgorithms/Python/blob/master/web_programming/co2_emission.py)
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
* [Download Images From Google Query](https://github.com/TheAlgorithms/Python/blob/master/web_programming/download_images_from_google_query.py)
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Giphy](https://github.com/TheAlgorithms/Python/blob/master/web_programming/giphy.py)
* [Instagram Crawler](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_crawler.py)
* [Instagram Pic](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_pic.py)
* [Instagram Video](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_video.py)
* [Random Anime Character](https://github.com/TheAlgorithms/Python/blob/master/web_programming/random_anime_character.py)
* [Recaptcha Verification](https://github.com/TheAlgorithms/Python/blob/master/web_programming/recaptcha_verification.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)
* [Test Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/test_fetch_github_info.py)
* [World Covid19 Stats](https://github.com/TheAlgorithms/Python/blob/master/web_programming/world_covid19_stats.py)
| 1 |
TheAlgorithms/Python | 5,518 | [mypy] Fix type annotations in `data_structures/binary_tree` | ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| shermanhui | "2021-10-22T04:43:40Z" | "2021-10-22T14:07:05Z" | d82cf5292fbd0ffe1764a1da5c96a39b244618eb | 629848e3721d9354d25fad6cb4729e6afdbbf799 | [mypy] Fix type annotations in `data_structures/binary_tree`. ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A binary search Tree
"""
class Node:
def __init__(self, value, parent):
self.value = value
self.parent = parent # Added in order to delete a node easier
self.left = None
self.right = None
def __repr__(self):
from pprint import pformat
if self.left is None and self.right is None:
return str(self.value)
return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1)
class BinarySearchTree:
def __init__(self, root=None):
self.root = root
def __str__(self):
"""
Return a string of all the Nodes using in order traversal
"""
return str(self.root)
def __reassign_nodes(self, node, new_children):
if new_children is not None: # reset its kids
new_children.parent = node.parent
if node.parent is not None: # reset its parent
if self.is_right(node): # If it is the right children
node.parent.right = new_children
else:
node.parent.left = new_children
else:
self.root = new_children
def is_right(self, node):
return node == node.parent.right
def empty(self):
return self.root is None
def __insert(self, value):
"""
Insert a new node in Binary Search Tree with value label
"""
new_node = Node(value, None) # create a new Node
if self.empty(): # if Tree is empty
self.root = new_node # set its root
else: # Tree is not empty
parent_node = self.root # from root
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
parent_node.left = new_node # We insert the new node in a leaf
break
else:
parent_node = parent_node.left
else:
if parent_node.right is None:
parent_node.right = new_node
break
else:
parent_node = parent_node.right
new_node.parent = parent_node
def insert(self, *values):
for value in values:
self.__insert(value)
return self
def search(self, value):
if self.empty():
raise IndexError("Warning: Tree is empty! please use another.")
else:
node = self.root
# use lazy evaluation here to avoid NoneType Attribute error
while node is not None and node.value is not value:
node = node.left if value < node.value else node.right
return node
def get_max(self, node=None):
"""
We go deep on the right branch
"""
if node is None:
node = self.root
if not self.empty():
while node.right is not None:
node = node.right
return node
def get_min(self, node=None):
"""
We go deep on the left branch
"""
if node is None:
node = self.root
if not self.empty():
node = self.root
while node.left is not None:
node = node.left
return node
def remove(self, value):
node = self.search(value) # Look for the node with that label
if node is not None:
if node.left is None and node.right is None: # If it has no children
self.__reassign_nodes(node, None)
elif node.left is None: # Has only right children
self.__reassign_nodes(node, node.right)
elif node.right is None: # Has only left children
self.__reassign_nodes(node, node.left)
else:
tmp_node = self.get_max(
node.left
) # Gets the max value of the left branch
self.remove(tmp_node.value)
node.value = (
tmp_node.value
) # Assigns the value to the node to delete and keep tree structure
def preorder_traverse(self, node):
if node is not None:
yield node # Preorder Traversal
yield from self.preorder_traverse(node.left)
yield from self.preorder_traverse(node.right)
def traversal_tree(self, traversal_function=None):
"""
This function traversal the tree.
You can pass a function to traversal the tree as needed by client code
"""
if traversal_function is None:
return self.preorder_traverse(self.root)
else:
return traversal_function(self.root)
def inorder(self, arr: list, node: Node):
"""Perform an inorder traversal and append values of the nodes to
a list named arr"""
if node:
self.inorder(arr, node.left)
arr.append(node.value)
self.inorder(arr, node.right)
def find_kth_smallest(self, k: int, node: Node) -> int:
"""Return the kth smallest element in a binary search tree"""
arr = []
self.inorder(arr, node) # append all values to list using inorder traversal
return arr[k - 1]
def postorder(curr_node):
"""
postOrder (left, right, self)
"""
node_list = list()
if curr_node is not None:
node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node]
return node_list
def binary_search_tree():
r"""
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
>>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7)
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
8 3 1 6 4 7 10 14 13
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
1 4 7 6 3 13 14 10 8
>>> BinarySearchTree().search(6)
Traceback (most recent call last):
...
IndexError: Warning: Tree is empty! please use another.
"""
testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7)
t = BinarySearchTree()
for i in testlist:
t.insert(i)
# Prints all the elements of the list in order traversal
print(t)
if t.search(6) is not None:
print("The value 6 exists")
else:
print("The value 6 doesn't exist")
if t.search(-1) is not None:
print("The value -1 exists")
else:
print("The value -1 doesn't exist")
if not t.empty():
print("Max Value: ", t.get_max().value)
print("Min Value: ", t.get_min().value)
for i in testlist:
t.remove(i)
print(t)
if __name__ == "__main__":
import doctest
doctest.testmod()
# binary_search_tree()
| """
A binary search Tree
"""
class Node:
def __init__(self, value, parent):
self.value = value
self.parent = parent # Added in order to delete a node easier
self.left = None
self.right = None
def __repr__(self):
from pprint import pformat
if self.left is None and self.right is None:
return str(self.value)
return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1)
class BinarySearchTree:
def __init__(self, root=None):
self.root = root
def __str__(self):
"""
Return a string of all the Nodes using in order traversal
"""
return str(self.root)
def __reassign_nodes(self, node, new_children):
if new_children is not None: # reset its kids
new_children.parent = node.parent
if node.parent is not None: # reset its parent
if self.is_right(node): # If it is the right children
node.parent.right = new_children
else:
node.parent.left = new_children
else:
self.root = new_children
def is_right(self, node):
return node == node.parent.right
def empty(self):
return self.root is None
def __insert(self, value):
"""
Insert a new node in Binary Search Tree with value label
"""
new_node = Node(value, None) # create a new Node
if self.empty(): # if Tree is empty
self.root = new_node # set its root
else: # Tree is not empty
parent_node = self.root # from root
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
parent_node.left = new_node # We insert the new node in a leaf
break
else:
parent_node = parent_node.left
else:
if parent_node.right is None:
parent_node.right = new_node
break
else:
parent_node = parent_node.right
new_node.parent = parent_node
def insert(self, *values):
for value in values:
self.__insert(value)
return self
def search(self, value):
if self.empty():
raise IndexError("Warning: Tree is empty! please use another.")
else:
node = self.root
# use lazy evaluation here to avoid NoneType Attribute error
while node is not None and node.value is not value:
node = node.left if value < node.value else node.right
return node
def get_max(self, node=None):
"""
We go deep on the right branch
"""
if node is None:
node = self.root
if not self.empty():
while node.right is not None:
node = node.right
return node
def get_min(self, node=None):
"""
We go deep on the left branch
"""
if node is None:
node = self.root
if not self.empty():
node = self.root
while node.left is not None:
node = node.left
return node
def remove(self, value):
node = self.search(value) # Look for the node with that label
if node is not None:
if node.left is None and node.right is None: # If it has no children
self.__reassign_nodes(node, None)
elif node.left is None: # Has only right children
self.__reassign_nodes(node, node.right)
elif node.right is None: # Has only left children
self.__reassign_nodes(node, node.left)
else:
tmp_node = self.get_max(
node.left
) # Gets the max value of the left branch
self.remove(tmp_node.value)
node.value = (
tmp_node.value
) # Assigns the value to the node to delete and keep tree structure
def preorder_traverse(self, node):
if node is not None:
yield node # Preorder Traversal
yield from self.preorder_traverse(node.left)
yield from self.preorder_traverse(node.right)
def traversal_tree(self, traversal_function=None):
"""
This function traversal the tree.
You can pass a function to traversal the tree as needed by client code
"""
if traversal_function is None:
return self.preorder_traverse(self.root)
else:
return traversal_function(self.root)
def inorder(self, arr: list, node: Node):
"""Perform an inorder traversal and append values of the nodes to
a list named arr"""
if node:
self.inorder(arr, node.left)
arr.append(node.value)
self.inorder(arr, node.right)
def find_kth_smallest(self, k: int, node: Node) -> int:
"""Return the kth smallest element in a binary search tree"""
arr: list = []
self.inorder(arr, node) # append all values to list using inorder traversal
return arr[k - 1]
def postorder(curr_node):
"""
postOrder (left, right, self)
"""
node_list = list()
if curr_node is not None:
node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node]
return node_list
def binary_search_tree():
r"""
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
>>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7)
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
8 3 1 6 4 7 10 14 13
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
1 4 7 6 3 13 14 10 8
>>> BinarySearchTree().search(6)
Traceback (most recent call last):
...
IndexError: Warning: Tree is empty! please use another.
"""
testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7)
t = BinarySearchTree()
for i in testlist:
t.insert(i)
# Prints all the elements of the list in order traversal
print(t)
if t.search(6) is not None:
print("The value 6 exists")
else:
print("The value 6 doesn't exist")
if t.search(-1) is not None:
print("The value -1 exists")
else:
print("The value -1 doesn't exist")
if not t.empty():
print("Max Value: ", t.get_max().value)
print("Min Value: ", t.get_min().value)
for i in testlist:
t.remove(i)
print(t)
if __name__ == "__main__":
import doctest
doctest.testmod()
# binary_search_tree()
| 1 |
TheAlgorithms/Python | 5,518 | [mypy] Fix type annotations in `data_structures/binary_tree` | ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| shermanhui | "2021-10-22T04:43:40Z" | "2021-10-22T14:07:05Z" | d82cf5292fbd0ffe1764a1da5c96a39b244618eb | 629848e3721d9354d25fad6cb4729e6afdbbf799 | [mypy] Fix type annotations in `data_structures/binary_tree`. ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/local/bin/python3
"""
Problem Description: Given two binary tree, return the merged tree.
The rule for merging is that if two nodes overlap, then put the value sum of
both nodes to the new value of the merged node. Otherwise, the NOT null node
will be used as the node of new tree.
"""
from __future__ import annotations
class Node:
"""
A binary node has value variable and pointers to its left and right node.
"""
def __init__(self, value: int = 0) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node:
"""
Returns root node of the merged tree.
>>> tree1 = Node(5)
>>> tree1.left = Node(6)
>>> tree1.right = Node(7)
>>> tree1.left.left = Node(2)
>>> tree2 = Node(4)
>>> tree2.left = Node(5)
>>> tree2.right = Node(8)
>>> tree2.left.right = Node(1)
>>> tree2.right.right = Node(4)
>>> merged_tree = merge_two_binary_trees(tree1, tree2)
>>> print_preorder(merged_tree)
9
11
2
1
15
4
"""
if tree1 is None:
return tree2
if tree2 is None:
return tree1
tree1.value = tree1.value + tree2.value
tree1.left = merge_two_binary_trees(tree1.left, tree2.left)
tree1.right = merge_two_binary_trees(tree1.right, tree2.right)
return tree1
def print_preorder(root: Node | None) -> None:
"""
Print pre-order traversal of the tree.
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> print_preorder(root)
1
2
3
>>> print_preorder(root.right)
3
"""
if root:
print(root.value)
print_preorder(root.left)
print_preorder(root.right)
if __name__ == "__main__":
tree1 = Node(1)
tree1.left = Node(2)
tree1.right = Node(3)
tree1.left.left = Node(4)
tree2 = Node(2)
tree2.left = Node(4)
tree2.right = Node(6)
tree2.left.right = Node(9)
tree2.right.right = Node(5)
print("Tree1 is: ")
print_preorder(tree1)
print("Tree2 is: ")
print_preorder(tree2)
merged_tree = merge_two_binary_trees(tree1, tree2)
print("Merged Tree is: ")
print_preorder(merged_tree)
| #!/usr/local/bin/python3
"""
Problem Description: Given two binary tree, return the merged tree.
The rule for merging is that if two nodes overlap, then put the value sum of
both nodes to the new value of the merged node. Otherwise, the NOT null node
will be used as the node of new tree.
"""
from __future__ import annotations
from typing import Optional
class Node:
"""
A binary node has value variable and pointers to its left and right node.
"""
def __init__(self, value: int = 0) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Optional[Node]:
"""
Returns root node of the merged tree.
>>> tree1 = Node(5)
>>> tree1.left = Node(6)
>>> tree1.right = Node(7)
>>> tree1.left.left = Node(2)
>>> tree2 = Node(4)
>>> tree2.left = Node(5)
>>> tree2.right = Node(8)
>>> tree2.left.right = Node(1)
>>> tree2.right.right = Node(4)
>>> merged_tree = merge_two_binary_trees(tree1, tree2)
>>> print_preorder(merged_tree)
9
11
2
1
15
4
"""
if tree1 is None:
return tree2
if tree2 is None:
return tree1
tree1.value = tree1.value + tree2.value
tree1.left = merge_two_binary_trees(tree1.left, tree2.left)
tree1.right = merge_two_binary_trees(tree1.right, tree2.right)
return tree1
def print_preorder(root: Node | None) -> None:
"""
Print pre-order traversal of the tree.
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> print_preorder(root)
1
2
3
>>> print_preorder(root.right)
3
"""
if root:
print(root.value)
print_preorder(root.left)
print_preorder(root.right)
if __name__ == "__main__":
tree1 = Node(1)
tree1.left = Node(2)
tree1.right = Node(3)
tree1.left.left = Node(4)
tree2 = Node(2)
tree2.left = Node(4)
tree2.right = Node(6)
tree2.left.right = Node(9)
tree2.right.right = Node(5)
print("Tree1 is: ")
print_preorder(tree1)
print("Tree2 is: ")
print_preorder(tree2)
merged_tree = merge_two_binary_trees(tree1, tree2)
print("Merged Tree is: ")
print_preorder(merged_tree)
| 1 |
TheAlgorithms/Python | 5,518 | [mypy] Fix type annotations in `data_structures/binary_tree` | ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| shermanhui | "2021-10-22T04:43:40Z" | "2021-10-22T14:07:05Z" | d82cf5292fbd0ffe1764a1da5c96a39b244618eb | 629848e3721d9354d25fad6cb4729e6afdbbf799 | [mypy] Fix type annotations in `data_structures/binary_tree`. ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
from typing import Iterable
class Heap:
"""A Max Heap Implementation
>>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]
>>> h = Heap()
>>> h.build_max_heap(unsorted)
>>> print(h)
[209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]
>>>
>>> h.extract_max()
209
>>> print(h)
[201, 107, 25, 103, 11, 15, 1, 9, 7, 5]
>>>
>>> h.insert(100)
>>> print(h)
[201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11]
>>>
>>> h.heap_sort()
>>> print(h)
[1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201]
"""
def __init__(self) -> None:
self.h: list[float] = []
self.heap_size: int = 0
def __repr__(self) -> str:
return str(self.h)
def parent_index(self, child_idx: int) -> int | None:
"""return the parent index of given child"""
if child_idx > 0:
return (child_idx - 1) // 2
return None
def left_child_idx(self, parent_idx: int) -> int | None:
"""
return the left child index if the left child exists.
if not, return None.
"""
left_child_index = 2 * parent_idx + 1
if left_child_index < self.heap_size:
return left_child_index
return None
def right_child_idx(self, parent_idx: int) -> int | None:
"""
return the right child index if the right child exists.
if not, return None.
"""
right_child_index = 2 * parent_idx + 2
if right_child_index < self.heap_size:
return right_child_index
return None
def max_heapify(self, index: int) -> None:
"""
correct a single violation of the heap property in a subtree's root.
"""
if index < self.heap_size:
violation: int = index
left_child = self.left_child_idx(index)
right_child = self.right_child_idx(index)
# check which child is larger than its parent
if left_child is not None and self.h[left_child] > self.h[violation]:
violation = left_child
if right_child is not None and self.h[right_child] > self.h[violation]:
violation = right_child
# if violation indeed exists
if violation != index:
# swap to fix the violation
self.h[violation], self.h[index] = self.h[index], self.h[violation]
# fix the subsequent violation recursively if any
self.max_heapify(violation)
def build_max_heap(self, collection: Iterable[float]) -> None:
"""build max heap from an unsorted array"""
self.h = list(collection)
self.heap_size = len(self.h)
if self.heap_size > 1:
# max_heapify from right to left but exclude leaves (last level)
for i in range(self.heap_size // 2 - 1, -1, -1):
self.max_heapify(i)
def max(self) -> float:
"""return the max in the heap"""
if self.heap_size >= 1:
return self.h[0]
else:
raise Exception("Empty heap")
def extract_max(self) -> float:
"""get and remove max from heap"""
if self.heap_size >= 2:
me = self.h[0]
self.h[0] = self.h.pop(-1)
self.heap_size -= 1
self.max_heapify(0)
return me
elif self.heap_size == 1:
self.heap_size -= 1
return self.h.pop(-1)
else:
raise Exception("Empty heap")
def insert(self, value: float) -> None:
"""insert a new value into the max heap"""
self.h.append(value)
idx = (self.heap_size - 1) // 2
self.heap_size += 1
while idx >= 0:
self.max_heapify(idx)
idx = (idx - 1) // 2
def heap_sort(self) -> None:
size = self.heap_size
for j in range(size - 1, 0, -1):
self.h[0], self.h[j] = self.h[j], self.h[0]
self.heap_size -= 1
self.max_heapify(0)
self.heap_size = size
if __name__ == "__main__":
import doctest
# run doc test
doctest.testmod()
# demo
for unsorted in [
[0],
[2],
[3, 5],
[5, 3],
[5, 5],
[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 3, 5],
[0, 2, 2, 3, 5],
[2, 5, 3, 0, 2, 3, 0, 3],
[6, 1, 2, 7, 9, 3, 4, 5, 10, 8],
[103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5],
[-45, -2, -5],
]:
print(f"unsorted array: {unsorted}")
heap = Heap()
heap.build_max_heap(unsorted)
print(f"after build heap: {heap}")
print(f"max value: {heap.extract_max()}")
print(f"after max value removed: {heap}")
heap.insert(100)
print(f"after new value 100 inserted: {heap}")
heap.heap_sort()
print(f"heap-sorted array: {heap}\n")
| from __future__ import annotations
from typing import Iterable
class Heap:
"""A Max Heap Implementation
>>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]
>>> h = Heap()
>>> h.build_max_heap(unsorted)
>>> print(h)
[209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]
>>>
>>> h.extract_max()
209
>>> print(h)
[201, 107, 25, 103, 11, 15, 1, 9, 7, 5]
>>>
>>> h.insert(100)
>>> print(h)
[201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11]
>>>
>>> h.heap_sort()
>>> print(h)
[1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201]
"""
def __init__(self) -> None:
self.h: list[float] = []
self.heap_size: int = 0
def __repr__(self) -> str:
return str(self.h)
def parent_index(self, child_idx: int) -> int | None:
"""return the parent index of given child"""
if child_idx > 0:
return (child_idx - 1) // 2
return None
def left_child_idx(self, parent_idx: int) -> int | None:
"""
return the left child index if the left child exists.
if not, return None.
"""
left_child_index = 2 * parent_idx + 1
if left_child_index < self.heap_size:
return left_child_index
return None
def right_child_idx(self, parent_idx: int) -> int | None:
"""
return the right child index if the right child exists.
if not, return None.
"""
right_child_index = 2 * parent_idx + 2
if right_child_index < self.heap_size:
return right_child_index
return None
def max_heapify(self, index: int) -> None:
"""
correct a single violation of the heap property in a subtree's root.
"""
if index < self.heap_size:
violation: int = index
left_child = self.left_child_idx(index)
right_child = self.right_child_idx(index)
# check which child is larger than its parent
if left_child is not None and self.h[left_child] > self.h[violation]:
violation = left_child
if right_child is not None and self.h[right_child] > self.h[violation]:
violation = right_child
# if violation indeed exists
if violation != index:
# swap to fix the violation
self.h[violation], self.h[index] = self.h[index], self.h[violation]
# fix the subsequent violation recursively if any
self.max_heapify(violation)
def build_max_heap(self, collection: Iterable[float]) -> None:
"""build max heap from an unsorted array"""
self.h = list(collection)
self.heap_size = len(self.h)
if self.heap_size > 1:
# max_heapify from right to left but exclude leaves (last level)
for i in range(self.heap_size // 2 - 1, -1, -1):
self.max_heapify(i)
def max(self) -> float:
"""return the max in the heap"""
if self.heap_size >= 1:
return self.h[0]
else:
raise Exception("Empty heap")
def extract_max(self) -> float:
"""get and remove max from heap"""
if self.heap_size >= 2:
me = self.h[0]
self.h[0] = self.h.pop(-1)
self.heap_size -= 1
self.max_heapify(0)
return me
elif self.heap_size == 1:
self.heap_size -= 1
return self.h.pop(-1)
else:
raise Exception("Empty heap")
def insert(self, value: float) -> None:
"""insert a new value into the max heap"""
self.h.append(value)
idx = (self.heap_size - 1) // 2
self.heap_size += 1
while idx >= 0:
self.max_heapify(idx)
idx = (idx - 1) // 2
def heap_sort(self) -> None:
size = self.heap_size
for j in range(size - 1, 0, -1):
self.h[0], self.h[j] = self.h[j], self.h[0]
self.heap_size -= 1
self.max_heapify(0)
self.heap_size = size
if __name__ == "__main__":
import doctest
# run doc test
doctest.testmod()
# demo
for unsorted in [
[0],
[2],
[3, 5],
[5, 3],
[5, 5],
[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 3, 5],
[0, 2, 2, 3, 5],
[2, 5, 3, 0, 2, 3, 0, 3],
[6, 1, 2, 7, 9, 3, 4, 5, 10, 8],
[103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5],
[-45, -2, -5],
]:
print(f"unsorted array: {unsorted}")
heap = Heap()
heap.build_max_heap(unsorted)
print(f"after build heap: {heap}")
print(f"max value: {heap.extract_max()}")
print(f"after max value removed: {heap}")
heap.insert(100)
print(f"after new value 100 inserted: {heap}")
heap.heap_sort()
print(f"heap-sorted array: {heap}\n")
| -1 |
TheAlgorithms/Python | 5,518 | [mypy] Fix type annotations in `data_structures/binary_tree` | ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| shermanhui | "2021-10-22T04:43:40Z" | "2021-10-22T14:07:05Z" | d82cf5292fbd0ffe1764a1da5c96a39b244618eb | 629848e3721d9354d25fad6cb4729e6afdbbf799 | [mypy] Fix type annotations in `data_structures/binary_tree`. ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
from .number_theory.prime_numbers import next_prime
class HashTable:
"""
Basic Hash Table example with open addressing and linear probing
"""
def __init__(self, size_table, charge_factor=None, lim_charge=None):
self.size_table = size_table
self.values = [None] * self.size_table
self.lim_charge = 0.75 if lim_charge is None else lim_charge
self.charge_factor = 1 if charge_factor is None else charge_factor
self.__aux_list = []
self._keys = {}
def keys(self):
return self._keys
def balanced_factor(self):
return sum(1 for slot in self.values if slot is not None) / (
self.size_table * self.charge_factor
)
def hash_function(self, key):
return key % self.size_table
def _step_by_step(self, step_ord):
print(f"step {step_ord}")
print([i for i in range(len(self.values))])
print(self.values)
def bulk_insert(self, values):
i = 1
self.__aux_list = values
for value in values:
self.insert_data(value)
self._step_by_step(i)
i += 1
def _set_value(self, key, data):
self.values[key] = data
self._keys[key] = data
def _collision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
else:
new_key = None
break
return new_key
def rehashing(self):
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/
for value in survivor_values:
self.insert_data(value)
def insert_data(self, data):
key = self.hash_function(data)
if self.values[key] is None:
self._set_value(key, data)
elif self.values[key] == data:
pass
else:
collision_resolution = self._collision_resolution(key, data)
if collision_resolution is not None:
self._set_value(collision_resolution, data)
else:
self.rehashing()
self.insert_data(data)
| #!/usr/bin/env python3
from .number_theory.prime_numbers import next_prime
class HashTable:
"""
Basic Hash Table example with open addressing and linear probing
"""
def __init__(self, size_table, charge_factor=None, lim_charge=None):
self.size_table = size_table
self.values = [None] * self.size_table
self.lim_charge = 0.75 if lim_charge is None else lim_charge
self.charge_factor = 1 if charge_factor is None else charge_factor
self.__aux_list = []
self._keys = {}
def keys(self):
return self._keys
def balanced_factor(self):
return sum(1 for slot in self.values if slot is not None) / (
self.size_table * self.charge_factor
)
def hash_function(self, key):
return key % self.size_table
def _step_by_step(self, step_ord):
print(f"step {step_ord}")
print([i for i in range(len(self.values))])
print(self.values)
def bulk_insert(self, values):
i = 1
self.__aux_list = values
for value in values:
self.insert_data(value)
self._step_by_step(i)
i += 1
def _set_value(self, key, data):
self.values[key] = data
self._keys[key] = data
def _collision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
else:
new_key = None
break
return new_key
def rehashing(self):
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/
for value in survivor_values:
self.insert_data(value)
def insert_data(self, data):
key = self.hash_function(data)
if self.values[key] is None:
self._set_value(key, data)
elif self.values[key] == data:
pass
else:
collision_resolution = self._collision_resolution(key, data)
if collision_resolution is not None:
self._set_value(collision_resolution, data)
else:
self.rehashing()
self.insert_data(data)
| -1 |
TheAlgorithms/Python | 5,518 | [mypy] Fix type annotations in `data_structures/binary_tree` | ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| shermanhui | "2021-10-22T04:43:40Z" | "2021-10-22T14:07:05Z" | d82cf5292fbd0ffe1764a1da5c96a39b244618eb | 629848e3721d9354d25fad6cb4729e6afdbbf799 | [mypy] Fix type annotations in `data_structures/binary_tree`. ### fix type annotations in `data_structures/binary_tree/binary_search_tree.py` and `data_structures/binary_tree/merge_two_binary_trees.py`
My contribution to fixing the `mypy` errors identified in #4052
Update binary_search_tree `arr` argument to be typed as a list
within `find_kth_smallest` function
Update return type of `merge_two_binary_trees` as both inputs can
be None which means that a None type value can be returned from
this function

* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Tree_sort algorithm.
Build a BST and in order traverse.
"""
class node:
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self, val):
if self.val:
if val < self.val:
if self.left is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
def inorder(root, res):
# Recursive traversal
if root:
inorder(root.left, res)
res.append(root.val)
inorder(root.right, res)
def tree_sort(arr):
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1, len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root, res)
return res
if __name__ == "__main__":
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
| """
Tree_sort algorithm.
Build a BST and in order traverse.
"""
class node:
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self, val):
if self.val:
if val < self.val:
if self.left is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
def inorder(root, res):
# Recursive traversal
if root:
inorder(root.left, res)
res.append(root.val)
inorder(root.right, res)
def tree_sort(arr):
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1, len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root, res)
return res
if __name__ == "__main__":
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.