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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
""" Conway's Game of Life implemented in Python. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ from __future__ import annotations from typing import List from PIL import Image # Define glider example GLIDER = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def new_generation(cells: List[List[int]]) -> List[List[int]]: """ Generates the next generation for a given state of Conway's Game of Life. >>> new_generation(BLINKER) [[0, 0, 0], [1, 1, 1], [0, 0, 0]] """ next_generation = [] for i in range(len(cells)): next_generation_row = [] for j in range(len(cells[i])): # Get the number of live neighbours neighbour_count = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i]) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i]) - 1: neighbour_count += cells[i][j + 1] if i < len(cells) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(cells) - 1: neighbour_count += cells[i + 1][j] if i < len(cells) - 1 and j < len(cells[i]) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. alive = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1) else: next_generation_row.append(0) next_generation.append(next_generation_row) return next_generation def generate_images(cells: list[list[int]], frames) -> list[Image.Image]: """ Generates a list of images of subsequent Game of Life states. """ images = [] for _ in range(frames): # Create output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Save cells to image for x in range(len(cells)): for y in range(len(cells[0])): colour = 255 - cells[y][x] * 255 pixels[x, y] = (colour, colour, colour) # Save image images.append(img) cells = new_generation(cells) return images if __name__ == "__main__": images = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
""" Conway's Game of Life implemented in Python. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ from __future__ import annotations from typing import List from PIL import Image # Define glider example GLIDER = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def new_generation(cells: List[List[int]]) -> List[List[int]]: """ Generates the next generation for a given state of Conway's Game of Life. >>> new_generation(BLINKER) [[0, 0, 0], [1, 1, 1], [0, 0, 0]] """ next_generation = [] for i in range(len(cells)): next_generation_row = [] for j in range(len(cells[i])): # Get the number of live neighbours neighbour_count = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i]) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i]) - 1: neighbour_count += cells[i][j + 1] if i < len(cells) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(cells) - 1: neighbour_count += cells[i + 1][j] if i < len(cells) - 1 and j < len(cells[i]) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. alive = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1) else: next_generation_row.append(0) next_generation.append(next_generation_row) return next_generation def generate_images(cells: list[list[int]], frames) -> list[Image.Image]: """ Generates a list of images of subsequent Game of Life states. """ images = [] for _ in range(frames): # Create output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Save cells to image for x in range(len(cells)): for y in range(len(cells[0])): colour = 255 - cells[y][x] * 255 pixels[x, y] = (colour, colour, colour) # Save image images.append(img) cells = new_generation(cells) return images if __name__ == "__main__": images = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 """Author Anurag Kumar | [email protected] | git/anuragkumarak95 Simple example of Fractal generation using recursive function. What is Sierpinski Triangle? >>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski. Requirements(pip): - turtle Python: - 2.6 Usage: - $python sierpinski_triangle.py <int:depth_for_fractal> Credits: This code was written by editing the code from http://www.riannetrujillo.com/blog/python-fractal/ """ import sys import turtle PROGNAME = "Sierpinski Triangle" points = [[-175, -125], [0, 175], [175, -125]] # size of triangle def getMid(p1, p2): return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) # find midpoint def triangle(points, depth): myPen.up() myPen.goto(points[0][0], points[0][1]) myPen.down() myPen.goto(points[1][0], points[1][1]) myPen.goto(points[2][0], points[2][1]) myPen.goto(points[0][0], points[0][1]) if depth > 0: triangle( [points[0], getMid(points[0], points[1]), getMid(points[0], points[2])], depth - 1, ) triangle( [points[1], getMid(points[0], points[1]), getMid(points[1], points[2])], depth - 1, ) triangle( [points[2], getMid(points[2], points[1]), getMid(points[0], points[2])], depth - 1, ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "right format for using this script: " "$python fractals.py <int:depth_for_fractal>" ) myPen = turtle.Turtle() myPen.ht() myPen.speed(5) myPen.pencolor("red") triangle(points, int(sys.argv[1]))
#!/usr/bin/python """Author Anurag Kumar | [email protected] | git/anuragkumarak95 Simple example of Fractal generation using recursive function. What is Sierpinski Triangle? >>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski. Requirements(pip): - turtle Python: - 2.6 Usage: - $python sierpinski_triangle.py <int:depth_for_fractal> Credits: This code was written by editing the code from http://www.riannetrujillo.com/blog/python-fractal/ """ import sys import turtle PROGNAME = "Sierpinski Triangle" points = [[-175, -125], [0, 175], [175, -125]] # size of triangle def getMid(p1, p2): return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) # find midpoint def triangle(points, depth): myPen.up() myPen.goto(points[0][0], points[0][1]) myPen.down() myPen.goto(points[1][0], points[1][1]) myPen.goto(points[2][0], points[2][1]) myPen.goto(points[0][0], points[0][1]) if depth > 0: triangle( [points[0], getMid(points[0], points[1]), getMid(points[0], points[2])], depth - 1, ) triangle( [points[1], getMid(points[0], points[1]), getMid(points[1], points[2])], depth - 1, ) triangle( [points[2], getMid(points[2], points[1]), getMid(points[0], points[2])], depth - 1, ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "right format for using this script: " "$python fractals.py <int:depth_for_fractal>" ) myPen = turtle.Turtle() myPen.ht() myPen.speed(5) myPen.pencolor("red") triangle(points, int(sys.argv[1]))
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. :param list_data: mutable ordered sequence of elements :param length: length of list data :return: the same list in ascending order >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] >>> bubble_sort([], 0) [] >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": import doctest doctest.testmod()
def bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. :param list_data: mutable ordered sequence of elements :param length: length of list data :return: the same list in ascending order >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] >>> bubble_sort([], 0) [] >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def MF_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global F # a global dp table for knapsack if F[i][j] < 0: if j < wt[i - 1]: val = MF_knapsack(i - 1, wt, val, j) else: val = max( MF_knapsack(i - 1, wt, val, j), MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) F[i][j] = val return F[i][j] def knapsack(W, wt, val, n): dp = [[0 for i in range(W + 1)] for j in range(n + 1)] for i in range(1, n + 1): for w in range(1, W + 1): if wt[i - 1] <= w: dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]) else: dp[i][w] = dp[i - 1][w] return dp[n][W], dp def knapsack_with_example_solution(W: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): raise ValueError( "The number of weights must be the " "same as the number of values.\nBut " f"got {num_items} weights and {len(val)} values" ) for i in range(num_items): if not isinstance(wt[i], int): raise TypeError( "All weights must be integers but " f"got weight of type {type(wt[i])} at index {i}" ) optimal_val, dp_table = knapsack(W, wt, val, num_items) example_optional_set = set() _construct_solution(dp_table, wt, num_items, W, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(MF_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def MF_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global F # a global dp table for knapsack if F[i][j] < 0: if j < wt[i - 1]: val = MF_knapsack(i - 1, wt, val, j) else: val = max( MF_knapsack(i - 1, wt, val, j), MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) F[i][j] = val return F[i][j] def knapsack(W, wt, val, n): dp = [[0 for i in range(W + 1)] for j in range(n + 1)] for i in range(1, n + 1): for w in range(1, W + 1): if wt[i - 1] <= w: dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]) else: dp[i][w] = dp[i - 1][w] return dp[n][W], dp def knapsack_with_example_solution(W: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): raise ValueError( "The number of weights must be the " "same as the number of values.\nBut " f"got {num_items} weights and {len(val)} values" ) for i in range(num_items): if not isinstance(wt[i], int): raise TypeError( "All weights must be integers but " f"got weight of type {type(wt[i])} at index {i}" ) optimal_val, dp_table = knapsack(W, wt, val, num_items) example_optional_set = set() _construct_solution(dp_table, wt, num_items, W, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(MF_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset dataset = pd.read_csv( "https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/" "position_salaries.csv" ) X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) poly_reg = PolynomialFeatures(degree=4) X_poly = poly_reg.fit_transform(X) pol_reg = LinearRegression() pol_reg.fit(X_poly, y) # Visualizing the Polymonial Regression results def viz_polymonial(): plt.scatter(X, y, color="red") plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color="blue") plt.title("Truth or Bluff (Linear Regression)") plt.xlabel("Position level") plt.ylabel("Salary") plt.show() return if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset dataset = pd.read_csv( "https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/" "position_salaries.csv" ) X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) poly_reg = PolynomialFeatures(degree=4) X_poly = poly_reg.fit_transform(X) pol_reg = LinearRegression() pol_reg.fit(X_poly, y) # Visualizing the Polymonial Regression results def viz_polymonial(): plt.scatter(X, y, color="red") plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color="blue") plt.title("Truth or Bluff (Linear Regression)") plt.xlabel("Position level") plt.ylabel("Salary") plt.show() return if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 28 Url: https://projecteuler.net/problem=28 Statement: Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ from math import ceil def solution(n: int = 1001) -> int: """Returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way. >>> solution(1001) 669171001 >>> solution(500) 82959497 >>> solution(100) 651897 >>> solution(50) 79697 >>> solution(10) 537 """ total = 1 for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd ** 2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
""" Problem 28 Url: https://projecteuler.net/problem=28 Statement: Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ from math import ceil def solution(n: int = 1001) -> int: """Returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way. >>> solution(1001) 669171001 >>> solution(500) 82959497 >>> solution(100) 651897 >>> solution(50) 79697 >>> solution(10) 537 """ total = 1 for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd ** 2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: n needs to be positive integer, your input -7 """ assert ( isinstance(n, int) and n > 0 ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: n needs to be positive integer, your input -7 """ assert ( isinstance(n, int) and n > 0 ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both input must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both input must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both input must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both input must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 base64 def encode_to_b16(inp: str) -> bytes: """ Encodes a given utf-8 string into base-16. >>> encode_to_b16('Hello World!') b'48656C6C6F20576F726C6421' >>> encode_to_b16('HELLO WORLD!') b'48454C4C4F20574F524C4421' >>> encode_to_b16('') b'' """ encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) b16encoded = base64.b16encode(encoded) # b16encoded the encoded string return b16encoded if __name__ == "__main__": import doctest doctest.testmod()
import base64 def encode_to_b16(inp: str) -> bytes: """ Encodes a given utf-8 string into base-16. >>> encode_to_b16('Hello World!') b'48656C6C6F20576F726C6421' >>> encode_to_b16('HELLO WORLD!') b'48454C4C4F20574F524C4421' >>> encode_to_b16('') b'' """ encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) b16encoded = base64.b16encode(encoded) # b16encoded the encoded string return b16encoded if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
""" Author : Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. """ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(",") print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])] * len(self.array) sum_value = [int(self.array[0])] * len(self.array) for i in range(1, len(self.array)): sum_value[i] = max( int(self.array[i]) + sum_value[i - 1], int(self.array[i]) ) rear[i] = max(sum_value[i], rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() print(("the results is:", re))
""" Author : Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. """ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(",") print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])] * len(self.array) sum_value = [int(self.array[0])] * len(self.array) for i in range(1, len(self.array)): sum_value[i] = max( int(self.array[i]) + sum_value[i - 1], int(self.array[i]) ) rear[i] = max(sum_value[i], rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() print(("the results is:", re))
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 """ digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 """ return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 """ return len(str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> num_digits()", "\t\tans =", num_digits(small_num), "\ttime =", timeit("z.num_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(small_num), "\ttime =", timeit("z.num_digits_fast(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(small_num), "\ttime =", timeit("z.num_digits_faster(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> num_digits()", "\t\tans =", num_digits(medium_num), "\ttime =", timeit("z.num_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(medium_num), "\ttime =", timeit("z.num_digits_fast(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(medium_num), "\ttime =", timeit("z.num_digits_faster(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> num_digits()", "\t\tans =", num_digits(large_num), "\ttime =", timeit("z.num_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(large_num), "\ttime =", timeit("z.num_digits_fast(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(large_num), "\ttime =", timeit("z.num_digits_faster(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 """ digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 """ return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 """ return len(str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> num_digits()", "\t\tans =", num_digits(small_num), "\ttime =", timeit("z.num_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(small_num), "\ttime =", timeit("z.num_digits_fast(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(small_num), "\ttime =", timeit("z.num_digits_faster(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> num_digits()", "\t\tans =", num_digits(medium_num), "\ttime =", timeit("z.num_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(medium_num), "\ttime =", timeit("z.num_digits_fast(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(medium_num), "\ttime =", timeit("z.num_digits_faster(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> num_digits()", "\t\tans =", num_digits(large_num), "\ttime =", timeit("z.num_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(large_num), "\ttime =", timeit("z.num_digits_fast(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(large_num), "\ttime =", timeit("z.num_digits_faster(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 207: https://projecteuler.net/problem=207 Problem Statement: For some positive integers k, there exists an integer partition of the form 4**t = 2**t + k, where 4**t, 2**t, and k are all positive integers and t is a real number. The first two such partitions are 4**1 = 2**1 + 2 and 4**1.5849625... = 2**1.5849625... + 6. Partitions where t is also an integer are called perfect. For any m ≥ 1 let P(m) be the proportion of such partitions that are perfect with k ≤ m. Thus P(6) = 1/2. In the following table are listed some values of P(m) P(5) = 1/1 P(10) = 1/2 P(15) = 2/3 P(20) = 1/2 P(25) = 1/2 P(30) = 2/5 ... P(180) = 1/4 P(185) = 3/13 Find the smallest m for which P(m) < 1/12345 Solution: Equation 4**t = 2**t + k solved for t gives: t = log2(sqrt(4*k+1)/2 + 1/2) For t to be real valued, sqrt(4*k+1) must be an integer which is implemented in function check_t_real(k). For a perfect partition t must be an integer. To speed up significantly the search for partitions, instead of incrementing k by one per iteration, the next valid k is found by k = (i**2 - 1) / 4 with an integer i and k has to be a positive integer. If this is the case a partition is found. The partition is perfect if t os an integer. The integer i is increased with increment 1 until the proportion perfect partitions / total partitions drops under the given value. """ import math def check_partition_perfect(positive_integer: int) -> bool: """ Check if t = f(positive_integer) = log2(sqrt(4*positive_integer+1)/2 + 1/2) is a real number. >>> check_partition_perfect(2) True >>> check_partition_perfect(6) False """ exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent) def solution(max_proportion: float = 1 / 12345) -> int: """ Find m for which the proportion of perfect partitions to total partitions is lower than max_proportion >>> solution(1) > 5 True >>> solution(1/2) > 10 True >>> solution(3 / 13) > 185 True """ total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer ** 2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return partition_candidate integer += 1 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 207: https://projecteuler.net/problem=207 Problem Statement: For some positive integers k, there exists an integer partition of the form 4**t = 2**t + k, where 4**t, 2**t, and k are all positive integers and t is a real number. The first two such partitions are 4**1 = 2**1 + 2 and 4**1.5849625... = 2**1.5849625... + 6. Partitions where t is also an integer are called perfect. For any m ≥ 1 let P(m) be the proportion of such partitions that are perfect with k ≤ m. Thus P(6) = 1/2. In the following table are listed some values of P(m) P(5) = 1/1 P(10) = 1/2 P(15) = 2/3 P(20) = 1/2 P(25) = 1/2 P(30) = 2/5 ... P(180) = 1/4 P(185) = 3/13 Find the smallest m for which P(m) < 1/12345 Solution: Equation 4**t = 2**t + k solved for t gives: t = log2(sqrt(4*k+1)/2 + 1/2) For t to be real valued, sqrt(4*k+1) must be an integer which is implemented in function check_t_real(k). For a perfect partition t must be an integer. To speed up significantly the search for partitions, instead of incrementing k by one per iteration, the next valid k is found by k = (i**2 - 1) / 4 with an integer i and k has to be a positive integer. If this is the case a partition is found. The partition is perfect if t os an integer. The integer i is increased with increment 1 until the proportion perfect partitions / total partitions drops under the given value. """ import math def check_partition_perfect(positive_integer: int) -> bool: """ Check if t = f(positive_integer) = log2(sqrt(4*positive_integer+1)/2 + 1/2) is a real number. >>> check_partition_perfect(2) True >>> check_partition_perfect(6) False """ exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent) def solution(max_proportion: float = 1 / 12345) -> int: """ Find m for which the proportion of perfect partitions to total partitions is lower than max_proportion >>> solution(1) > 5 True >>> solution(1/2) > 10 True >>> solution(3 / 13) > 185 True """ total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer ** 2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return partition_candidate integer += 1 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass from typing import Optional test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next: Optional[Node] class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Optional[Node] = None for i in reversed(sorted(ints)): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass from typing import Optional test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next: Optional[Node] class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Optional[Node] = None for i in reversed(sorted(ints)): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 typing import List 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 typing import List 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 math import asin, atan, cos, radians, sin, sqrt, tan def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth's curvature when calculating distance from point A to B. This effect is negligible for small distances but adds up as distance increases. The Haversine method treats the earth as a sphere which allows us to "project" the two points A and B onto the surface of that sphere and approximate the spherical distance between them. Since the Earth is not a perfect sphere, other methods which model the Earth's ellipsoidal nature are more accurate but a quick and modifiable computation like Haversine can be handy for shorter range distances. Args: lat1, lon1: latitude and longitude of coordinate 1 lat2, lon2: latitude and longitude of coordinate 2 Returns: geographical distance between two points in metres >>> from collections import namedtuple >>> point_2d = namedtuple("point_2d", "lat lon") >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227) >>> YOSEMITE = point_2d(37.864742, -119.537521) >>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters" '254,352 meters' """ # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System # Distance in metres(m) AXIS_A = 6378137.0 AXIS_B = 6356752.314245 RADIUS = 6378137 # Equation parameters # Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation flattening = (AXIS_A - AXIS_B) / AXIS_A phi_1 = atan((1 - flattening) * tan(radians(lat1))) phi_2 = atan((1 - flattening) * tan(radians(lat2))) lambda_1 = radians(lon1) lambda_2 = radians(lon2) # Equation sin_sq_phi = sin((phi_2 - phi_1) / 2) sin_sq_lambda = sin((lambda_2 - lambda_1) / 2) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda)) return 2 * RADIUS * asin(h_value) if __name__ == "__main__": import doctest doctest.testmod()
from math import asin, atan, cos, radians, sin, sqrt, tan def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth's curvature when calculating distance from point A to B. This effect is negligible for small distances but adds up as distance increases. The Haversine method treats the earth as a sphere which allows us to "project" the two points A and B onto the surface of that sphere and approximate the spherical distance between them. Since the Earth is not a perfect sphere, other methods which model the Earth's ellipsoidal nature are more accurate but a quick and modifiable computation like Haversine can be handy for shorter range distances. Args: lat1, lon1: latitude and longitude of coordinate 1 lat2, lon2: latitude and longitude of coordinate 2 Returns: geographical distance between two points in metres >>> from collections import namedtuple >>> point_2d = namedtuple("point_2d", "lat lon") >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227) >>> YOSEMITE = point_2d(37.864742, -119.537521) >>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters" '254,352 meters' """ # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System # Distance in metres(m) AXIS_A = 6378137.0 AXIS_B = 6356752.314245 RADIUS = 6378137 # Equation parameters # Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation flattening = (AXIS_A - AXIS_B) / AXIS_A phi_1 = atan((1 - flattening) * tan(radians(lat1))) phi_2 = atan((1 - flattening) * tan(radians(lat2))) lambda_1 = radians(lon1) lambda_2 = radians(lon2) # Equation sin_sq_phi = sin((phi_2 - phi_1) / 2) sin_sq_lambda = sin((lambda_2 - lambda_1) / 2) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda)) return 2 * RADIUS * asin(h_value) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
PNG  IHDR=iCCPICC Profile(UoT?o\?US[IB*unS6mUo xB ISA$=t@hpS]Ƹ9w>5@WI`]5;V! A'@{N\..ƅG_!7suV$BlW=}i; F)A<.&Xax,38S(b׵*%31l #O-zQvaXOP5o6Zz&⻏^wkI/#&\%x/@{7S މjPh͔&mry>k7=ߪB#@fs_{덱п0-LZ~%Gpˈ{YXf^+_s-T>D@קƸ-9!r[2]3BcnCs?>*ԮeD|%4` :X2 pQSLPRaeyqĘ י5Fit )CdL$o$rpӶb>4+̹F_{Яki+x.+B.{L<۩ =UHcnf<>F ^e||pyv%b:iX'%8Iߔ? rw[vITVQN^dpYI"|#\cz[2M^S0[zIJ/HHȟ- Ic<xx-8ZNxA-8mCkKHaYn1Ĝ {qHgu#L hs :6z!y@}zgqٺ/S4~\~Y3M9PyK=. -z$8Y7"tkHևwⳟ\87܅O$~j]n5`ffsKpYqx(@ pHYs B(xdiTXtXML:com.adobe.xmp<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 4.4.0"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"> <xmp:CreatorTool>www.inkscape.org</xmp:CreatorTool> </rdf:Description> </rdf:RDF> </x:xmpmeta> 4 IDATxyeߧ{dL.$$$! "+@EY *̪zn^f\]x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"V-U/^$%}?V)?۟ *cK@'F*cwuQTħ W84xXwr wIk&m|]m#S{n\X/tdcae(e{<C_ zu_4\ kwCε+蹶b4jnS޲mmui)SyR0l΁i.vb<gIDATQ,m7I1Ï5\[m|]Ai 2 u-uze:ptFQ5͍/ mUdx9=`+WApm,g-(]^-UЫ2u3sNCZʨ* AL /8_6ug*eekˎi9tYWˢ@Zo6=*K[FIvYB ruVzUǡl2 _UϮ򧙞[[Zp&{BZMZ<^NㅸOv4 iM]*VUumqĺ]S!=}Keuy|f£ ]̺󙟿8'P]IENDB`
PNG  IHDR=iCCPICC Profile(UoT?o\?US[IB*unS6mUo xB ISA$=t@hpS]Ƹ9w>5@WI`]5;V! A'@{N\..ƅG_!7suV$BlW=}i; F)A<.&Xax,38S(b׵*%31l #O-zQvaXOP5o6Zz&⻏^wkI/#&\%x/@{7S މjPh͔&mry>k7=ߪB#@fs_{덱п0-LZ~%Gpˈ{YXf^+_s-T>D@קƸ-9!r[2]3BcnCs?>*ԮeD|%4` :X2 pQSLPRaeyqĘ י5Fit )CdL$o$rpӶb>4+̹F_{Яki+x.+B.{L<۩ =UHcnf<>F ^e||pyv%b:iX'%8Iߔ? rw[vITVQN^dpYI"|#\cz[2M^S0[zIJ/HHȟ- Ic<xx-8ZNxA-8mCkKHaYn1Ĝ {qHgu#L hs :6z!y@}zgqٺ/S4~\~Y3M9PyK=. -z$8Y7"tkHևwⳟ\87܅O$~j]n5`ffsKpYqx(@ pHYs B(xdiTXtXML:com.adobe.xmp<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 4.4.0"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"> <xmp:CreatorTool>www.inkscape.org</xmp:CreatorTool> </rdf:Description> </rdf:RDF> </x:xmpmeta> 4 IDATxyeߧ{dL.$$$! "+@EY *̪zn^f\]x@@@ $stw+$IU{>bу bUVz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K@'F*cwuQTħ W84xXwr wIk&m|]m#S{n\X/tdcae(e{<C_ zu_4\ kwCε+蹶b4jnS޲mmui)SyR0l΁i.vb<gIDATQ,m7I1Ï5\[m|]Ai 2 u-uze:ptFQ5͍/ mUdx9=`+WApm,g-(]^-UЫ2u3sNCZʨ* AL /8_6ug*eekˎi9tYWˢ@Zo6=*K[FIvYB ruVzUǡl2 _UϮ򧙞[[Zp&{BZMZ<^NㅸOv4 iM]*VUumqĺ]S!=}Keuy|f£ ]̺󙟿8'P]IENDB`
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
# Fibonacci Sequence Using Recursion def recur_fibo(n: int) -> int: """ >>> [recur_fibo(i) for i in range(12)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] """ return n if n <= 1 else recur_fibo(n - 1) + recur_fibo(n - 2) def main() -> None: limit = int(input("How many terms to include in fibonacci series: ")) if limit > 0: print(f"The first {limit} terms of the fibonacci series are as follows:") print([recur_fibo(n) for n in range(limit)]) else: print("Please enter a positive integer: ") if __name__ == "__main__": main()
# Fibonacci Sequence Using Recursion def recur_fibo(n: int) -> int: """ >>> [recur_fibo(i) for i in range(12)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] """ return n if n <= 1 else recur_fibo(n - 1) + recur_fibo(n - 2) def main() -> None: limit = int(input("How many terms to include in fibonacci series: ")) if limit > 0: print(f"The first {limit} terms of the fibonacci series are as follows:") print([recur_fibo(n) for n in range(limit)]) else: print("Please enter a positive integer: ") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( [ reduce(lambda x, y: int(x) * int(y), n[i : i + 13]) for i in range(len(n) - 12) ] ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( [ reduce(lambda x, y: int(x) * int(y), n[i : i + 13]) for i in range(len(n) - 12) ] ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 typing import Tuple def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> Tuple[int, int]: """ Extended Euclid >>> 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) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
from typing import Tuple def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> Tuple[int, int]: """ Extended Euclid >>> 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) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 FYshuffle(list): for i 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", FYshuffle(integers), FYshuffle(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 FYshuffle(list): for i 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", FYshuffle(integers), FYshuffle(strings))
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 """ from typing import List 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 succeeds we return True saying that it is possible to connect this vertices either 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 """ from typing import List 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 succeeds we return True saying that it is possible to connect this vertices either 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes, num_edges = 9, 14 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, num_edges, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes, num_edges = 9, 14 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, num_edges, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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 oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("19") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function """ oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number if __name__ == "__main__": from doctest import testmod testmod()
def oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("19") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function """ oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
"""Absolute Value.""" def abs_val(num): """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def test_abs_val(): """ >>> test_abs_val() """ assert 0 == abs_val(0) assert 34 == abs_val(34) assert 100000000000 == abs_val(-100000000000) if __name__ == "__main__": print(abs_val(-34)) # --> 34
"""Absolute Value.""" def abs_val(num): """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def test_abs_val(): """ >>> test_abs_val() """ assert 0 == abs_val(0) assert 34 == abs_val(34) assert 100000000000 == abs_val(-100000000000) if __name__ == "__main__": print(abs_val(-34)) # --> 34
-1
TheAlgorithms/Python
4,293
[mypy] fix small folders 2
### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-26T10:13:28Z"
"2021-03-26T11:21:17Z"
959507901ac8f10cd605c51c305d13b27d105536
9b60be67afca18f0d5e50e532096a68605d61b81
[mypy] fix small folders 2. ### **Describe your change:** Related Issue: #4052 * [ ] 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. * [ ] 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. * [x] 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}`.
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
name: "build" on: pull_request: schedule: - cron: "0 0 * * *" # Run everyday jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: "3.9" - uses: actions/cache@v2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools six wheel python -m pip install mypy pytest-cov -r requirements.txt # FIXME: #4052 fix mypy errors in other directories and add them here - run: mypy --ignore-missing-imports backtracking bit_manipulation blockchain boolean_algebra cellular_automata compression computer_vision fractals fuzzy_logic genetic_algorithm geodesy knapsack networking_flow scheduling sorts - name: Run tests run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/ --cov-report=term-missing:skip-covered --cov=. . - if: ${{ success() }} run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
name: "build" on: pull_request: schedule: - cron: "0 0 * * *" # Run everyday jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: "3.9" - uses: actions/cache@v2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools six wheel python -m pip install mypy pytest-cov -r requirements.txt # FIXME: #4052 fix mypy errors in other directories and add them here - run: mypy --ignore-missing-imports backtracking bit_manipulation blockchain boolean_algebra cellular_automata compression computer_vision divide_and_conquer electronics file_transfer fractals fuzzy_logic genetic_algorithm geodesy knapsack networking_flow quantum scheduling sorts - name: Run tests run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/ --cov-report=term-missing:skip-covered --cov=. . - if: ${{ success() }} run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 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) * [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 Implementation](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code_implementation.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) * [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 * [Harriscorner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harriscorner.py) * [Meanthreshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/meanthreshold.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) * [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.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) * [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) * 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) * 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) * [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 * [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 * [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) * [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) * [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) * [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) ## 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) * [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) * [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) * [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) * [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) * [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) * [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 Python](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_python.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) * [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 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) * [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 Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic_mean.py) * [Geometric Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_mean.py) * [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.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) * [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) * [Davis–Putnam–Logemann–Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davis–putnam–logemann–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) ## 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 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 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) * [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) * [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) * [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 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) * [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) * [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) * [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) * [Swap Case](https://github.com/TheAlgorithms/Python/blob/master/strings/swap_case.py) * [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.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) ## Traversals * [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/traversals/binary_tree_traversals.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) * [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) * [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) * [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 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) * [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 Implementation](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code_implementation.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) * [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 * [Harriscorner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harriscorner.py) * [Meanthreshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/meanthreshold.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) * [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.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) * [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) * 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) * 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) * [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 * [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 * [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) * [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) * [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) * [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) ## 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) * [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) * [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) * [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) * [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) * [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) * [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 Python](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_python.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) * [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 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) * [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 Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic_mean.py) * [Geometric Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_mean.py) * [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.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) * [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) * [Davis–Putnam–Logemann–Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davis–putnam–logemann–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) ## 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 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 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) * [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) * [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) * [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 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) * [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) * [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) * [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) * [Swap Case](https://github.com/TheAlgorithms/Python/blob/master/strings/swap_case.py) * [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.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) ## Traversals * [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/traversals/binary_tree_traversals.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) * [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) * [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) * [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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 typing import List def max_difference(a: List[int]) -> (int, int): """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
def max_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 math def default_matrix_multiplication(a: list, b: list) -> list: """ Multiplication only for 2x2 matrices """ if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def matrix_addition(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def matrix_subtraction(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def split_matrix(a: list) -> tuple[list, list, list, list]: """ Given an even length matrix, returns the top_left, top_right, bot_left, bot_right quadrant. >>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]]) ([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]]) >>> split_matrix([ ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6], ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6] ... ]) # doctest: +NORMALIZE_WHITESPACE ([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]]) """ if len(a) % 2 != 0 or len(a[0]) % 2 != 0: raise Exception("Odd matrices are not supported!") matrix_length = len(a) mid = matrix_length // 2 top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)] bot_right = [ [a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length) ] top_left = [[a[i][j] for j in range(mid)] for i in range(mid)] bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)] return top_left, top_right, bot_left, bot_right def matrix_dimensions(matrix: list) -> tuple[int, int]: return len(matrix), len(matrix[0]) def print_matrix(matrix: list) -> None: for i in range(len(matrix)): print(matrix[i]) def actual_strassen(matrix_a: list, matrix_b: list) -> list: """ Recursive function to calculate the product of two matrices, using the Strassen Algorithm. It only supports even length matrices. """ if matrix_dimensions(matrix_a) == (2, 2): return default_matrix_multiplication(matrix_a, matrix_b) a, b, c, d = split_matrix(matrix_a) e, f, g, h = split_matrix(matrix_b) t1 = actual_strassen(a, matrix_subtraction(f, h)) t2 = actual_strassen(matrix_addition(a, b), h) t3 = actual_strassen(matrix_addition(c, d), e) t4 = actual_strassen(d, matrix_subtraction(g, e)) t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h)) t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h)) t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f)) top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6) top_right = matrix_addition(t1, t2) bot_left = matrix_addition(t3, t4) bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7) # construct the new matrix from our 4 quadrants new_matrix = [] for i in range(len(top_right)): new_matrix.append(top_left[i] + top_right[i]) for i in range(len(bot_right)): new_matrix.append(bot_left[i] + bot_right[i]) return new_matrix def strassen(matrix1: list, matrix2: list) -> list: """ >>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]]) [[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]] >>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]]) [[139, 163], [121, 134], [100, 121]] """ if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: raise Exception( f"Unable to multiply these matrices, please check the dimensions. \n" f"Matrix A:{matrix1} \nMatrix B:{matrix2}" ) dimension1 = matrix_dimensions(matrix1) dimension2 = matrix_dimensions(matrix2) if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]: return matrix1, matrix2 maximum = max(max(dimension1), max(dimension2)) maxim = int(math.pow(2, math.ceil(math.log2(maximum)))) new_matrix1 = matrix1 new_matrix2 = matrix2 # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0, maxim): if i < dimension1[0]: for j in range(dimension1[1], maxim): new_matrix1[i].append(0) else: new_matrix1.append([0] * maxim) if i < dimension2[0]: for j in range(dimension2[1], maxim): new_matrix2[i].append(0) else: new_matrix2.append([0] * maxim) final_matrix = actual_strassen(new_matrix1, new_matrix2) # Removing the additional zeros for i in range(0, maxim): if i < dimension1[0]: for j in range(dimension2[1], maxim): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": matrix1 = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrix1, matrix2))
from __future__ import annotations import math def default_matrix_multiplication(a: list, b: list) -> list: """ Multiplication only for 2x2 matrices """ if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def matrix_addition(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def matrix_subtraction(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def split_matrix(a: list) -> tuple[list, list, list, list]: """ Given an even length matrix, returns the top_left, top_right, bot_left, bot_right quadrant. >>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]]) ([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]]) >>> split_matrix([ ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6], ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6] ... ]) # doctest: +NORMALIZE_WHITESPACE ([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]]) """ if len(a) % 2 != 0 or len(a[0]) % 2 != 0: raise Exception("Odd matrices are not supported!") matrix_length = len(a) mid = matrix_length // 2 top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)] bot_right = [ [a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length) ] top_left = [[a[i][j] for j in range(mid)] for i in range(mid)] bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)] return top_left, top_right, bot_left, bot_right def matrix_dimensions(matrix: list) -> tuple[int, int]: return len(matrix), len(matrix[0]) def print_matrix(matrix: list) -> None: for i in range(len(matrix)): print(matrix[i]) def actual_strassen(matrix_a: list, matrix_b: list) -> list: """ Recursive function to calculate the product of two matrices, using the Strassen Algorithm. It only supports even length matrices. """ if matrix_dimensions(matrix_a) == (2, 2): return default_matrix_multiplication(matrix_a, matrix_b) a, b, c, d = split_matrix(matrix_a) e, f, g, h = split_matrix(matrix_b) t1 = actual_strassen(a, matrix_subtraction(f, h)) t2 = actual_strassen(matrix_addition(a, b), h) t3 = actual_strassen(matrix_addition(c, d), e) t4 = actual_strassen(d, matrix_subtraction(g, e)) t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h)) t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h)) t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f)) top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6) top_right = matrix_addition(t1, t2) bot_left = matrix_addition(t3, t4) bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7) # construct the new matrix from our 4 quadrants new_matrix = [] for i in range(len(top_right)): new_matrix.append(top_left[i] + top_right[i]) for i in range(len(bot_right)): new_matrix.append(bot_left[i] + bot_right[i]) return new_matrix def strassen(matrix1: list, matrix2: list) -> list: """ >>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]]) [[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]] >>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]]) [[139, 163], [121, 134], [100, 121]] """ if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: raise Exception( f"Unable to multiply these matrices, please check the dimensions. \n" f"Matrix A:{matrix1} \nMatrix B:{matrix2}" ) dimension1 = matrix_dimensions(matrix1) dimension2 = matrix_dimensions(matrix2) if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]: return [matrix1, matrix2] maximum = max(max(dimension1), max(dimension2)) maxim = int(math.pow(2, math.ceil(math.log2(maximum)))) new_matrix1 = matrix1 new_matrix2 = matrix2 # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0, maxim): if i < dimension1[0]: for j in range(dimension1[1], maxim): new_matrix1[i].append(0) else: new_matrix1.append([0] * maxim) if i < dimension2[0]: for j in range(dimension2[1], maxim): new_matrix2[i].append(0) else: new_matrix2.append([0] * maxim) final_matrix = actual_strassen(new_matrix1, new_matrix2) # Removing the additional zeros for i in range(0, maxim): if i < dimension1[0]: for j in range(dimension2[1], maxim): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": matrix1 = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrix1, matrix2))
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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.m.wikipedia.org/wiki/Electric_power from collections import namedtuple from typing import Tuple def electric_power(voltage: float, current: float, power: float) -> Tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): File "<stdin>", line 15, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): File "<stdin>", line 19, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): File "<stdin>", line 23, in <modulei ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) result(name='power', value=4.84) """ result = namedtuple("result", "name value") if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage", power / current) elif current == 0: return result("current", power / voltage) elif power == 0: return result("power", float(round(abs(voltage * current), 2))) if __name__ == "__main__": import doctest doctest.testmod()
# https://en.m.wikipedia.org/wiki/Electric_power from collections import namedtuple from typing import Tuple def electric_power(voltage: float, current: float, power: float) -> Tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): File "<stdin>", line 15, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): File "<stdin>", line 19, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): File "<stdin>", line 23, in <modulei ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) result(name='power', value=4.84) """ result = namedtuple("result", "name value") if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage", power / current) elif current == 0: return result("current", power / voltage) elif power == 0: return result("power", float(round(abs(voltage * current), 2))) else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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/Ohm%27s_law from typing import Dict def ohms_law(voltage: float, current: float, resistance: float) -> Dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Ohm%27s_law from typing import Dict def ohms_law(voltage: float, current: float, resistance: float) -> Dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
if __name__ == "__main__": import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) print(f"data={data}") if not data: break out_file.write(data) # Write data to a file print("Successfully got the file") sock.close() print("Connection closed")
if __name__ == "__main__": import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) print(f"{data = }") if not data: break out_file.write(data) # Write data to a file print("Successfully got the file") sock.close() print("Connection closed")
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 send_file(filename: str = "mytext.txt", testing: bool = False) -> None: import socket port = 12312 # Reserve a port for your service. sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name sock.bind((host, port)) # Bind to the port sock.listen(5) # Now wait for client connection. print("Server listening....") while True: conn, addr = sock.accept() # Establish connection with client. print(f"Got connection from {addr}") data = conn.recv(1024) print(f"Server received {data}") with open(filename, "rb") as in_file: data = in_file.read(1024) while data: conn.send(data) print(f"Sent {data!r}") data = in_file.read(1024) print("Done sending") conn.close() if testing: # Allow the test to complete break sock.shutdown(1) sock.close() if __name__ == "__main__": send_file()
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: import socket port = 12312 # Reserve a port for your service. sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name sock.bind((host, port)) # Bind to the port sock.listen(5) # Now wait for client connection. print("Server listening....") while True: conn, addr = sock.accept() # Establish connection with client. print(f"Got connection from {addr}") data = conn.recv(1024) print(f"Server received: {data = }") with open(filename, "rb") as in_file: data = in_file.read(1024) while data: conn.send(data) print(f"Sent {data!r}") data = in_file.read(1024) print("Done sending") conn.close() if testing: # Allow the test to complete break sock.shutdown(1) sock.close() if __name__ == "__main__": send_file()
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate from qiskit import Aer, QuantumCircuit, execute from qiskit.providers import BaseBackend def store_two_classics(val1: int, val2: int) -> (QuantumCircuit, str, str): """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because its easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) def ripple_adder( val1: int, val2: int, backend: BaseBackend = Aer.get_backend("qasm_simulator") ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding +ve Integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts().keys())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate from qiskit import Aer, QuantumCircuit, execute from qiskit.providers import BaseBackend def store_two_classics(val1: int, val2: int) -> tuple[QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because its easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) def ripple_adder( val1: int, val2: int, backend: BaseBackend = Aer.get_backend("qasm_simulator") ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding +ve Integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts().keys())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
"""Find mean of a list of numbers.""" def average(nums): """Find mean of a list of numbers.""" return sum(nums) / len(nums) def test_average(): """ >>> test_average() """ assert 12.0 == average([3, 6, 9, 12, 15, 18, 21]) assert 20 == average([5, 10, 15, 20, 25, 30, 35]) assert 4.5 == average([1, 2, 3, 4, 5, 6, 7, 8]) if __name__ == "__main__": """Call average module to find mean of a specific list of numbers.""" print(average([2, 4, 6, 8, 20, 50, 70]))
"""Find mean of a list of numbers.""" def average(nums): """Find mean of a list of numbers.""" return sum(nums) / len(nums) def test_average(): """ >>> test_average() """ assert 12.0 == average([3, 6, 9, 12, 15, 18, 21]) assert 20 == average([5, 10, 15, 20, 25, 30, 35]) assert 4.5 == average([1, 2, 3, 4, 5, 6, 7, 8]) if __name__ == "__main__": """Call average module to find mean of a specific list of numbers.""" print(average([2, 4, 6, 8, 20, 50, 70]))
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
"""Matrix Exponentiation""" import timeit """ Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time. You read more about it here: http://zobayer.blogspot.com/2010/11/matrix-exponentiation.html https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/ """ class Matrix: def __init__(self, arg): if isinstance(arg, list): # Initializes a matrix identical to the one provided. self.t = arg self.n = len(arg) else: # Initializes a square matrix of the given size and set values to zero. self.n = arg self.t = [[0 for _ in range(self.n)] for _ in range(self.n)] def __mul__(self, b): matrix = Matrix(self.n) for i in range(self.n): for j in range(self.n): for k in range(self.n): matrix.t[i][j] += self.t[i][k] * b.t[k][j] return matrix def modular_exponentiation(a, b): matrix = Matrix([[1, 0], [0, 1]]) while b > 0: if b & 1: matrix *= a a *= a b >>= 1 return matrix def fibonacci_with_matrix_exponentiation(n, f1, f2): # Trivial Cases if n == 1: return f1 elif n == 2: return f2 matrix = Matrix([[1, 1], [1, 0]]) matrix = modular_exponentiation(matrix, n - 2) return f2 * matrix.t[0][0] + f1 * matrix.t[0][1] def simple_fibonacci(n, f1, f2): # Trivial Cases if n == 1: return f1 elif n == 2: return f2 fn_1 = f1 fn_2 = f2 n -= 2 while n > 0: fn_1, fn_2 = fn_1 + fn_2, fn_1 n -= 1 return fn_1 def matrix_exponentiation_time(): setup = """ from random import randint from __main__ import fibonacci_with_matrix_exponentiation """ code = "fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print("With matrix exponentiation the average execution time is ", exec_time / 100) return exec_time def simple_fibonacci_time(): setup = """ from random import randint from __main__ import simple_fibonacci """ code = "simple_fibonacci(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print( "Without matrix exponentiation the average execution time is ", exec_time / 100 ) return exec_time def main(): matrix_exponentiation_time() simple_fibonacci_time() if __name__ == "__main__": main()
"""Matrix Exponentiation""" import timeit """ Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time. You read more about it here: http://zobayer.blogspot.com/2010/11/matrix-exponentiation.html https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/ """ class Matrix: def __init__(self, arg): if isinstance(arg, list): # Initializes a matrix identical to the one provided. self.t = arg self.n = len(arg) else: # Initializes a square matrix of the given size and set values to zero. self.n = arg self.t = [[0 for _ in range(self.n)] for _ in range(self.n)] def __mul__(self, b): matrix = Matrix(self.n) for i in range(self.n): for j in range(self.n): for k in range(self.n): matrix.t[i][j] += self.t[i][k] * b.t[k][j] return matrix def modular_exponentiation(a, b): matrix = Matrix([[1, 0], [0, 1]]) while b > 0: if b & 1: matrix *= a a *= a b >>= 1 return matrix def fibonacci_with_matrix_exponentiation(n, f1, f2): # Trivial Cases if n == 1: return f1 elif n == 2: return f2 matrix = Matrix([[1, 1], [1, 0]]) matrix = modular_exponentiation(matrix, n - 2) return f2 * matrix.t[0][0] + f1 * matrix.t[0][1] def simple_fibonacci(n, f1, f2): # Trivial Cases if n == 1: return f1 elif n == 2: return f2 fn_1 = f1 fn_2 = f2 n -= 2 while n > 0: fn_1, fn_2 = fn_1 + fn_2, fn_1 n -= 1 return fn_1 def matrix_exponentiation_time(): setup = """ from random import randint from __main__ import fibonacci_with_matrix_exponentiation """ code = "fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print("With matrix exponentiation the average execution time is ", exec_time / 100) return exec_time def simple_fibonacci_time(): setup = """ from random import randint from __main__ import simple_fibonacci """ code = "simple_fibonacci(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print( "Without matrix exponentiation the average execution time is ", exec_time / 100 ) return exec_time def main(): matrix_exponentiation_time() simple_fibonacci_time() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 median filter algorithm """ from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
""" Implementation of median filter algorithm """ from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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! """ def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ fact = 1 result = 0 for i in range(1, num + 1): fact *= i for j in str(fact): result += int(j) return result 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! """ def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ fact = 1 result = 0 for i in range(1, num + 1): fact *= i for j in str(fact): result += int(j) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 from collections import Counter from random import random class MarkovChainGraphUndirectedUnweighted: """ Undirected Unweighted Graph for running Markov Chain Algorithm """ def __init__(self): self.connections = {} def add_node(self, node: str) -> None: self.connections[node] = {} def add_transition_probability( self, node1: str, node2: str, probability: float ) -> None: if node1 not in self.connections: self.add_node(node1) if node2 not in self.connections: self.add_node(node2) self.connections[node1][node2] = probability def get_nodes(self) -> list[str]: return list(self.connections) def transition(self, node: str) -> str: current_probability = 0 random_value = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest def get_transitions( start: str, transitions: list[tuple[str, str, float]], steps: int ) -> dict[str, int]: """ Running Markov Chain algorithm and calculating the number of times each node is visited >>> transitions = [ ... ('a', 'a', 0.9), ... ('a', 'b', 0.075), ... ('a', 'c', 0.025), ... ('b', 'a', 0.15), ... ('b', 'b', 0.8), ... ('b', 'c', 0.05), ... ('c', 'a', 0.25), ... ('c', 'b', 0.25), ... ('c', 'c', 0.5) ... ] >>> result = get_transitions('a', transitions, 5000) >>> result['a'] > result['b'] > result['c'] True """ graph = MarkovChainGraphUndirectedUnweighted() for node1, node2, probability in transitions: graph.add_transition_probability(node1, node2, probability) visited = Counter(graph.get_nodes()) node = start for _ in range(steps): node = graph.transition(node) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from collections import Counter from random import random class MarkovChainGraphUndirectedUnweighted: """ Undirected Unweighted Graph for running Markov Chain Algorithm """ def __init__(self): self.connections = {} def add_node(self, node: str) -> None: self.connections[node] = {} def add_transition_probability( self, node1: str, node2: str, probability: float ) -> None: if node1 not in self.connections: self.add_node(node1) if node2 not in self.connections: self.add_node(node2) self.connections[node1][node2] = probability def get_nodes(self) -> list[str]: return list(self.connections) def transition(self, node: str) -> str: current_probability = 0 random_value = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest def get_transitions( start: str, transitions: list[tuple[str, str, float]], steps: int ) -> dict[str, int]: """ Running Markov Chain algorithm and calculating the number of times each node is visited >>> transitions = [ ... ('a', 'a', 0.9), ... ('a', 'b', 0.075), ... ('a', 'c', 0.025), ... ('b', 'a', 0.15), ... ('b', 'b', 0.8), ... ('b', 'c', 0.05), ... ('c', 'a', 0.25), ... ('c', 'b', 0.25), ... ('c', 'c', 0.5) ... ] >>> result = get_transitions('a', transitions, 5000) >>> result['a'] > result['b'] > result['c'] True """ graph = MarkovChainGraphUndirectedUnweighted() for node1, node2, probability in transitions: graph.add_transition_probability(node1, node2, probability) visited = Counter(graph.get_nodes()) node = start for _ in range(steps): node = graph.transition(node) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 """ Build a quantum circuit with pair or group of qubits to perform quantum entanglement. Quantum entanglement is a phenomenon observed at the quantum scale where entangled particles stay connected (in some sense) so that the actions performed on one of the particles affects the other, no matter the distance between two particles. """ import qiskit def quantum_entanglement(qubits: int = 2) -> qiskit.result.counts.Counts: """ # >>> quantum_entanglement(2) # {'00': 500, '11': 500} # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├─── # └───┘┌─┴─┐└╥┘┌─┐ # q_1: ─────┤ X ├─╫─┤M├ # └───┘ ║ └╥┘ # c: 2/═══════════╩══╩═ # 0 1 Args: qubits (int): number of quibits to use. Defaults to 2 Returns: qiskit.result.counts.Counts: mapping of states to its counts """ classical_bits = qubits # Using Aer's qasm_simulator simulator = qiskit.Aer.get_backend("qasm_simulator") # Creating a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0) for i in range(1, qubits): # Adding CX (CNOT) gate circuit.cx(i - 1, i) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(qubits)), list(range(classical_bits))) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the qasm simulator job = qiskit.execute(circuit, simulator, shots=1000) return job.result().get_counts(circuit) if __name__ == "__main__": print(f"Total count for various states are: {quantum_entanglement(3)}")
#!/usr/bin/env python3 """ Build a quantum circuit with pair or group of qubits to perform quantum entanglement. Quantum entanglement is a phenomenon observed at the quantum scale where entangled particles stay connected (in some sense) so that the actions performed on one of the particles affects the other, no matter the distance between two particles. """ import qiskit def quantum_entanglement(qubits: int = 2) -> qiskit.result.counts.Counts: """ # >>> quantum_entanglement(2) # {'00': 500, '11': 500} # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├─── # └───┘┌─┴─┐└╥┘┌─┐ # q_1: ─────┤ X ├─╫─┤M├ # └───┘ ║ └╥┘ # c: 2/═══════════╩══╩═ # 0 1 Args: qubits (int): number of quibits to use. Defaults to 2 Returns: qiskit.result.counts.Counts: mapping of states to its counts """ classical_bits = qubits # Using Aer's qasm_simulator simulator = qiskit.Aer.get_backend("qasm_simulator") # Creating a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0) for i in range(1, qubits): # Adding CX (CNOT) gate circuit.cx(i - 1, i) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(qubits)), list(range(classical_bits))) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the qasm simulator job = qiskit.execute(circuit, simulator, shots=1000) return job.result().get_counts(circuit) if __name__ == "__main__": print(f"Total count for various states are: {quantum_entanglement(3)}")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 requests from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info def test_fetch_github_info(monkeypatch): class FakeResponse: def __init__(self, content) -> None: assert isinstance(content, (bytes, str)) self.content = content def json(self): return json.loads(self.content) def mock_response(*args, **kwargs): assert args[0] == AUTHENTICATED_USER_ENDPOINT assert "Authorization" in kwargs["headers"] assert kwargs["headers"]["Authorization"].startswith("token ") assert "Accept" in kwargs["headers"] return FakeResponse(b'{"login":"test","id":1}') monkeypatch.setattr(requests, "get", mock_response) result = fetch_github_info("token") assert result["login"] == "test" assert result["id"] == 1
import json import requests from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info def test_fetch_github_info(monkeypatch): class FakeResponse: def __init__(self, content) -> None: assert isinstance(content, (bytes, str)) self.content = content def json(self): return json.loads(self.content) def mock_response(*args, **kwargs): assert args[0] == AUTHENTICATED_USER_ENDPOINT assert "Authorization" in kwargs["headers"] assert kwargs["headers"]["Authorization"].startswith("token ") assert "Accept" in kwargs["headers"] return FakeResponse(b'{"login":"test","id":1}') monkeypatch.setattr(requests, "get", mock_response) result = fetch_github_info("token") assert result["login"] == "test" assert result["id"] == 1
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Approximates the area under the curve using the trapezoidal rule """ from typing import Callable, Union def trapezoidal_area( fnc: Callable[[Union[int, float]], Union[int, float]], x_start: Union[int, float], x_end: Union[int, float], steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" '10.000' >>> def f(x): ... return 9*x**2 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" '192.0000' >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for i in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x ** 3 + x ** 2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
""" Approximates the area under the curve using the trapezoidal rule """ from typing import Callable, Union def trapezoidal_area( fnc: Callable[[Union[int, float]], Union[int, float]], x_start: Union[int, float], x_end: Union[int, float], steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" '10.000' >>> def f(x): ... return 9*x**2 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" '192.0000' >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for i in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x ** 3 + x ** 2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(num: int) -> bool: """ Determines whether the given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True >>> is_prime(0) False """ if num == 2: return True elif num % 2 == 0: return False else: sq = int(sqrt(num)) + 1 for i in range(3, sq, 2): if num % i == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ count = 0 number = 1 while count != nth and number < 3: number += 1 if is_prime(number): count += 1 while count != nth: number += 2 if is_prime(number): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(num: int) -> bool: """ Determines whether the given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True >>> is_prime(0) False """ if num == 2: return True elif num % 2 == 0: return False else: sq = int(sqrt(num)) + 1 for i in range(3, sq, 2): if num % i == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ count = 0 number = 1 while count != nth and number < 3: number += 1 if is_prime(number): count += 1 while count != nth: number += 2 if is_prime(number): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handing Writing Word Photo Detail:Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hidden layer of BP * Output layer of BP Author: Stephen Lee Github: [email protected] Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ import pickle import numpy as np from matplotlib import pyplot as plt class CNN: def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): """ :param conv1_get: [a,c,d],size, number, step of convolution kernel :param size_p1: pooling size :param bp_num1: units number of flatten layer :param bp_num2: units number of hidden layer :param bp_num3: units number of output layer :param rate_w: rate of weight learning :param rate_t: rate of threshold learning """ self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t self.w_conv1 = [ np.mat(-1 * np.random.rand(self.conv1[0], self.conv1[0]) + 0.5) for i in range(self.conv1[1]) ] self.wkj = np.mat(-1 * np.random.rand(self.num_bp3, self.num_bp2) + 0.5) self.vji = np.mat(-1 * np.random.rand(self.num_bp2, self.num_bp1) + 0.5) self.thre_conv1 = -2 * np.random.rand(self.conv1[1]) + 1 self.thre_bp2 = -2 * np.random.rand(self.num_bp2) + 1 self.thre_bp3 = -2 * np.random.rand(self.num_bp3) + 1 def save_model(self, save_path): # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, "num_bp2": self.num_bp2, "num_bp3": self.num_bp3, "conv1": self.conv1, "step_conv1": self.step_conv1, "size_pooling1": self.size_pooling1, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conv1, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conv1, "thre_bp2": self.thre_bp2, "thre_bp3": self.thre_bp3, } with open(save_path, "wb") as f: pickle.dump(model_dic, f) print("Model saved: %s" % save_path) @classmethod def ReadModel(cls, model_path): # read saved model with open(model_path, "rb") as f: model_dic = pickle.load(f) conv_get = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) size_p1 = model_dic.get("size_pooling1") bp1 = model_dic.get("num_bp1") bp2 = model_dic.get("num_bp2") bp3 = model_dic.get("num_bp3") r_w = model_dic.get("rate_weight") r_t = model_dic.get("rate_thre") # create model instance conv_ins = CNN(conv_get, size_p1, bp1, bp2, bp3, r_w, r_t) # modify model parameter conv_ins.w_conv1 = model_dic.get("w_conv1") conv_ins.wkj = model_dic.get("wkj") conv_ins.vji = model_dic.get("vji") conv_ins.thre_conv1 = model_dic.get("thre_conv1") conv_ins.thre_bp2 = model_dic.get("thre_bp2") conv_ins.thre_bp3 = model_dic.get("thre_bp3") return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1 * x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): # convolution process size_conv = convs[0] num_conv = convs[1] size_data = np.shape(data)[0] # get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(focus) # calculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] Size_FeatureMap = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = ( np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape( Size_FeatureMap, Size_FeatureMap ) data_featuremap.append(featuremap) # expanding the data slice to One dimenssion focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list, data_featuremap def pooling(self, featuremaps, size_pooling, type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): focus = map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if type == "average_pool": # average pooling map_pooled.append(np.average(focus)) elif type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, data): # expanding three dimension data to one dimension list data_expanded = [] for i in range(len(data)): shapes = np.shape(data[i]) data_listed = data[i].reshape(1, shapes[0] * shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): # expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1, shapes[0] * shapes[1]) return data_expanded def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): """ calculate the gradient from the data slice of pool layer pd_pool: list of matrix out_map: the shape of data slice(size_map*size_map) return: pd_all: list of matrix, [num, size_map, size_map] """ pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i : i + size_pooling, j : j + size_pooling] = pd_pool[ i_pool ] i_pool = i_pool + 1 pd_conv2 = np.multiply( pd_conv1, np.multiply(out_map[i_map], (1 - out_map[i_map])) ) pd_all.append(pd_conv2) return pd_all def train( self, patterns, datas_train, datas_teach, n_repeat, error_accuracy, draw_e=bool ): # model traning print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(datas_train))) print((" - - Shape: Teach_Data ", np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: error_count = 0 print("-------------Learning Time %d--------------" % rp) for p in range(len(datas_train)): # print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1, data_conved1 = self.convolute( data_train, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) """ print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) """ data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1, self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2, self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- pd_k_all = np.multiply( (data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3)) ) pd_j_all = np.multiply( np.dot(pd_k_all, self.wkj), np.multiply(bp_out2, (1 - bp_out2)) ) pd_i_all = np.dot(pd_j_all, self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1 * self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool( data_conved1, pd_conv1_pooled, shape_featuremap1[0], shape_featuremap1[1], self.size_pooling1, ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list, data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape( (self.conv1[0], self.conv1[0]) ) self.thre_conv1[k_conv] = ( self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre ) # all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs(data_teach - bp_out3)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) rp = rp + 1 mse = error_count / patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, "+-") plt.plot(yplot, "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(True, alpha=0.5) plt.show() print("------------------Training Complished---------------------") print((" - - Training epoch: ", rp, " - - Mse: %.6f" % mse)) if draw_e: draw_error() return mse def predict(self, datas_test): # model predict produce_out = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round, each)) for each in produce_out] return np.asarray(res) def convolution(self, data): # return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1, data_pooled1 if __name__ == "__main__": """ I will put the example on other file """
""" - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handing Writing Word Photo Detail:Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hidden layer of BP * Output layer of BP Author: Stephen Lee Github: [email protected] Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ import pickle import numpy as np from matplotlib import pyplot as plt class CNN: def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): """ :param conv1_get: [a,c,d],size, number, step of convolution kernel :param size_p1: pooling size :param bp_num1: units number of flatten layer :param bp_num2: units number of hidden layer :param bp_num3: units number of output layer :param rate_w: rate of weight learning :param rate_t: rate of threshold learning """ self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t self.w_conv1 = [ np.mat(-1 * np.random.rand(self.conv1[0], self.conv1[0]) + 0.5) for i in range(self.conv1[1]) ] self.wkj = np.mat(-1 * np.random.rand(self.num_bp3, self.num_bp2) + 0.5) self.vji = np.mat(-1 * np.random.rand(self.num_bp2, self.num_bp1) + 0.5) self.thre_conv1 = -2 * np.random.rand(self.conv1[1]) + 1 self.thre_bp2 = -2 * np.random.rand(self.num_bp2) + 1 self.thre_bp3 = -2 * np.random.rand(self.num_bp3) + 1 def save_model(self, save_path): # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, "num_bp2": self.num_bp2, "num_bp3": self.num_bp3, "conv1": self.conv1, "step_conv1": self.step_conv1, "size_pooling1": self.size_pooling1, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conv1, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conv1, "thre_bp2": self.thre_bp2, "thre_bp3": self.thre_bp3, } with open(save_path, "wb") as f: pickle.dump(model_dic, f) print("Model saved: %s" % save_path) @classmethod def ReadModel(cls, model_path): # read saved model with open(model_path, "rb") as f: model_dic = pickle.load(f) conv_get = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) size_p1 = model_dic.get("size_pooling1") bp1 = model_dic.get("num_bp1") bp2 = model_dic.get("num_bp2") bp3 = model_dic.get("num_bp3") r_w = model_dic.get("rate_weight") r_t = model_dic.get("rate_thre") # create model instance conv_ins = CNN(conv_get, size_p1, bp1, bp2, bp3, r_w, r_t) # modify model parameter conv_ins.w_conv1 = model_dic.get("w_conv1") conv_ins.wkj = model_dic.get("wkj") conv_ins.vji = model_dic.get("vji") conv_ins.thre_conv1 = model_dic.get("thre_conv1") conv_ins.thre_bp2 = model_dic.get("thre_bp2") conv_ins.thre_bp3 = model_dic.get("thre_bp3") return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1 * x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): # convolution process size_conv = convs[0] num_conv = convs[1] size_data = np.shape(data)[0] # get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(focus) # calculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] Size_FeatureMap = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = ( np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape( Size_FeatureMap, Size_FeatureMap ) data_featuremap.append(featuremap) # expanding the data slice to One dimenssion focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list, data_featuremap def pooling(self, featuremaps, size_pooling, type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): focus = map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if type == "average_pool": # average pooling map_pooled.append(np.average(focus)) elif type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, data): # expanding three dimension data to one dimension list data_expanded = [] for i in range(len(data)): shapes = np.shape(data[i]) data_listed = data[i].reshape(1, shapes[0] * shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): # expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1, shapes[0] * shapes[1]) return data_expanded def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): """ calculate the gradient from the data slice of pool layer pd_pool: list of matrix out_map: the shape of data slice(size_map*size_map) return: pd_all: list of matrix, [num, size_map, size_map] """ pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i : i + size_pooling, j : j + size_pooling] = pd_pool[ i_pool ] i_pool = i_pool + 1 pd_conv2 = np.multiply( pd_conv1, np.multiply(out_map[i_map], (1 - out_map[i_map])) ) pd_all.append(pd_conv2) return pd_all def train( self, patterns, datas_train, datas_teach, n_repeat, error_accuracy, draw_e=bool ): # model traning print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(datas_train))) print((" - - Shape: Teach_Data ", np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: error_count = 0 print("-------------Learning Time %d--------------" % rp) for p in range(len(datas_train)): # print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1, data_conved1 = self.convolute( data_train, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) """ print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) """ data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1, self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2, self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- pd_k_all = np.multiply( (data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3)) ) pd_j_all = np.multiply( np.dot(pd_k_all, self.wkj), np.multiply(bp_out2, (1 - bp_out2)) ) pd_i_all = np.dot(pd_j_all, self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1 * self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool( data_conved1, pd_conv1_pooled, shape_featuremap1[0], shape_featuremap1[1], self.size_pooling1, ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list, data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape( (self.conv1[0], self.conv1[0]) ) self.thre_conv1[k_conv] = ( self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre ) # all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs(data_teach - bp_out3)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) rp = rp + 1 mse = error_count / patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, "+-") plt.plot(yplot, "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(True, alpha=0.5) plt.show() print("------------------Training Complished---------------------") print((" - - Training epoch: ", rp, " - - Mse: %.6f" % mse)) if draw_e: draw_error() return mse def predict(self, datas_test): # model predict produce_out = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round, each)) for each in produce_out] return np.asarray(res) def convolution(self, data): # return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1, data_pooled1 if __name__ == "__main__": """ I will put the example on other file """
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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/Tree_traversal class Node: """ A Node has data variable and pointers to its left and right nodes. """ def __init__(self, data): self.left = None self.right = None self.data = data def make_tree() -> Node: root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) return root def preorder(root: Node): """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node): """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node): """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node): """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order_1(root: Node): """ Print whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ if not root: return temp = root que = [temp] while len(que) > 0: print(que[0].data, end=" ") temp = que.pop(0) if temp.left: que.append(temp.left) if temp.right: que.append(temp.right) return que def level_order_2(root: Node, level: int): """ Level-wise traversal: Print all nodes present at the given level of the binary tree """ if not root: return root if level == 1: print(root.data, end=" ") elif level > 1: level_order_2(root.left, level - 1) level_order_2(root.right, level - 1) def print_left_to_right(root: Node, level: int): """ Print elements on particular level from left to right direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_left_to_right(root.left, level - 1) print_left_to_right(root.right, level - 1) def print_right_to_left(root: Node, level: int): """ Print elements on particular level from right to left direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_right_to_left(root.right, level - 1) print_right_to_left(root.left, level - 1) def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: print_right_to_left(root, h) flag = 0 def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversal is {postorder(root)}") print(f"Height of Tree is {height(root)}") print("Complete Level Order Traversal is : ") level_order_1(root) print("\nLevel-wise order Traversal is : ") for h in range(1, height(root) + 1): level_order_2(root, h) print("\nZigZag order Traversal is : ") zigzag(root) print() if __name__ == "__main__": import doctest doctest.testmod() main()
# https://en.wikipedia.org/wiki/Tree_traversal class Node: """ A Node has data variable and pointers to its left and right nodes. """ def __init__(self, data): self.left = None self.right = None self.data = data def make_tree() -> Node: root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) return root def preorder(root: Node): """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node): """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node): """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node): """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order_1(root: Node): """ Print whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ if not root: return temp = root que = [temp] while len(que) > 0: print(que[0].data, end=" ") temp = que.pop(0) if temp.left: que.append(temp.left) if temp.right: que.append(temp.right) return que def level_order_2(root: Node, level: int): """ Level-wise traversal: Print all nodes present at the given level of the binary tree """ if not root: return root if level == 1: print(root.data, end=" ") elif level > 1: level_order_2(root.left, level - 1) level_order_2(root.right, level - 1) def print_left_to_right(root: Node, level: int): """ Print elements on particular level from left to right direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_left_to_right(root.left, level - 1) print_left_to_right(root.right, level - 1) def print_right_to_left(root: Node, level: int): """ Print elements on particular level from right to left direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_right_to_left(root.right, level - 1) print_right_to_left(root.left, level - 1) def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: print_right_to_left(root, h) flag = 0 def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversal is {postorder(root)}") print(f"Height of Tree is {height(root)}") print("Complete Level Order Traversal is : ") level_order_1(root) print("\nLevel-wise order Traversal is : ") for h in range(1, height(root) + 1): level_order_2(root, h) print("\nZigZag order Traversal is : ") zigzag(root) print() if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 actual_power(a: int, b: int): """ Function using divide and conquer to calculate a^b. It only works for integer a,b. """ if b == 0: return 1 if (b % 2) == 0: return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) else: return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) def power(a: int, b: int) -> float: """ >>> power(4,6) 4096 >>> power(2,3) 8 >>> power(-2,3) -8 >>> power(2,-3) 0.125 >>> power(-2,-3) -0.125 """ if b < 0: return 1 / actual_power(a, b) return actual_power(a, b) if __name__ == "__main__": print(power(-2, -3))
def actual_power(a: int, b: int): """ Function using divide and conquer to calculate a^b. It only works for integer a,b. """ if b == 0: return 1 if (b % 2) == 0: return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) else: return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) def power(a: int, b: int) -> float: """ >>> power(4,6) 4096 >>> power(2,3) 8 >>> power(-2,3) -8 >>> power(2,-3) 0.125 >>> power(-2,-3) -0.125 """ if b < 0: return 1 / actual_power(a, b) return actual_power(a, b) if __name__ == "__main__": print(power(-2, -3))
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 quick_sort_3partition(sorting: list, left: int, right: int) -> None: if right <= left: return a = i = left b = right pivot = sorting[left] while i <= b: if sorting[i] < pivot: sorting[a], sorting[i] = sorting[i], sorting[a] a += 1 i += 1 elif sorting[i] > pivot: sorting[b], sorting[i] = sorting[i], sorting[b] b -= 1 else: i += 1 quick_sort_3partition(sorting, left, a - 1) quick_sort_3partition(sorting, b + 1, right) def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None: """ A pure Python implementation of quick sort algorithm(in-place) with Lomuto partition scheme: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme :param sorting: sort list :param left: left endpoint of sorting :param right: right endpoint of sorting :return: None Examples: >>> nums1 = [0, 5, 3, 1, 2] >>> quick_sort_lomuto_partition(nums1, 0, 4) >>> nums1 [0, 1, 2, 3, 5] >>> nums2 = [] >>> quick_sort_lomuto_partition(nums2, 0, 0) >>> nums2 [] >>> nums3 = [-2, 5, 0, -4] >>> quick_sort_lomuto_partition(nums3, 0, 3) >>> nums3 [-4, -2, 0, 5] """ if left < right: pivot_index = lomuto_partition(sorting, left, right) quick_sort_lomuto_partition(sorting, left, pivot_index - 1) quick_sort_lomuto_partition(sorting, pivot_index + 1, right) def lomuto_partition(sorting: list, left: int, right: int) -> int: """ Example: >>> lomuto_partition([1,5,7,6], 0, 3) 2 """ pivot = sorting[right] store_index = left for i in range(left, right): if sorting[i] < pivot: sorting[store_index], sorting[i] = sorting[i], sorting[store_index] store_index += 1 sorting[right], sorting[store_index] = sorting[store_index], sorting[right] return store_index def three_way_radix_quicksort(sorting: list) -> list: """ Three-way radix quicksort: https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort First divide the list into three parts. Then recursively sort the "less than" and "greater than" partitions. >>> three_way_radix_quicksort([]) [] >>> three_way_radix_quicksort([1]) [1] >>> three_way_radix_quicksort([-5, -2, 1, -2, 0, 1]) [-5, -2, -2, 0, 1, 1] >>> three_way_radix_quicksort([1, 2, 5, 1, 2, 0, 0, 5, 2, -1]) [-1, 0, 0, 1, 1, 2, 2, 2, 5, 5] """ if len(sorting) <= 1: return sorting return ( three_way_radix_quicksort([i for i in sorting if i < sorting[0]]) + [i for i in sorting if i == sorting[0]] + three_way_radix_quicksort([i for i in sorting if i > sorting[0]]) ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] quick_sort_3partition(unsorted, 0, len(unsorted) - 1) print(unsorted)
def quick_sort_3partition(sorting: list, left: int, right: int) -> None: if right <= left: return a = i = left b = right pivot = sorting[left] while i <= b: if sorting[i] < pivot: sorting[a], sorting[i] = sorting[i], sorting[a] a += 1 i += 1 elif sorting[i] > pivot: sorting[b], sorting[i] = sorting[i], sorting[b] b -= 1 else: i += 1 quick_sort_3partition(sorting, left, a - 1) quick_sort_3partition(sorting, b + 1, right) def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None: """ A pure Python implementation of quick sort algorithm(in-place) with Lomuto partition scheme: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme :param sorting: sort list :param left: left endpoint of sorting :param right: right endpoint of sorting :return: None Examples: >>> nums1 = [0, 5, 3, 1, 2] >>> quick_sort_lomuto_partition(nums1, 0, 4) >>> nums1 [0, 1, 2, 3, 5] >>> nums2 = [] >>> quick_sort_lomuto_partition(nums2, 0, 0) >>> nums2 [] >>> nums3 = [-2, 5, 0, -4] >>> quick_sort_lomuto_partition(nums3, 0, 3) >>> nums3 [-4, -2, 0, 5] """ if left < right: pivot_index = lomuto_partition(sorting, left, right) quick_sort_lomuto_partition(sorting, left, pivot_index - 1) quick_sort_lomuto_partition(sorting, pivot_index + 1, right) def lomuto_partition(sorting: list, left: int, right: int) -> int: """ Example: >>> lomuto_partition([1,5,7,6], 0, 3) 2 """ pivot = sorting[right] store_index = left for i in range(left, right): if sorting[i] < pivot: sorting[store_index], sorting[i] = sorting[i], sorting[store_index] store_index += 1 sorting[right], sorting[store_index] = sorting[store_index], sorting[right] return store_index def three_way_radix_quicksort(sorting: list) -> list: """ Three-way radix quicksort: https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort First divide the list into three parts. Then recursively sort the "less than" and "greater than" partitions. >>> three_way_radix_quicksort([]) [] >>> three_way_radix_quicksort([1]) [1] >>> three_way_radix_quicksort([-5, -2, 1, -2, 0, 1]) [-5, -2, -2, 0, 1, 1] >>> three_way_radix_quicksort([1, 2, 5, 1, 2, 0, 0, 5, 2, -1]) [-1, 0, 0, 1, 1, 2, 2, 2, 5, 5] """ if len(sorting) <= 1: return sorting return ( three_way_radix_quicksort([i for i in sorting if i < sorting[0]]) + [i for i in sorting if i == sorting[0]] + three_way_radix_quicksort([i for i in sorting if i > sorting[0]]) ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] quick_sort_3partition(unsorted, 0, len(unsorted) - 1) print(unsorted)
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a and c(dABCd) -> remove d (ABC) """ def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
""" https://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a and c(dABCd) -> remove d (ABC) """ def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible """ def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible """ def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == "__main__": # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
from collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == "__main__": # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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/Combination """ from math import factorial def combinations(n: int, k: int) -> int: """ Returns the number of different combinations of k length which can be made from n values, where n >= k. Examples: >>> combinations(10,5) 252 >>> combinations(6,3) 20 >>> combinations(20,5) 15504 >>> combinations(52, 5) 2598960 >>> combinations(0, 0) 1 >>> combinations(-4, -5) ... Traceback (most recent call last): ValueError: Please enter positive integers for n and k where n >= k """ # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k") return int(factorial(n) / ((factorial(k)) * (factorial(n - k)))) if __name__ == "__main__": print( "\nThe number of five-card hands possible from a standard", f"fifty-two card deck is: {combinations(52, 5)}", ) print( "\nIf a class of 40 students must be arranged into groups of", f"4 for group projects, there are {combinations(40, 4)} ways", "to arrange them.\n", ) print( "If 10 teams are competing in a Formula One race, there", f"are {combinations(10, 3)} ways that first, second and", "third place can be awarded.\n", )
""" https://en.wikipedia.org/wiki/Combination """ from math import factorial def combinations(n: int, k: int) -> int: """ Returns the number of different combinations of k length which can be made from n values, where n >= k. Examples: >>> combinations(10,5) 252 >>> combinations(6,3) 20 >>> combinations(20,5) 15504 >>> combinations(52, 5) 2598960 >>> combinations(0, 0) 1 >>> combinations(-4, -5) ... Traceback (most recent call last): ValueError: Please enter positive integers for n and k where n >= k """ # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k") return int(factorial(n) / ((factorial(k)) * (factorial(n - k)))) if __name__ == "__main__": print( "\nThe number of five-card hands possible from a standard", f"fifty-two card deck is: {combinations(52, 5)}", ) print( "\nIf a class of 40 students must be arranged into groups of", f"4 for group projects, there are {combinations(40, 4)} ways", "to arrange them.\n", ) print( "If 10 teams are competing in a Formula One race, there", f"are {combinations(10, 3)} ways that first, second and", "third place can be awarded.\n", )
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# Divide and Conquer algorithm def find_min(nums, left, right): """ find min value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: min in nums >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_min(nums, 0, len(nums) - 1) == min(nums) True """ if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_min = find_min(nums, left, mid) # find min in range[left, mid] right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right] return left_min if left_min <= right_min else right_min if __name__ == "__main__": nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] assert find_min(nums, 0, len(nums) - 1) == 1
# Divide and Conquer algorithm def find_min(nums, left, right): """ find min value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: min in nums >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_min(nums, 0, len(nums) - 1) == min(nums) True """ if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_min = find_min(nums, left, mid) # find min in range[left, mid] right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right] return left_min if left_min <= right_min else right_min if __name__ == "__main__": nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] assert find_min(nums, 0, len(nums) - 1) == 1
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 math class Graph: def __init__(self, N=0): # a graph with Node 0,1,...,N-1 self.N = N self.W = [ [math.inf for j in range(0, N)] for i in range(0, N) ] # adjacency matrix for weight self.dp = [ [math.inf for j in range(0, N)] for i in range(0, N) ] # dp[i][j] stores minimum distance from i to j def addEdge(self, u, v, w): self.dp[u][v] = w def floyd_warshall(self): for k in range(0, self.N): for i in range(0, self.N): for j in range(0, self.N): self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j]) def showMin(self, u, v): return self.dp[u][v] if __name__ == "__main__": graph = Graph(5) graph.addEdge(0, 2, 9) graph.addEdge(0, 4, 10) graph.addEdge(1, 3, 5) graph.addEdge(2, 3, 7) graph.addEdge(3, 0, 10) graph.addEdge(3, 1, 2) graph.addEdge(3, 2, 1) graph.addEdge(3, 4, 6) graph.addEdge(4, 1, 3) graph.addEdge(4, 2, 4) graph.addEdge(4, 3, 9) graph.floyd_warshall() graph.showMin(1, 4) graph.showMin(0, 3)
import math class Graph: def __init__(self, N=0): # a graph with Node 0,1,...,N-1 self.N = N self.W = [ [math.inf for j in range(0, N)] for i in range(0, N) ] # adjacency matrix for weight self.dp = [ [math.inf for j in range(0, N)] for i in range(0, N) ] # dp[i][j] stores minimum distance from i to j def addEdge(self, u, v, w): self.dp[u][v] = w def floyd_warshall(self): for k in range(0, self.N): for i in range(0, self.N): for j in range(0, self.N): self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j]) def showMin(self, u, v): return self.dp[u][v] if __name__ == "__main__": graph = Graph(5) graph.addEdge(0, 2, 9) graph.addEdge(0, 4, 10) graph.addEdge(1, 3, 5) graph.addEdge(2, 3, 7) graph.addEdge(3, 0, 10) graph.addEdge(3, 1, 2) graph.addEdge(3, 2, 1) graph.addEdge(3, 4, 6) graph.addEdge(4, 1, 3) graph.addEdge(4, 2, 4) graph.addEdge(4, 3, 9) graph.floyd_warshall() graph.showMin(1, 4) graph.showMin(0, 3)
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2 ,len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heap_sort(array) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(sort(unsorted))
""" Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2 ,len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heap_sort(array) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(sort(unsorted))
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 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("The value of log(log(n)) is {:.4f}".format(math.log(math.log(n)))) """ 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("The value of log(log(n)) is {:.4f}".format(math.log(math.log(n)))) """ The number of distinct prime factors is/are 3 The value of log(log(n)) is 2.8765 """
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass from typing import Optional test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next: Optional[Node] class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Optional[Node] = None for i in reversed(sorted(ints)): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass from typing import Optional test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next: Optional[Node] class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Optional[Node] = None for i in reversed(sorted(ints)): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ def isprime(number: int) -> bool: """ Determines whether the given number is prime or not >>> isprime(2) True >>> isprime(15) False >>> isprime(29) True """ for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. """ try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes = [] num = 2 while len(primes) < nth: if isprime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ def isprime(number: int) -> bool: """ Determines whether the given number is prime or not >>> isprime(2) True >>> isprime(15) False >>> isprime(29) True """ for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. """ try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes = [] num = 2 while len(primes) < nth: if isprime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" One of the several implementations of Lempel–Ziv–Welch decompression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def decompress_data(data_bits: str) -> str: """ Decompresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id lexicon[curr_string] = last_match_id + "0" if math.log2(index).is_integer(): newLex = {} for curr_key in list(lexicon): newLex["0" + curr_key] = lexicon.pop(curr_key) lexicon = newLex lexicon[bin(index)[2:]] = last_match_id + "1" index += 1 curr_string = "" return result def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def remove_prefix(data_bits: str) -> str: """ Removes size prefix, that compressed file should have Returns the result """ counter = 0 for letter in data_bits: if letter == "1": break counter += 1 data_bits = data_bits[counter:] data_bits = data_bits[counter + 1 :] return data_bits def compress(source_path: str, destination_path: str) -> None: """ Reads source file, decompresses it and writes the result in destination file """ data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) write_file_binary(destination_path, decompressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
""" One of the several implementations of Lempel–Ziv–Welch decompression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def decompress_data(data_bits: str) -> str: """ Decompresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id lexicon[curr_string] = last_match_id + "0" if math.log2(index).is_integer(): newLex = {} for curr_key in list(lexicon): newLex["0" + curr_key] = lexicon.pop(curr_key) lexicon = newLex lexicon[bin(index)[2:]] = last_match_id + "1" index += 1 curr_string = "" return result def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def remove_prefix(data_bits: str) -> str: """ Removes size prefix, that compressed file should have Returns the result """ counter = 0 for letter in data_bits: if letter == "1": break counter += 1 data_bits = data_bits[counter:] data_bits = data_bits[counter + 1 :] return data_bits def compress(source_path: str, destination_path: str) -> None: """ Reads source file, decompresses it and writes the result in destination file """ data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) write_file_binary(destination_path, decompressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 roman_to_int(roman: str) -> int: """ LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(roman_to_int(key) == value for key, value in tests.items()) True """ vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True """ ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] result = [] for (arabic, roman) in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
def roman_to_int(roman: str) -> int: """ LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(roman_to_int(key) == value for key, value in tests.items()) True """ vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True """ ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] result = [] for (arabic, roman) in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ fib = [0, 1] i = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1]) if fib[i + 2] > n: break i += 1 total = 0 for j in range(len(fib) - 1): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ fib = [0, 1] i = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1]) if fib[i + 2] > n: break i += 1 total = 0 for j in range(len(fib) - 1): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head = None self.size = 0 def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1 def remove(self) -> Any: if self.is_empty(): return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if not self.is_empty: return "" else: iterate = self.head item_str = "" item_list = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head = None self.size = 0 def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1 def remove(self) -> Any: if self.is_empty(): return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if not self.is_empty: return "" else: iterate = self.head item_str = "" item_list = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 script demonstrates the implementation of the ReLU function. It's a kind of activation function defined as the positive part of its argument in the context of neural network. The function takes a vector of K real numbers as input and then argmax(x, 0). After through ReLU, the element of the vector always 0 or real number. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Rectifier_(neural_networks) """ from __future__ import annotations import numpy as np def relu(vector: list[float]): """ Implements the relu function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: relu_vec (np.array): The input numpy array, after applying relu. >>> vec = np.array([-1, 0, 5]) >>> relu(vec) array([0, 0, 5]) """ # compare two arrays and then return element-wise maxima. return np.maximum(0, vector) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
""" This script demonstrates the implementation of the ReLU function. It's a kind of activation function defined as the positive part of its argument in the context of neural network. The function takes a vector of K real numbers as input and then argmax(x, 0). After through ReLU, the element of the vector always 0 or real number. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Rectifier_(neural_networks) """ from __future__ import annotations import numpy as np def relu(vector: list[float]): """ Implements the relu function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: relu_vec (np.array): The input numpy array, after applying relu. >>> vec = np.array([-1, 0, 5]) >>> relu(vec) array([0, 0, 5]) """ # compare two arrays and then return element-wise maxima. return np.maximum(0, vector) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 a Binary Number.""" def decimal_to_binary(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if type(num) == float: raise TypeError("'float' object cannot be interpreted as an integer") if type(num) == str: raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) if __name__ == "__main__": import doctest doctest.testmod()
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if type(num) == float: raise TypeError("'float' object cannot be interpreted as an integer") if type(num) == str: raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 typing import List class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: string_rep.append(f"{temp.data}") temp = temp.next return "->".join(string_rep) def make_linked_list(elements_list: List): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List. >>> make_linked_list([]) Traceback (most recent call last): ... Exception: The Elements List is empty >>> make_linked_list([7]) 7 >>> make_linked_list(['abc']) abc >>> make_linked_list([7, 25]) 7->25 """ if not elements_list: raise Exception("The Elements List is empty") current = head = Node(elements_list[0]) for i in range(1, len(elements_list)): current.next = Node(elements_list[i]) current = current.next return head def print_reverse(head_node: Node) -> None: """Prints the elements of the given Linked List in reverse order >>> print_reverse([]) >>> linked_list = make_linked_list([69, 88, 73]) >>> print_reverse(linked_list) 73 88 69 """ if head_node is not None and isinstance(head_node, Node): print_reverse(head_node.next) print(head_node.data) def main(): from doctest import testmod testmod() linked_list = make_linked_list([14, 52, 14, 12, 43]) print("Linked List:") print(linked_list) print("Elements in Reverse:") print_reverse(linked_list) if __name__ == "__main__": main()
from typing import List class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: string_rep.append(f"{temp.data}") temp = temp.next return "->".join(string_rep) def make_linked_list(elements_list: List): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List. >>> make_linked_list([]) Traceback (most recent call last): ... Exception: The Elements List is empty >>> make_linked_list([7]) 7 >>> make_linked_list(['abc']) abc >>> make_linked_list([7, 25]) 7->25 """ if not elements_list: raise Exception("The Elements List is empty") current = head = Node(elements_list[0]) for i in range(1, len(elements_list)): current.next = Node(elements_list[i]) current = current.next return head def print_reverse(head_node: Node) -> None: """Prints the elements of the given Linked List in reverse order >>> print_reverse([]) >>> linked_list = make_linked_list([69, 88, 73]) >>> print_reverse(linked_list) 73 88 69 """ if head_node is not None and isinstance(head_node, Node): print_reverse(head_node.next) print(head_node.data) def main(): from doctest import testmod testmod() linked_list = make_linked_list([14, 52, 14, 12, 43]) print("Linked List:") print(linked_list) print("Elements in Reverse:") print_reverse(linked_list) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 math def perfect_square(num: int) -> bool: """ Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False >>> perfect_square(9) True >>> perfect_square(16) True >>> perfect_square(1) True >>> perfect_square(0) True >>> perfect_square(10) False """ return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: """ Check if a number is perfect square using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_square_binary_search(9) True >>> perfect_square_binary_search(16) True >>> perfect_square_binary_search(1) True >>> perfect_square_binary_search(0) True >>> perfect_square_binary_search(10) False >>> perfect_square_binary_search(-1) False >>> perfect_square_binary_search(1.1) False >>> perfect_square_binary_search("a") Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> perfect_square_binary_search(None) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'NoneType' >>> perfect_square_binary_search([]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ left = 0 right = n while left <= right: mid = (left + right) // 2 if mid ** 2 == n: return True elif mid ** 2 > n: right = mid - 1 else: left = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
import math def perfect_square(num: int) -> bool: """ Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False >>> perfect_square(9) True >>> perfect_square(16) True >>> perfect_square(1) True >>> perfect_square(0) True >>> perfect_square(10) False """ return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: """ Check if a number is perfect square using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_square_binary_search(9) True >>> perfect_square_binary_search(16) True >>> perfect_square_binary_search(1) True >>> perfect_square_binary_search(0) True >>> perfect_square_binary_search(10) False >>> perfect_square_binary_search(-1) False >>> perfect_square_binary_search(1.1) False >>> perfect_square_binary_search("a") Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> perfect_square_binary_search(None) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'NoneType' >>> perfect_square_binary_search([]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ left = 0 right = n while left <= right: mid = (left + right) // 2 if mid ** 2 == n: return True elif mid ** 2 > n: right = mid - 1 else: left = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# flake8: noqa """ Sieve of Eratosthenes Input : n =10 Output: 2 3 5 7 Input : n = 20 Output: 2 3 5 7 11 13 17 19 you can read in detail about this at https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def prime_sieve_eratosthenes(num): """ print the prime numbers up to n >>> prime_sieve_eratosthenes(10) 2,3,5,7, >>> prime_sieve_eratosthenes(20) 2,3,5,7,11,13,17,19, """ primes = [True for i in range(num + 1)] p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 for prime in range(2, num + 1): if primes[prime]: print(prime, end=",") if __name__ == "__main__": import doctest doctest.testmod() num = int(input()) prime_sieve_eratosthenes(num)
# flake8: noqa """ Sieve of Eratosthenes Input : n =10 Output: 2 3 5 7 Input : n = 20 Output: 2 3 5 7 11 13 17 19 you can read in detail about this at https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def prime_sieve_eratosthenes(num): """ print the prime numbers up to n >>> prime_sieve_eratosthenes(10) 2,3,5,7, >>> prime_sieve_eratosthenes(20) 2,3,5,7,11,13,17,19, """ primes = [True for i in range(num + 1)] p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 for prime in range(2, num + 1): if primes[prime]: print(prime, end=",") if __name__ == "__main__": import doctest doctest.testmod() num = int(input()) prime_sieve_eratosthenes(num)
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 85: https://projecteuler.net/problem=85 By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles.  Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution. Solution: For a grid with side-lengths a and b, the number of rectangles contained in the grid is [a*(a+1)/2] * [b*(b+1)/2)], which happens to be the product of the a-th and b-th triangle numbers. So to find the solution grid (a,b), we need to find the two triangle numbers whose product is closest to two million. Denote these two triangle numbers Ta and Tb. We want their product Ta*Tb to be as close as possible to 2m. Assuming that the best solution is fairly close to 2m, We can assume that both Ta and Tb are roughly bounded by 2m. Since Ta = a(a+1)/2, we can assume that a (and similarly b) are roughly bounded by sqrt(2 * 2m) = 2000. Since this is a rough bound, to be on the safe side we add 10%. Therefore we start by generating all the triangle numbers Ta for 1 <= a <= 2200. This can be done iteratively since the ith triangle number is the sum of 1,2, ... ,i, and so T(i) = T(i-1) + i. We then search this list of triangle numbers for the two that give a product closest to our target of two million. Rather than testing every combination of 2 elements of the list, which would find the result in quadratic time, we can find the best pair in linear time. We iterate through the list of triangle numbers using enumerate() so we have a and Ta. Since we want Ta * Tb to be as close as possible to 2m, we know that Tb needs to be roughly 2m / Ta. Using the formula Tb = b*(b+1)/2 as well as the quadratic formula, we can solve for b: b is roughly (-1 + sqrt(1 + 8 * 2m / Ta)) / 2. Since the closest integers to this estimate will give product closest to 2m, we only need to consider the integers above and below. It's then a simple matter to get the triangle numbers corresponding to those integers, calculate the product Ta * Tb, compare that product to our target 2m, and keep track of the (a,b) pair that comes the closest. Reference: https://en.wikipedia.org/wiki/Triangular_number https://en.wikipedia.org/wiki/Quadratic_formula """ from math import ceil, floor, sqrt from typing import List def solution(target: int = 2000000) -> int: """ Find the area of the grid which contains as close to two million rectangles as possible. >>> solution(20) 6 >>> solution(2000) 72 >>> solution(2000000000) 86595 """ triangle_numbers: List[int] = [0] idx: int for idx in range(1, ceil(sqrt(target * 2) * 1.1)): triangle_numbers.append(triangle_numbers[-1] + idx) # we want this to be as close as possible to target best_product: int = 0 # the area corresponding to the grid that gives the product closest to target area: int = 0 # an estimate of b, using the quadratic formula b_estimate: float # the largest integer less than b_estimate b_floor: int # the largest integer less than b_estimate b_ceil: int # the triangle number corresponding to b_floor triangle_b_first_guess: int # the triangle number corresponding to b_ceil triangle_b_second_guess: int for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1): b_estimate = (-1 + sqrt(1 + 8 * target / triangle_a)) / 2 b_floor = floor(b_estimate) b_ceil = ceil(b_estimate) triangle_b_first_guess = triangle_numbers[b_floor] triangle_b_second_guess = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_first_guess * triangle_a area = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_second_guess * triangle_a area = idx_a * b_ceil return area if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 85: https://projecteuler.net/problem=85 By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles.  Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution. Solution: For a grid with side-lengths a and b, the number of rectangles contained in the grid is [a*(a+1)/2] * [b*(b+1)/2)], which happens to be the product of the a-th and b-th triangle numbers. So to find the solution grid (a,b), we need to find the two triangle numbers whose product is closest to two million. Denote these two triangle numbers Ta and Tb. We want their product Ta*Tb to be as close as possible to 2m. Assuming that the best solution is fairly close to 2m, We can assume that both Ta and Tb are roughly bounded by 2m. Since Ta = a(a+1)/2, we can assume that a (and similarly b) are roughly bounded by sqrt(2 * 2m) = 2000. Since this is a rough bound, to be on the safe side we add 10%. Therefore we start by generating all the triangle numbers Ta for 1 <= a <= 2200. This can be done iteratively since the ith triangle number is the sum of 1,2, ... ,i, and so T(i) = T(i-1) + i. We then search this list of triangle numbers for the two that give a product closest to our target of two million. Rather than testing every combination of 2 elements of the list, which would find the result in quadratic time, we can find the best pair in linear time. We iterate through the list of triangle numbers using enumerate() so we have a and Ta. Since we want Ta * Tb to be as close as possible to 2m, we know that Tb needs to be roughly 2m / Ta. Using the formula Tb = b*(b+1)/2 as well as the quadratic formula, we can solve for b: b is roughly (-1 + sqrt(1 + 8 * 2m / Ta)) / 2. Since the closest integers to this estimate will give product closest to 2m, we only need to consider the integers above and below. It's then a simple matter to get the triangle numbers corresponding to those integers, calculate the product Ta * Tb, compare that product to our target 2m, and keep track of the (a,b) pair that comes the closest. Reference: https://en.wikipedia.org/wiki/Triangular_number https://en.wikipedia.org/wiki/Quadratic_formula """ from math import ceil, floor, sqrt from typing import List def solution(target: int = 2000000) -> int: """ Find the area of the grid which contains as close to two million rectangles as possible. >>> solution(20) 6 >>> solution(2000) 72 >>> solution(2000000000) 86595 """ triangle_numbers: List[int] = [0] idx: int for idx in range(1, ceil(sqrt(target * 2) * 1.1)): triangle_numbers.append(triangle_numbers[-1] + idx) # we want this to be as close as possible to target best_product: int = 0 # the area corresponding to the grid that gives the product closest to target area: int = 0 # an estimate of b, using the quadratic formula b_estimate: float # the largest integer less than b_estimate b_floor: int # the largest integer less than b_estimate b_ceil: int # the triangle number corresponding to b_floor triangle_b_first_guess: int # the triangle number corresponding to b_ceil triangle_b_second_guess: int for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1): b_estimate = (-1 + sqrt(1 + 8 * target / triangle_a)) / 2 b_floor = floor(b_estimate) b_ceil = ceil(b_estimate) triangle_b_first_guess = triangle_numbers[b_floor] triangle_b_second_guess = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_first_guess * triangle_a area = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_second_guess * triangle_a area = idx_a * b_ceil return area if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return f"Node({self.data})" class LinkedList: def __init__(self): self.head = None def __iter__(self): node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("head") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self): """ String representation/visualization of a Linked Lists """ return "->".join([str(item) for item in self]) def __getitem__(self, index): """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node # Used to change the data of a particular node def __setitem__(self, index, data): """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for i in range(index): current = current.next current.data = data def insert_tail(self, data) -> None: self.insert_nth(len(self), data) def insert_head(self, data) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data print(self) def delete_head(self): return self.delete_nth(0) def delete_tail(self): # delete from tail return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0): if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("list index out of range") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: return self.head is None def reverse(self): prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() assert False # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() assert False # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return f"Node({self.data})" class LinkedList: def __init__(self): self.head = None def __iter__(self): node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("head") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self): """ String representation/visualization of a Linked Lists """ return "->".join([str(item) for item in self]) def __getitem__(self, index): """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node # Used to change the data of a particular node def __setitem__(self, index, data): """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for i in range(index): current = current.next current.data = data def insert_tail(self, data) -> None: self.insert_nth(len(self), data) def insert_head(self, data) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data print(self) def delete_head(self): return self.delete_nth(0) def delete_tail(self): # delete from tail return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0): if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("list index out of range") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: return self.head is None def reverse(self): prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() assert False # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() assert False # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001/010/100/000/101 b source: http://www.cse.yorku.ca/~oz/hash.html """ def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash = 5381 for x in s: hash = ((hash << 5) + hash) + ord(x) return hash & 0xFFFFFFFF
""" This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001/010/100/000/101 b source: http://www.cse.yorku.ca/~oz/hash.html """ def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash = 5381 for x in s: hash = ((hash << 5) + hash) + ord(x) return hash & 0xFFFFFFFF
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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. """ 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 = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 return int(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. """ 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 = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# An island in matrix is a group of linked areas, all having the same value. # This code counts number of islands in a given matrix, with including diagonal # connections. class matrix: # Public class to implement a graph def __init__(self, row: int, col: int, graph: list): self.ROW = row self.COL = col self.graph = graph def is_safe(self, i, j, visited) -> bool: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def diffs(self, i, j, visited): # Checking all 8 elements surrounding nth element rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] visited[i][j] = True # Make those cells visited for k in range(8): if self.is_safe(i + rowNbr[k], j + colNbr[k], visited): self.diffs(i + rowNbr[k], j + colNbr[k], visited) def count_islands(self) -> int: # And finally, count all islands. visited = [[False for j in range(self.COL)] for i in range(self.ROW)] count = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(i, j, visited) count += 1 return count
# An island in matrix is a group of linked areas, all having the same value. # This code counts number of islands in a given matrix, with including diagonal # connections. class matrix: # Public class to implement a graph def __init__(self, row: int, col: int, graph: list): self.ROW = row self.COL = col self.graph = graph def is_safe(self, i, j, visited) -> bool: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def diffs(self, i, j, visited): # Checking all 8 elements surrounding nth element rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] visited[i][j] = True # Make those cells visited for k in range(8): if self.is_safe(i + rowNbr[k], j + colNbr[k], visited): self.diffs(i + rowNbr[k], j + colNbr[k], visited) def count_islands(self) -> int: # And finally, count all islands. visited = [[False for j in range(self.COL)] for i in range(self.ROW)] count = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(i, j, visited) count += 1 return count
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Similarity Search : https://en.wikipedia.org/wiki/Similarity_search Similarity search is a search algorithm for finding the nearest vector from vectors, used in natural language processing. In this algorithm, it calculates distance with euclidean distance and returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector (float) """ import math from typing import List, Union import numpy as np def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates euclidean distance between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Euclidean distance of input_a and input_b. By using math.sqrt(), result will be float. >>> euclidean(np.array([0]), np.array([1])) 1.0 >>> euclidean(np.array([0, 1]), np.array([1, 1])) 1.0 >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) 1.0 """ return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> List[List[Union[List[float], float]]]: """ :param dataset: Set containing the vectors. Should be ndarray. :param value_array: vector/vectors we want to know the nearest vector from dataset. :return: Result will be a list containing 1. the nearest vector 2. distance from the vector >>> dataset = np.array([[0], [1], [2]]) >>> value_array = np.array([[0]]) >>> similarity_search(dataset, value_array) [[[0], 0.0]] >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] These are the errors that might occur: 1. If dimensions are different. For example, dataset has 2d array and value_array has 1d array: >>> dataset = np.array([[1]]) >>> value_array = np.array([1]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 2. If data's shapes are different. For example, dataset has shape of (3, 2) and value_array has (2, 3). We are expecting same shapes of two arrays, so it is wrong. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's shape... dataset : 2, value_array : 3 3. If data types are different. When trying to compare, we are expecting same types so they should be same. If not, it'll come up with errors. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: Input data have different datatype... dataset : float32, value_array : int32 """ if dataset.ndim != value_array.ndim: raise ValueError( f"Wrong input data's dimensions... dataset : {dataset.ndim}, " f"value_array : {value_array.ndim}" ) try: if dataset.shape[1] != value_array.shape[1]: raise ValueError( f"Wrong input data's shape... dataset : {dataset.shape[1]}, " f"value_array : {value_array.shape[1]}" ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: raise TypeError( f"Input data have different datatype... dataset : {dataset.dtype}, " f"value_array : {value_array.dtype}" ) answer = [] for value in value_array: dist = euclidean(value, dataset[0]) vector = dataset[0].tolist() for dataset_value in dataset[1:]: temp_dist = euclidean(value, dataset_value) if dist > temp_dist: dist = temp_dist vector = dataset_value.tolist() answer.append([vector, dist]) return answer if __name__ == "__main__": import doctest doctest.testmod()
""" Similarity Search : https://en.wikipedia.org/wiki/Similarity_search Similarity search is a search algorithm for finding the nearest vector from vectors, used in natural language processing. In this algorithm, it calculates distance with euclidean distance and returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector (float) """ import math from typing import List, Union import numpy as np def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates euclidean distance between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Euclidean distance of input_a and input_b. By using math.sqrt(), result will be float. >>> euclidean(np.array([0]), np.array([1])) 1.0 >>> euclidean(np.array([0, 1]), np.array([1, 1])) 1.0 >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) 1.0 """ return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> List[List[Union[List[float], float]]]: """ :param dataset: Set containing the vectors. Should be ndarray. :param value_array: vector/vectors we want to know the nearest vector from dataset. :return: Result will be a list containing 1. the nearest vector 2. distance from the vector >>> dataset = np.array([[0], [1], [2]]) >>> value_array = np.array([[0]]) >>> similarity_search(dataset, value_array) [[[0], 0.0]] >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] These are the errors that might occur: 1. If dimensions are different. For example, dataset has 2d array and value_array has 1d array: >>> dataset = np.array([[1]]) >>> value_array = np.array([1]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 2. If data's shapes are different. For example, dataset has shape of (3, 2) and value_array has (2, 3). We are expecting same shapes of two arrays, so it is wrong. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's shape... dataset : 2, value_array : 3 3. If data types are different. When trying to compare, we are expecting same types so they should be same. If not, it'll come up with errors. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: Input data have different datatype... dataset : float32, value_array : int32 """ if dataset.ndim != value_array.ndim: raise ValueError( f"Wrong input data's dimensions... dataset : {dataset.ndim}, " f"value_array : {value_array.ndim}" ) try: if dataset.shape[1] != value_array.shape[1]: raise ValueError( f"Wrong input data's shape... dataset : {dataset.shape[1]}, " f"value_array : {value_array.shape[1]}" ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: raise TypeError( f"Input data have different datatype... dataset : {dataset.dtype}, " f"value_array : {value_array.dtype}" ) answer = [] for value in value_array: dist = euclidean(value, dataset[0]) vector = dataset[0].tolist() for dataset_value in dataset[1:]: temp_dist = euclidean(value, dataset_value) if dist > temp_dist: dist = temp_dist vector = dataset_value.tolist() answer.append([vector, dist]) return answer if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
""" Find Volumes of Various Shapes. Wikipedia reference: https://en.wikipedia.org/wiki/Volume """ from math import pi, pow from typing import Union def vol_cube(side_length: Union[int, float]) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 """ return pow(side_length, 3) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 """ return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 """ return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * pi * radius^2 * height >>> vol_right_circ_cone(2, 3) 12.566370614359172 """ return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Prism. Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return V = Bh >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 """ return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: """ Calculate the Volume of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return (4/3) * pi * r^3 >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 """ return 4 / 3 * pi * pow(radius, 3) def vol_circular_cylinder(radius: float, height: float) -> float: """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return pi * radius^2 * height >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 """ return pi * pow(radius, 2) * height def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print("Cube: " + str(vol_cube(2))) # = 8 print("Cuboid: " + str(vol_cuboid(2, 2, 2))) # = 8 print("Cone: " + str(vol_cone(2, 2))) # ~= 1.33 print("Right Circular Cone: " + str(vol_right_circ_cone(2, 2))) # ~= 8.38 print("Prism: " + str(vol_prism(2, 2))) # = 4 print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33 print("Sphere: " + str(vol_sphere(2))) # ~= 33.5 print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1 if __name__ == "__main__": main()
""" Find Volumes of Various Shapes. Wikipedia reference: https://en.wikipedia.org/wiki/Volume """ from math import pi, pow from typing import Union def vol_cube(side_length: Union[int, float]) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 """ return pow(side_length, 3) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 """ return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 """ return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * pi * radius^2 * height >>> vol_right_circ_cone(2, 3) 12.566370614359172 """ return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Prism. Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return V = Bh >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 """ return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: """ Calculate the Volume of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return (4/3) * pi * r^3 >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 """ return 4 / 3 * pi * pow(radius, 3) def vol_circular_cylinder(radius: float, height: float) -> float: """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return pi * radius^2 * height >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 """ return pi * pow(radius, 2) * height def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print("Cube: " + str(vol_cube(2))) # = 8 print("Cuboid: " + str(vol_cuboid(2, 2, 2))) # = 8 print("Cone: " + str(vol_cone(2, 2))) # ~= 1.33 print("Right Circular Cone: " + str(vol_right_circ_cone(2, 2))) # ~= 8.38 print("Prism: " + str(vol_prism(2, 2))) # = 4 print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33 print("Sphere: " + str(vol_sphere(2))) # ~= 33.5 print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1 if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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://www.geeksforgeeks.org/newton-forward-backward-interpolation/ import math from typing import List # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() -> None: n = int(input("enter the numbers of values: ")) y: List[List[float]] = [] for i in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print("enter the values of parameters in a list: ") x = list(map(int, input().split())) print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) print(f"the value at {value} is {summ}") if __name__ == "__main__": main()
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ import math from typing import List # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() -> None: n = int(input("enter the numbers of values: ")) y: List[List[float]] = [] for i in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print("enter the values of parameters in a list: ") x = list(map(int, input().split())) print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) print(f"the value at {value} is {summ}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
-1
TheAlgorithms/Python
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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
4,292
[mypy] fix small folders
### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
algobytewise
"2021-03-23T07:05:28Z"
"2021-03-23T15:51:50Z"
a8db5d4b93410d8ad3c281d1edd9ce26c6e087e0
959507901ac8f10cd605c51c305d13b27d105536
[mypy] fix small folders. ### **Describe your change:** Related Issue: #4052 comment for strassen_matrix_multiplication.py: I couldn't use Tuple as return type since one branch of the function returns a tuple an another a list/matrix. So I turned the tuple into a list instead. comment for electric_power.py & ohms_law.py: I added a final else-clause for raising an error to make sure that each branch either has a return-value or throws an error * [ ] 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. * [ ] 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. * [x] 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}`.
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( ("1" + "0" * (binary_number_length - len(binary_number)) + binary_number) if number < 0 else "0" ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( ("1" + "0" * (binary_number_length - len(binary_number)) + binary_number) if number < 0 else "0" ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
-1