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*unS6mUoxBISA$=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`:X2pQSLPRaeyqĘ
י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`ffsKpY qx(@ pHYs
B(x diTXtXML: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,\.mJ9S?m6jEObiʏ[AC bt wbQ\7~/Xƀ veKiT;⹆=aIsyF]@nqV-rq + E DDRR}ލa7azຠ("Pϭ^>{kz5Ԣn8W(mz4
F#('>K[hw8
qQ(Cez(0!8;g}7iu>0Y3
@'`ii]k.f
F CD܈{"'UJNAe<\qPeqj ʝL}vÇ֟tqdFk6wk+r#*xuBzc--;obʝ͍fYdn!9:sbABk6Vf7>Kv ]v5]?I{tҊF0do#Ii_Z1ÆLyH6V}%slE(u <{ c>M}k<Cl>xcp K>
*WǢm֯$wee\=dNfPU9zIzJ%b2κhG!Q^ܳ>A״vj,s'7bn)c}
X".j>@;^<ƉFg8YecsbeH8_` YY!{_?ߝ3uπT|Y-oexI}UP
t.S,2_)? bQ8ZAjsڷ?|ퟩvc,;8]އ O.@vE8#qva3vX{+w@Ddᇩyq9柼jΎ|plU@C@J~Y7^*"2=]M]~e X QZd+f^ː\8]9T`rf u=[:Y1a8"Xւ
h?OP5Toۀ{,["v
ZAKmHhMKQj^j8>M]*I!5
UPؚT>;`WXEz>N厬˻!F@ֵ1Nҳ$LR]
Q
q,GX[FKl xmrX+|Z7Zc< +M[lcҎ{rBz,V9=P3^d;-ˁ'!:-vl\ia~5L:B
A/S6v|^F(QV--MKnI|Q^ua9_YzVq"w.Ʈ( VoZ3ލ7h,?842L2ɢčkl5(zwZnA*>.̦Z;us,gQdW94EOIШAm
==fΣYv'NF4T7kX .OD|AZYrj 65Y07||o}wq~@3U28V E`@WV˭[y4
QQz \A8*kj,#cp2]As<'J/iD)`3RkVqYRbrpQI^zR[%n%1--X勞(lKD~x_?qR_i7ƥ
(@a 2UBP1~tg{7G">NgWUe~(6aur8Z$N|U(S0jToﺿ_8= !"d9%66i
FLڸC)
*9٭K"v>|kN<2TaFPq@" W<([*Aż=`!-&Q۾NsNw5F$hIT2I._ϗ\`C~rܷ~[oOsVQ *\&^㔂 O<\۾خUJb l(wڵ^cLcSˣ~vלGr@'Dg,Q!%(~NK9 7mgٚ[Y؈7;@aZsbDC{p<rPk
lLz6]U__ط&j0cZOZk.nf^q?rvm2";W"| bW@xi &q_!%;ۄF47ݗG24{@}oq>Nvt't Q@j$QsnT5!}Brq/7uqdZ WPኑQ!Yx5 .Ӧ?j.a АѥMuLk++'kn,P!X9.7o8 bߊCey|W*o,&kH$QeOv6)vb)N~cӾL΄̖އ}`.w=᪅d
8atfceW<wY?/:;r)b6Ca8uQQ'+Te` $WTǧ\<3kڨiytūg>NJE[p?=!!AKo |r
bNbpZnpjzځ&\*qiBd{7eec7,] ~ص[znXd\BR:
5*qOF %74U!Ǐ~ubl
AhX=0v~~n("*l:Ck3KBKVG0*T{ZnzlEh~yDW%dX%fNābPbveq<JqW-jm.%і+*Re hY`YfV%M2uV"[tXln#"\\Ub7g]mi
#潊e8@tS_8tlX4a4>Jnʫq(+@Abjqt;oqɬh D%qVqZCn\4 ,bvU.9d,TjksUqnS4^.9rHs+jE.|;SQ :"^("o8~emY,k&L[j']U\&[hti[*T{e\p$0ׂ'8VV&G#[,=;y7n2aw+~fU`.QdAd^Agp2B5vVʿ=0QQz8V4[}>3s'fp Ǒ*%2y
>Sd.XU0@D!89ZfCHފf[)S{Z
`
|8N<EHR+e>h*fxU]w|-}76&QX^*f+a,V[։96ipqU /ˇ3K~G/-8,%cxl_蛪5D:c3dڲ_eX@[T6/5ю} %<{NṪutŨq;=V
jX= xrjׁ8[@h0Eڕt8grGUlSSSZ@JxE&id97-L'A6Q,RC hDT+k4r!zDF[L<pJ9EgM$XnzV~ue+e)ru8m@,ry>Ad]ShR.a/Dlsp
s%mbƏZGs[ 0B^(__Yyi֦A-|tavJn/v}ݙ 7Ly:fj<Yb\8rUfԣJ+K>D")"%Ԇpm}/|wwx'ojj%t8 ߸<gE[V)nVs~X)#< (cJø2\/jV4b,Pc
"jHba`Gw"#ЍІ<p:7(n66|_[l+Q|>SkB av@s+jiQ]Bw!/pq+jacXv&ZkSwSzdwqDDj˂ib:$9I0*^ܚ90Eڴ5:zu*wb
Mr!+.:o}9f)G2et5Nf2PzȄD6Fc\nkSEaDWWym# \xeSt?eK"`2GLo\\~Q AQdl+8Q9w$Ve:("H:A_Ii ܬ,\Gl5u~J:ݮ%Y]lRYe KDd23P۞A-C5+r csY$XΕgDD"c#]='Fi^Bx~0P
Lm"lkZZ|'*B"ȩ'_4Lorc&ŎpS+Bc3cL[EOcֳmw;k"㋵UE~(<<<udX$f++@%kF!69O
.XK(nX6X!rfl'¢,B>[D?$7.' >]ZͻQ\%/i Tф.7K](kacy/_bG6K{Yv](^z檱IIa\Jv~"S"<"71<>tc;p
;w?~.\XkctrJ?RX>
-*bu<#ZEݙ0KX*3h:a|eJ# 1-b@!Q,X/&1#Nb">g絿Yr9W\t;|3(TQW*],+̳ <c-wuwW~3H@O1`Fꮘsa"b}yZVHKY~R)uNJ>ZDB=_R%8=mbmZ1ƸLq:{7bn[=]v:UIJE2J
XS%1h~}VW]\r>k!?.s\%ZGdj!X~>|֕+O܆瀬$u%1eSuW~GQ
][S\ۏkEŧw`dή]63gΜk<8 VR_O'MH$(ĪDĆa 9ޝR3^ڶ?H?Au|ɡxI2sc$>³*V2l-= o E'oy>b7W}"|v]Coj3jB3ARH lkU 6W
Ho/P!BQ>6gΜf2wXk֊c3cBʊLC&Sšfb0=vpP} !ok[X˒UaChl1⑂NUJ0ua-HwŃMJ;^o A8$Ao! )`
wi6)78P
RӽGyӔ1!R+Qw/m,JPJ8.u]d2U"gO8MBB^Ǣ2,&<߇hBU5 tU|9S\ccS%<`O*fnB٥֬}sovvX(KRc݈G QUG 8JD~y&NlDą~5?a1cZ&"'#l<i?]wE_l)sXJRތ)I㲵̉8KYY*|/+o/Əgj$ѕ>ꅞ(V`F!0Wn%`w1y; QooQl6%<F&HpcHR
k㠊xXcr
YY=_c=Ue1K|!J\lxY ,0Deug<GO!zy^xS__oUS/S"XǏ3yX S GO&6,.q;VD3eD6\ ڵkoyw*8IxKǓĤ8N<XZ{$kceU,cFX |B]ԸH0yNm߿n).kTWWH-:5D&?t-
nE:w?=8D`rKm$7Tՠ0#U8K#jBzcVrJ6=1Cx)ʉ/}>U%SJZkB T3SrwWdKJIaC;
NvEf3ΝQs#Ss$;I$n822ҦFG
hncxjc<=ܻOl{Ac6 hyº
<]ɽ_
ZZZҥK
@__ߵUU_QZG㸃UX|{QEa!A>~c|ac׃Q|ǘl`IB,1D7δ#m֭DzP%q;1vu九xpYawlӳJՏ)ڂnՔW
M~&uWrFu"HSiFaLzAP~D臬2\7
]pXtpg9fڹ4Ny`Ti414!J"1!FQDwͻ7?uܺO409[I8gjw)*7Ɛ֭;CQ]]}NEZ)ҫc,I/%|ߧ}CozVdưkYK$&oq=._@:$=<C&Ơct</|fb7xgCh2nK_>bWZUT|zc
cʔ)y9 "g90P%
+[r9$$2Y6L/H"c9qqUX>/
%
"bsli,veO{zn+.`Bzcm'~<(
R^ZҸop覴*=ʴ;`3^JxN..L?*<1E^Pu#!AXфaHd"\7C1SOs?6moڹj*we}cP1oJ{Y]]Rc
X픅^Ks*)u7'Zc`1qE",k:L'(DpqkNX=c4JsDadA|H[{۪g6>s%oQ@ZZZ$
L< |