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 | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/Breadth-first_search
pseudo-code:
breadth_first_search(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
while Q is non-empty:
remove the first node of Q, call it v
for each edge(v, w): // for w in graph[v]
if w unexplored:
mark w as explored
add w to Q (at the end)
"""
from __future__ import annotations
from collections import deque
from queue import Queue
from timeit import timeit
G = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
def breadth_first_search(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using queue.Queue.
>>> ''.join(breadth_first_search(G, 'A'))
'ABCDEF'
"""
explored = {start}
result = [start]
queue: Queue = Queue()
queue.put(start)
while not queue.empty():
v = queue.get()
for w in graph[v]:
if w not in explored:
explored.add(w)
result.append(w)
queue.put(w)
return result
def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using collection.queue.
>>> ''.join(breadth_first_search_with_deque(G, 'A'))
'ABCDEF'
"""
visited = {start}
result = [start]
queue = deque([start])
while queue:
v = queue.popleft()
for child in graph[v]:
if child not in visited:
visited.add(child)
result.append(child)
queue.append(child)
return result
def benchmark_function(name: str) -> None:
setup = f"from __main__ import G, {name}"
number = 10000
res = timeit(f"{name}(G, 'A')", setup=setup, number=number)
print(f"{name:<35} finished {number} runs in {res:.5f} seconds")
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark_function("breadth_first_search")
benchmark_function("breadth_first_search_with_deque")
# breadth_first_search finished 10000 runs in 0.20999 seconds
# breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds
| """
https://en.wikipedia.org/wiki/Breadth-first_search
pseudo-code:
breadth_first_search(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
while Q is non-empty:
remove the first node of Q, call it v
for each edge(v, w): // for w in graph[v]
if w unexplored:
mark w as explored
add w to Q (at the end)
"""
from __future__ import annotations
from collections import deque
from queue import Queue
from timeit import timeit
G = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
def breadth_first_search(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using queue.Queue.
>>> ''.join(breadth_first_search(G, 'A'))
'ABCDEF'
"""
explored = {start}
result = [start]
queue: Queue = Queue()
queue.put(start)
while not queue.empty():
v = queue.get()
for w in graph[v]:
if w not in explored:
explored.add(w)
result.append(w)
queue.put(w)
return result
def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using collection.queue.
>>> ''.join(breadth_first_search_with_deque(G, 'A'))
'ABCDEF'
"""
visited = {start}
result = [start]
queue = deque([start])
while queue:
v = queue.popleft()
for child in graph[v]:
if child not in visited:
visited.add(child)
result.append(child)
queue.append(child)
return result
def benchmark_function(name: str) -> None:
setup = f"from __main__ import G, {name}"
number = 10000
res = timeit(f"{name}(G, 'A')", setup=setup, number=number)
print(f"{name:<35} finished {number} runs in {res:.5f} seconds")
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark_function("breadth_first_search")
benchmark_function("breadth_first_search_with_deque")
# breadth_first_search finished 10000 runs in 0.20999 seconds
# breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
# Divide and Conquer algorithm
def find_min(nums: list[int | float], left: int, right: int) -> int | float:
"""
find min value in list
:param nums: contains elements
:param left: index of first element
:param right: index of last element
:return: min in nums
>>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
... find_min(nums, 0, len(nums) - 1) == min(nums)
True
True
True
True
>>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> find_min(nums, 0, len(nums) - 1) == min(nums)
True
>>> find_min([], 0, 0)
Traceback (most recent call last):
...
ValueError: find_min() arg is an empty sequence
>>> find_min(nums, 0, len(nums)) == min(nums)
Traceback (most recent call last):
...
IndexError: list index out of range
>>> find_min(nums, -len(nums), -1) == min(nums)
True
>>> find_min(nums, -len(nums) - 1, -1) == min(nums)
Traceback (most recent call last):
...
IndexError: list index out of range
"""
if len(nums) == 0:
raise ValueError("find_min() arg is an empty sequence")
if (
left >= len(nums)
or left < -len(nums)
or right >= len(nums)
or right < -len(nums)
):
raise IndexError("list index out of range")
if left == right:
return nums[left]
mid = (left + right) >> 1 # the middle
left_min = find_min(nums, left, mid) # find min in range[left, mid]
right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right]
return left_min if left_min <= right_min else right_min
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| from __future__ import annotations
# Divide and Conquer algorithm
def find_min(nums: list[int | float], left: int, right: int) -> int | float:
"""
find min value in list
:param nums: contains elements
:param left: index of first element
:param right: index of last element
:return: min in nums
>>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
... find_min(nums, 0, len(nums) - 1) == min(nums)
True
True
True
True
>>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> find_min(nums, 0, len(nums) - 1) == min(nums)
True
>>> find_min([], 0, 0)
Traceback (most recent call last):
...
ValueError: find_min() arg is an empty sequence
>>> find_min(nums, 0, len(nums)) == min(nums)
Traceback (most recent call last):
...
IndexError: list index out of range
>>> find_min(nums, -len(nums), -1) == min(nums)
True
>>> find_min(nums, -len(nums) - 1, -1) == min(nums)
Traceback (most recent call last):
...
IndexError: list index out of range
"""
if len(nums) == 0:
raise ValueError("find_min() arg is an empty sequence")
if (
left >= len(nums)
or left < -len(nums)
or right >= len(nums)
or right < -len(nums)
):
raise IndexError("list index out of range")
if left == right:
return nums[left]
mid = (left + right) >> 1 # the middle
left_min = find_min(nums, left, mid) # find min in range[left, mid]
right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right]
return left_min if left_min <= right_min else right_min
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # This theorem states that the number of prime factors of n
# will be approximately log(log(n)) for most natural numbers n
import math
def exact_prime_factor_count(n):
"""
>>> exact_prime_factor_count(51242183)
3
"""
count = 0
if n % 2 == 0:
count += 1
while n % 2 == 0:
n = int(n / 2)
# the n input value must be odd so that
# we can skip one element (ie i += 2)
i = 3
while i <= int(math.sqrt(n)):
if n % i == 0:
count += 1
while n % i == 0:
n = int(n / i)
i = i + 2
# this condition checks the prime
# number n is greater than 2
if n > 2:
count += 1
return count
if __name__ == "__main__":
n = 51242183
print(f"The number of distinct prime factors is/are {exact_prime_factor_count(n)}")
print(f"The value of log(log(n)) is {math.log(math.log(n)):.4f}")
"""
The number of distinct prime factors is/are 3
The value of log(log(n)) is 2.8765
"""
| # This theorem states that the number of prime factors of n
# will be approximately log(log(n)) for most natural numbers n
import math
def exact_prime_factor_count(n):
"""
>>> exact_prime_factor_count(51242183)
3
"""
count = 0
if n % 2 == 0:
count += 1
while n % 2 == 0:
n = int(n / 2)
# the n input value must be odd so that
# we can skip one element (ie i += 2)
i = 3
while i <= int(math.sqrt(n)):
if n % i == 0:
count += 1
while n % i == 0:
n = int(n / i)
i = i + 2
# this condition checks the prime
# number n is greater than 2
if n > 2:
count += 1
return count
if __name__ == "__main__":
n = 51242183
print(f"The number of distinct prime factors is/are {exact_prime_factor_count(n)}")
print(f"The value of log(log(n)) is {math.log(math.log(n)):.4f}")
"""
The number of distinct prime factors is/are 3
The value of log(log(n)) is 2.8765
"""
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Gaussian elimination method for solving a system of linear equations.
Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination
"""
import numpy as np
from numpy import float64
from numpy.typing import NDArray
def retroactive_resolution(
coefficients: NDArray[float64], vector: NDArray[float64]
) -> NDArray[float64]:
"""
This function performs a retroactive linear system resolution
for triangular matrix
Examples:
2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1
0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1
0x1 + 0x2 + 5x3 = 15
>>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]])
array([[2.],
[2.],
[3.]])
>>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]])
array([[-1. ],
[ 0.5]])
"""
rows, columns = np.shape(coefficients)
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
for row in reversed(range(rows)):
total = 0
for col in range(row + 1, columns):
total += coefficients[row, col] * x[col]
x[row, 0] = (vector[row] - total) / coefficients[row, row]
return x
def gaussian_elimination(
coefficients: NDArray[float64], vector: NDArray[float64]
) -> NDArray[float64]:
"""
This function performs Gaussian elimination method
Examples:
1x1 - 4x2 - 2x3 = -2 1x1 + 2x2 = 5
5x1 + 2x2 - 2x3 = -3 5x1 + 2x2 = 5
1x1 - 1x2 + 0x3 = 4
>>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]])
array([[ 2.3 ],
[-1.7 ],
[ 5.55]])
>>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]])
array([[0. ],
[2.5]])
"""
# coefficients must to be a square matrix so we need to check first
rows, columns = np.shape(coefficients)
if rows != columns:
return np.array((), dtype=float)
# augmented matrix
augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
augmented_mat = augmented_mat.astype("float64")
# scale the matrix leaving it triangular
for row in range(rows - 1):
pivot = augmented_mat[row, row]
for col in range(row + 1, columns):
factor = augmented_mat[col, row] / pivot
augmented_mat[col, :] -= factor * augmented_mat[row, :]
x = retroactive_resolution(
augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
)
return x
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Gaussian elimination method for solving a system of linear equations.
Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination
"""
import numpy as np
from numpy import float64
from numpy.typing import NDArray
def retroactive_resolution(
coefficients: NDArray[float64], vector: NDArray[float64]
) -> NDArray[float64]:
"""
This function performs a retroactive linear system resolution
for triangular matrix
Examples:
2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1
0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1
0x1 + 0x2 + 5x3 = 15
>>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]])
array([[2.],
[2.],
[3.]])
>>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]])
array([[-1. ],
[ 0.5]])
"""
rows, columns = np.shape(coefficients)
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
for row in reversed(range(rows)):
total = 0
for col in range(row + 1, columns):
total += coefficients[row, col] * x[col]
x[row, 0] = (vector[row] - total) / coefficients[row, row]
return x
def gaussian_elimination(
coefficients: NDArray[float64], vector: NDArray[float64]
) -> NDArray[float64]:
"""
This function performs Gaussian elimination method
Examples:
1x1 - 4x2 - 2x3 = -2 1x1 + 2x2 = 5
5x1 + 2x2 - 2x3 = -3 5x1 + 2x2 = 5
1x1 - 1x2 + 0x3 = 4
>>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]])
array([[ 2.3 ],
[-1.7 ],
[ 5.55]])
>>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]])
array([[0. ],
[2.5]])
"""
# coefficients must to be a square matrix so we need to check first
rows, columns = np.shape(coefficients)
if rows != columns:
return np.array((), dtype=float)
# augmented matrix
augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
augmented_mat = augmented_mat.astype("float64")
# scale the matrix leaving it triangular
for row in range(rows - 1):
pivot = augmented_mat[row, row]
for col in range(row + 1, columns):
factor = augmented_mat[col, row] / pivot
augmented_mat[col, :] -= factor * augmented_mat[row, :]
x = retroactive_resolution(
augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
)
return x
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Combinatoric selections
Problem 53
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater
than one-million?
"""
from math import factorial
def combinations(n, r):
return factorial(n) / (factorial(r) * factorial(n - r))
def solution():
"""Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than
one-million
>>> solution()
4075
"""
total = 0
for i in range(1, 101):
for j in range(1, i + 1):
if combinations(i, j) > 1e6:
total += 1
return total
if __name__ == "__main__":
print(solution())
| """
Combinatoric selections
Problem 53
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater
than one-million?
"""
from math import factorial
def combinations(n, r):
return factorial(n) / (factorial(r) * factorial(n - r))
def solution():
"""Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than
one-million
>>> solution()
4075
"""
total = 0
for i in range(1, 101):
for j in range(1, i + 1):
if combinations(i, j) > 1e6:
total += 1
return total
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from collections import Counter
def sock_merchant(colors: list[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([1, 1, 3, 3])
2
"""
return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values())
if __name__ == "__main__":
import doctest
doctest.testmod()
colors = [int(x) for x in input("Enter socks by color :").rstrip().split()]
print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
| from collections import Counter
def sock_merchant(colors: list[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([1, 1, 3, 3])
2
"""
return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values())
if __name__ == "__main__":
import doctest
doctest.testmod()
colors = [int(x) for x in input("Enter socks by color :").rstrip().split()]
print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
def find_max(nums: list[int | float]) -> int | float:
"""
>>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
... find_max(nums) == max(nums)
True
True
True
True
>>> find_max([2, 4, 9, 7, 19, 94, 5])
94
>>> find_max([])
Traceback (most recent call last):
...
ValueError: find_max() arg is an empty sequence
"""
if len(nums) == 0:
raise ValueError("find_max() arg is an empty sequence")
max_num = nums[0]
for x in nums:
if x > max_num:
max_num = x
return max_num
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| from __future__ import annotations
def find_max(nums: list[int | float]) -> int | float:
"""
>>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
... find_max(nums) == max(nums)
True
True
True
True
>>> find_max([2, 4, 9, 7, 19, 94, 5])
94
>>> find_max([])
Traceback (most recent call last):
...
ValueError: find_max() arg is an empty sequence
"""
if len(nums) == 0:
raise ValueError("find_max() arg is an empty sequence")
max_num = nums[0]
for x in nums:
if x > max_num:
max_num = x
return max_num
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
import random
class Dice:
NUM_SIDES = 6
def __init__(self):
"""Initialize a six sided dice"""
self.sides = list(range(1, Dice.NUM_SIDES + 1))
def roll(self):
return random.choice(self.sides)
def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:
"""
Return probability list of all possible sums when throwing dice.
>>> random.seed(0)
>>> throw_dice(10, 1)
[10.0, 0.0, 30.0, 50.0, 10.0, 0.0]
>>> throw_dice(100, 1)
[19.0, 17.0, 17.0, 11.0, 23.0, 13.0]
>>> throw_dice(1000, 1)
[18.8, 15.5, 16.3, 17.6, 14.2, 17.6]
>>> throw_dice(10000, 1)
[16.35, 16.89, 16.93, 16.6, 16.52, 16.71]
>>> throw_dice(10000, 2)
[2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75]
"""
dices = [Dice() for i in range(num_dice)]
count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1)
for _ in range(num_throws):
count_of_sum[sum(dice.roll() for dice in dices)] += 1
probability = [round((count * 100) / num_throws, 2) for count in count_of_sum]
return probability[num_dice:] # remove probability of sums that never appear
if __name__ == "__main__":
import doctest
doctest.testmod()
| from __future__ import annotations
import random
class Dice:
NUM_SIDES = 6
def __init__(self):
"""Initialize a six sided dice"""
self.sides = list(range(1, Dice.NUM_SIDES + 1))
def roll(self):
return random.choice(self.sides)
def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:
"""
Return probability list of all possible sums when throwing dice.
>>> random.seed(0)
>>> throw_dice(10, 1)
[10.0, 0.0, 30.0, 50.0, 10.0, 0.0]
>>> throw_dice(100, 1)
[19.0, 17.0, 17.0, 11.0, 23.0, 13.0]
>>> throw_dice(1000, 1)
[18.8, 15.5, 16.3, 17.6, 14.2, 17.6]
>>> throw_dice(10000, 1)
[16.35, 16.89, 16.93, 16.6, 16.52, 16.71]
>>> throw_dice(10000, 2)
[2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75]
"""
dices = [Dice() for i in range(num_dice)]
count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1)
for _ in range(num_throws):
count_of_sum[sum(dice.roll() for dice in dices)] += 1
probability = [round((count * 100) / num_throws, 2) for count in count_of_sum]
return probability[num_dice:] # remove probability of sums that never appear
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Description
The Koch snowflake is a fractal curve and one of the earliest fractals to
have been described. The Koch snowflake can be built up iteratively, in a
sequence of stages. The first stage is an equilateral triangle, and each
successive stage is formed by adding outward bends to each side of the
previous stage, making smaller equilateral triangles.
This can be achieved through the following steps for each line:
1. divide the line segment into three segments of equal length.
2. draw an equilateral triangle that has the middle segment from step 1
as its base and points outward.
3. remove the line segment that is the base of the triangle from step 2.
(description adapted from https://en.wikipedia.org/wiki/Koch_snowflake )
(for a more detailed explanation and an implementation in the
Processing language, see https://natureofcode.com/book/chapter-8-fractals/
#84-the-koch-curve-and-the-arraylist-technique )
Requirements (pip):
- matplotlib
- numpy
"""
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
VECTOR_1 = numpy.array([0, 0])
VECTOR_2 = numpy.array([0.5, 0.8660254])
VECTOR_3 = numpy.array([1, 0])
INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
# uncomment for simple Koch curve instead of Koch snowflake
# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]
def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]:
"""
Go through the number of iterations determined by the argument "steps".
Be careful with high values (above 5) since the time to calculate increases
exponentially.
>>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1)
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
vectors = initial_vectors
for _ in range(steps):
vectors = iteration_step(vectors)
return vectors
def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:
"""
Loops through each pair of adjacent vectors. Each line between two adjacent
vectors is divided into 4 segments by adding 3 additional vectors in-between
the original two vectors. The vector in the middle is constructed through a
60 degree rotation so it is bent outwards.
>>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])])
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
new_vectors = []
for i, start_vector in enumerate(vectors[:-1]):
end_vector = vectors[i + 1]
new_vectors.append(start_vector)
difference_vector = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3)
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60)
)
new_vectors.append(start_vector + difference_vector * 2 / 3)
new_vectors.append(vectors[-1])
return new_vectors
def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:
"""
Standard rotation of a 2D vector with a rotation matrix
(see https://en.wikipedia.org/wiki/Rotation_matrix )
>>> rotate(numpy.array([1, 0]), 60)
array([0.5 , 0.8660254])
>>> rotate(numpy.array([1, 0]), 90)
array([6.123234e-17, 1.000000e+00])
"""
theta = numpy.radians(angle_in_degrees)
c, s = numpy.cos(theta), numpy.sin(theta)
rotation_matrix = numpy.array(((c, -s), (s, c)))
return numpy.dot(rotation_matrix, vector)
def plot(vectors: list[numpy.ndarray]) -> None:
"""
Utility function to plot the vectors using matplotlib.pyplot
No doctest was implemented since this function does not have a return value
"""
# avoid stretched display of graph
axes = plt.gca()
axes.set_aspect("equal")
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
x_coordinates, y_coordinates = zip(*vectors)
plt.plot(x_coordinates, y_coordinates)
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
processed_vectors = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| """
Description
The Koch snowflake is a fractal curve and one of the earliest fractals to
have been described. The Koch snowflake can be built up iteratively, in a
sequence of stages. The first stage is an equilateral triangle, and each
successive stage is formed by adding outward bends to each side of the
previous stage, making smaller equilateral triangles.
This can be achieved through the following steps for each line:
1. divide the line segment into three segments of equal length.
2. draw an equilateral triangle that has the middle segment from step 1
as its base and points outward.
3. remove the line segment that is the base of the triangle from step 2.
(description adapted from https://en.wikipedia.org/wiki/Koch_snowflake )
(for a more detailed explanation and an implementation in the
Processing language, see https://natureofcode.com/book/chapter-8-fractals/
#84-the-koch-curve-and-the-arraylist-technique )
Requirements (pip):
- matplotlib
- numpy
"""
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
VECTOR_1 = numpy.array([0, 0])
VECTOR_2 = numpy.array([0.5, 0.8660254])
VECTOR_3 = numpy.array([1, 0])
INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
# uncomment for simple Koch curve instead of Koch snowflake
# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]
def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]:
"""
Go through the number of iterations determined by the argument "steps".
Be careful with high values (above 5) since the time to calculate increases
exponentially.
>>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1)
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
vectors = initial_vectors
for _ in range(steps):
vectors = iteration_step(vectors)
return vectors
def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:
"""
Loops through each pair of adjacent vectors. Each line between two adjacent
vectors is divided into 4 segments by adding 3 additional vectors in-between
the original two vectors. The vector in the middle is constructed through a
60 degree rotation so it is bent outwards.
>>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])])
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
new_vectors = []
for i, start_vector in enumerate(vectors[:-1]):
end_vector = vectors[i + 1]
new_vectors.append(start_vector)
difference_vector = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3)
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60)
)
new_vectors.append(start_vector + difference_vector * 2 / 3)
new_vectors.append(vectors[-1])
return new_vectors
def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:
"""
Standard rotation of a 2D vector with a rotation matrix
(see https://en.wikipedia.org/wiki/Rotation_matrix )
>>> rotate(numpy.array([1, 0]), 60)
array([0.5 , 0.8660254])
>>> rotate(numpy.array([1, 0]), 90)
array([6.123234e-17, 1.000000e+00])
"""
theta = numpy.radians(angle_in_degrees)
c, s = numpy.cos(theta), numpy.sin(theta)
rotation_matrix = numpy.array(((c, -s), (s, c)))
return numpy.dot(rotation_matrix, vector)
def plot(vectors: list[numpy.ndarray]) -> None:
"""
Utility function to plot the vectors using matplotlib.pyplot
No doctest was implemented since this function does not have a return value
"""
# avoid stretched display of graph
axes = plt.gca()
axes.set_aspect("equal")
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
x_coordinates, y_coordinates = zip(*vectors)
plt.plot(x_coordinates, y_coordinates)
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
processed_vectors = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """ Luhn Algorithm """
from __future__ import annotations
def is_luhn(string: str) -> bool:
"""
Perform Luhn validation on an input string
Algorithm:
* Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9.
* Sum the numbers
*
>>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
... 79927398719)
>>> [is_luhn(str(test_case)) for test_case in test_cases]
[False, False, False, True, False, False, False, False, False, False]
"""
check_digit: int
_vector: list[str] = list(string)
__vector, check_digit = _vector[:-1], int(_vector[-1])
vector: list[int] = [int(digit) for digit in __vector]
vector.reverse()
for i, digit in enumerate(vector):
if i & 1 == 0:
doubled: int = digit * 2
if doubled > 9:
doubled -= 9
check_digit += doubled
else:
check_digit += digit
return check_digit % 10 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
assert is_luhn("79927398713")
assert not is_luhn("79927398714")
| """ Luhn Algorithm """
from __future__ import annotations
def is_luhn(string: str) -> bool:
"""
Perform Luhn validation on an input string
Algorithm:
* Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9.
* Sum the numbers
*
>>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
... 79927398719)
>>> [is_luhn(str(test_case)) for test_case in test_cases]
[False, False, False, True, False, False, False, False, False, False]
"""
check_digit: int
_vector: list[str] = list(string)
__vector, check_digit = _vector[:-1], int(_vector[-1])
vector: list[int] = [int(digit) for digit in __vector]
vector.reverse()
for i, digit in enumerate(vector):
if i & 1 == 0:
doubled: int = digit * 2
if doubled > 9:
doubled -= 9
check_digit += doubled
else:
check_digit += digit
return check_digit % 10 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
assert is_luhn("79927398713")
assert not is_luhn("79927398714")
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Find the area of various geometric shapes
Wikipedia reference: https://en.wikipedia.org/wiki/Area
"""
from math import pi, sqrt, tan
def surface_area_cube(side_length: float) -> float:
"""
Calculate the Surface Area of a Cube.
>>> surface_area_cube(1)
6
>>> surface_area_cube(1.6)
15.360000000000003
>>> surface_area_cube(0)
0
>>> surface_area_cube(3)
54
>>> surface_area_cube(-1)
Traceback (most recent call last):
...
ValueError: surface_area_cube() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("surface_area_cube() only accepts non-negative values")
return 6 * side_length**2
def surface_area_cuboid(length: float, breadth: float, height: float) -> float:
"""
Calculate the Surface Area of a Cuboid.
>>> surface_area_cuboid(1, 2, 3)
22
>>> surface_area_cuboid(0, 0, 0)
0
>>> surface_area_cuboid(1.6, 2.6, 3.6)
38.56
>>> surface_area_cuboid(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_cuboid() only accepts non-negative values
>>> surface_area_cuboid(1, -2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_cuboid() only accepts non-negative values
>>> surface_area_cuboid(1, 2, -3)
Traceback (most recent call last):
...
ValueError: surface_area_cuboid() only accepts non-negative values
"""
if length < 0 or breadth < 0 or height < 0:
raise ValueError("surface_area_cuboid() only accepts non-negative values")
return 2 * ((length * breadth) + (breadth * height) + (length * height))
def surface_area_sphere(radius: float) -> float:
"""
Calculate the Surface Area of a Sphere.
Wikipedia reference: https://en.wikipedia.org/wiki/Sphere
Formula: 4 * pi * r^2
>>> surface_area_sphere(5)
314.1592653589793
>>> surface_area_sphere(1)
12.566370614359172
>>> surface_area_sphere(1.6)
32.169908772759484
>>> surface_area_sphere(0)
0.0
>>> surface_area_sphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_sphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_sphere() only accepts non-negative values")
return 4 * pi * radius**2
def surface_area_hemisphere(radius: float) -> float:
"""
Calculate the Surface Area of a Hemisphere.
Formula: 3 * pi * r^2
>>> surface_area_hemisphere(5)
235.61944901923448
>>> surface_area_hemisphere(1)
9.42477796076938
>>> surface_area_hemisphere(0)
0.0
>>> surface_area_hemisphere(1.1)
11.40398133253095
>>> surface_area_hemisphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_hemisphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_hemisphere() only accepts non-negative values")
return 3 * pi * radius**2
def surface_area_cone(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)
>>> surface_area_cone(10, 24)
1130.9733552923256
>>> surface_area_cone(6, 8)
301.59289474462014
>>> surface_area_cone(1.6, 2.6)
23.387862992395807
>>> surface_area_cone(0, 0)
0.0
>>> surface_area_cone(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height**2 + radius**2) ** 0.5)
def surface_area_conical_frustum(
radius_1: float, radius_2: float, height: float
) -> float:
"""
Calculate the Surface Area of a Conical Frustum.
>>> surface_area_conical_frustum(1, 2, 3)
45.511728065337266
>>> surface_area_conical_frustum(4, 5, 6)
300.7913575056268
>>> surface_area_conical_frustum(0, 0, 0)
0.0
>>> surface_area_conical_frustum(1.6, 2.6, 3.6)
78.57907060751548
>>> surface_area_conical_frustum(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_conical_frustum() only accepts non-negative values
>>> surface_area_conical_frustum(1, -2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_conical_frustum() only accepts non-negative values
>>> surface_area_conical_frustum(1, 2, -3)
Traceback (most recent call last):
...
ValueError: surface_area_conical_frustum() only accepts non-negative values
"""
if radius_1 < 0 or radius_2 < 0 or height < 0:
raise ValueError(
"surface_area_conical_frustum() only accepts non-negative values"
)
slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5
return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2)
def surface_area_cylinder(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cylinder.
Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder
Formula: 2 * pi * r * (h + r)
>>> surface_area_cylinder(7, 10)
747.6990515543707
>>> surface_area_cylinder(1.6, 2.6)
42.22300526424682
>>> surface_area_cylinder(0, 0)
0.0
>>> surface_area_cylinder(6, 8)
527.7875658030853
>>> surface_area_cylinder(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cylinder() only accepts non-negative values")
return 2 * pi * radius * (height + radius)
def surface_area_torus(torus_radius: float, tube_radius: float) -> float:
"""Calculate the Area of a Torus.
Wikipedia reference: https://en.wikipedia.org/wiki/Torus
:return 4pi^2 * torus_radius * tube_radius
>>> surface_area_torus(1, 1)
39.47841760435743
>>> surface_area_torus(4, 3)
473.7410112522892
>>> surface_area_torus(3, 4)
Traceback (most recent call last):
...
ValueError: surface_area_torus() does not support spindle or self intersecting tori
>>> surface_area_torus(1.6, 1.6)
101.06474906715503
>>> surface_area_torus(0, 0)
0.0
>>> surface_area_torus(-1, 1)
Traceback (most recent call last):
...
ValueError: surface_area_torus() only accepts non-negative values
>>> surface_area_torus(1, -1)
Traceback (most recent call last):
...
ValueError: surface_area_torus() only accepts non-negative values
"""
if torus_radius < 0 or tube_radius < 0:
raise ValueError("surface_area_torus() only accepts non-negative values")
if torus_radius < tube_radius:
raise ValueError(
"surface_area_torus() does not support spindle or self intersecting tori"
)
return 4 * pow(pi, 2) * torus_radius * tube_radius
def area_rectangle(length: float, width: float) -> float:
"""
Calculate the area of a rectangle.
>>> area_rectangle(10, 20)
200
>>> area_rectangle(1.6, 2.6)
4.16
>>> area_rectangle(0, 0)
0
>>> area_rectangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
"""
if length < 0 or width < 0:
raise ValueError("area_rectangle() only accepts non-negative values")
return length * width
def area_square(side_length: float) -> float:
"""
Calculate the area of a square.
>>> area_square(10)
100
>>> area_square(0)
0
>>> area_square(1.6)
2.5600000000000005
>>> area_square(-1)
Traceback (most recent call last):
...
ValueError: area_square() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("area_square() only accepts non-negative values")
return side_length**2
def area_triangle(base: float, height: float) -> float:
"""
Calculate the area of a triangle given the base and height.
>>> area_triangle(10, 10)
50.0
>>> area_triangle(1.6, 2.6)
2.08
>>> area_triangle(0, 0)
0.0
>>> area_triangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_triangle() only accepts non-negative values")
return (base * height) / 2
def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float:
"""
Calculate area of triangle when the length of 3 sides are known.
This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula
>>> area_triangle_three_sides(5, 12, 13)
30.0
>>> area_triangle_three_sides(10, 11, 12)
51.521233486786784
>>> area_triangle_three_sides(0, 0, 0)
0.0
>>> area_triangle_three_sides(1.6, 2.6, 3.6)
1.8703742940919619
>>> area_triangle_three_sides(-1, -2, -1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(1, -2, 1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(2, 4, 7)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(2, 7, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(7, 2, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
"""
if side1 < 0 or side2 < 0 or side3 < 0:
raise ValueError("area_triangle_three_sides() only accepts non-negative values")
elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1:
raise ValueError("Given three sides do not form a triangle")
semi_perimeter = (side1 + side2 + side3) / 2
area = sqrt(
semi_perimeter
* (semi_perimeter - side1)
* (semi_perimeter - side2)
* (semi_perimeter - side3)
)
return area
def area_parallelogram(base: float, height: float) -> float:
"""
Calculate the area of a parallelogram.
>>> area_parallelogram(10, 20)
200
>>> area_parallelogram(1.6, 2.6)
4.16
>>> area_parallelogram(0, 0)
0
>>> area_parallelogram(-1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(-1, 2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_parallelogram() only accepts non-negative values")
return base * height
def area_trapezium(base1: float, base2: float, height: float) -> float:
"""
Calculate the area of a trapezium.
>>> area_trapezium(10, 20, 30)
450.0
>>> area_trapezium(1.6, 2.6, 3.6)
7.5600000000000005
>>> area_trapezium(0, 0, 0)
0.0
>>> area_trapezium(-1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
"""
if base1 < 0 or base2 < 0 or height < 0:
raise ValueError("area_trapezium() only accepts non-negative values")
return 1 / 2 * (base1 + base2) * height
def area_circle(radius: float) -> float:
"""
Calculate the area of a circle.
>>> area_circle(20)
1256.6370614359173
>>> area_circle(1.6)
8.042477193189871
>>> area_circle(0)
0.0
>>> area_circle(-1)
Traceback (most recent call last):
...
ValueError: area_circle() only accepts non-negative values
"""
if radius < 0:
raise ValueError("area_circle() only accepts non-negative values")
return pi * radius**2
def area_ellipse(radius_x: float, radius_y: float) -> float:
"""
Calculate the area of a ellipse.
>>> area_ellipse(10, 10)
314.1592653589793
>>> area_ellipse(10, 20)
628.3185307179587
>>> area_ellipse(0, 0)
0.0
>>> area_ellipse(1.6, 2.6)
13.06902543893354
>>> area_ellipse(-10, 20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(-10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
"""
if radius_x < 0 or radius_y < 0:
raise ValueError("area_ellipse() only accepts non-negative values")
return pi * radius_x * radius_y
def area_rhombus(diagonal_1: float, diagonal_2: float) -> float:
"""
Calculate the area of a rhombus.
>>> area_rhombus(10, 20)
100.0
>>> area_rhombus(1.6, 2.6)
2.08
>>> area_rhombus(0, 0)
0.0
>>> area_rhombus(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
"""
if diagonal_1 < 0 or diagonal_2 < 0:
raise ValueError("area_rhombus() only accepts non-negative values")
return 1 / 2 * diagonal_1 * diagonal_2
def area_reg_polygon(sides: int, length: float) -> float:
"""
Calculate the area of a regular polygon.
Wikipedia reference: https://en.wikipedia.org/wiki/Polygon#Regular_polygons
Formula: (n*s^2*cot(pi/n))/4
>>> area_reg_polygon(3, 10)
43.301270189221945
>>> area_reg_polygon(4, 10)
100.00000000000001
>>> area_reg_polygon(0, 0)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
>>> area_reg_polygon(-1, -2)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
>>> area_reg_polygon(5, -2)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts non-negative values as \
length of a side
>>> area_reg_polygon(-1, 2)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
"""
if not isinstance(sides, int) or sides < 3:
raise ValueError(
"area_reg_polygon() only accepts integers greater than or \
equal to three as number of sides"
)
elif length < 0:
raise ValueError(
"area_reg_polygon() only accepts non-negative values as \
length of a side"
)
return (sides * length**2) / (4 * tan(pi / sides))
return (sides * length**2) / (4 * tan(pi / sides))
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) # verbose so we can see methods missing tests
print("[DEMO] Areas of various geometric shapes: \n")
print(f"Rectangle: {area_rectangle(10, 20) = }")
print(f"Square: {area_square(10) = }")
print(f"Triangle: {area_triangle(10, 10) = }")
print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }")
print(f"Parallelogram: {area_parallelogram(10, 20) = }")
print(f"Rhombus: {area_rhombus(10, 20) = }")
print(f"Trapezium: {area_trapezium(10, 20, 30) = }")
print(f"Circle: {area_circle(20) = }")
print(f"Ellipse: {area_ellipse(10, 20) = }")
print("\nSurface Areas of various geometric shapes: \n")
print(f"Cube: {surface_area_cube(20) = }")
print(f"Cuboid: {surface_area_cuboid(10, 20, 30) = }")
print(f"Sphere: {surface_area_sphere(20) = }")
print(f"Hemisphere: {surface_area_hemisphere(20) = }")
print(f"Cone: {surface_area_cone(10, 20) = }")
print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }")
print(f"Cylinder: {surface_area_cylinder(10, 20) = }")
print(f"Torus: {surface_area_torus(20, 10) = }")
print(f"Equilateral Triangle: {area_reg_polygon(3, 10) = }")
print(f"Square: {area_reg_polygon(4, 10) = }")
print(f"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
| """
Find the area of various geometric shapes
Wikipedia reference: https://en.wikipedia.org/wiki/Area
"""
from math import pi, sqrt, tan
def surface_area_cube(side_length: float) -> float:
"""
Calculate the Surface Area of a Cube.
>>> surface_area_cube(1)
6
>>> surface_area_cube(1.6)
15.360000000000003
>>> surface_area_cube(0)
0
>>> surface_area_cube(3)
54
>>> surface_area_cube(-1)
Traceback (most recent call last):
...
ValueError: surface_area_cube() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("surface_area_cube() only accepts non-negative values")
return 6 * side_length**2
def surface_area_cuboid(length: float, breadth: float, height: float) -> float:
"""
Calculate the Surface Area of a Cuboid.
>>> surface_area_cuboid(1, 2, 3)
22
>>> surface_area_cuboid(0, 0, 0)
0
>>> surface_area_cuboid(1.6, 2.6, 3.6)
38.56
>>> surface_area_cuboid(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_cuboid() only accepts non-negative values
>>> surface_area_cuboid(1, -2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_cuboid() only accepts non-negative values
>>> surface_area_cuboid(1, 2, -3)
Traceback (most recent call last):
...
ValueError: surface_area_cuboid() only accepts non-negative values
"""
if length < 0 or breadth < 0 or height < 0:
raise ValueError("surface_area_cuboid() only accepts non-negative values")
return 2 * ((length * breadth) + (breadth * height) + (length * height))
def surface_area_sphere(radius: float) -> float:
"""
Calculate the Surface Area of a Sphere.
Wikipedia reference: https://en.wikipedia.org/wiki/Sphere
Formula: 4 * pi * r^2
>>> surface_area_sphere(5)
314.1592653589793
>>> surface_area_sphere(1)
12.566370614359172
>>> surface_area_sphere(1.6)
32.169908772759484
>>> surface_area_sphere(0)
0.0
>>> surface_area_sphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_sphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_sphere() only accepts non-negative values")
return 4 * pi * radius**2
def surface_area_hemisphere(radius: float) -> float:
"""
Calculate the Surface Area of a Hemisphere.
Formula: 3 * pi * r^2
>>> surface_area_hemisphere(5)
235.61944901923448
>>> surface_area_hemisphere(1)
9.42477796076938
>>> surface_area_hemisphere(0)
0.0
>>> surface_area_hemisphere(1.1)
11.40398133253095
>>> surface_area_hemisphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_hemisphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_hemisphere() only accepts non-negative values")
return 3 * pi * radius**2
def surface_area_cone(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)
>>> surface_area_cone(10, 24)
1130.9733552923256
>>> surface_area_cone(6, 8)
301.59289474462014
>>> surface_area_cone(1.6, 2.6)
23.387862992395807
>>> surface_area_cone(0, 0)
0.0
>>> surface_area_cone(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height**2 + radius**2) ** 0.5)
def surface_area_conical_frustum(
radius_1: float, radius_2: float, height: float
) -> float:
"""
Calculate the Surface Area of a Conical Frustum.
>>> surface_area_conical_frustum(1, 2, 3)
45.511728065337266
>>> surface_area_conical_frustum(4, 5, 6)
300.7913575056268
>>> surface_area_conical_frustum(0, 0, 0)
0.0
>>> surface_area_conical_frustum(1.6, 2.6, 3.6)
78.57907060751548
>>> surface_area_conical_frustum(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_conical_frustum() only accepts non-negative values
>>> surface_area_conical_frustum(1, -2, 3)
Traceback (most recent call last):
...
ValueError: surface_area_conical_frustum() only accepts non-negative values
>>> surface_area_conical_frustum(1, 2, -3)
Traceback (most recent call last):
...
ValueError: surface_area_conical_frustum() only accepts non-negative values
"""
if radius_1 < 0 or radius_2 < 0 or height < 0:
raise ValueError(
"surface_area_conical_frustum() only accepts non-negative values"
)
slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5
return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2)
def surface_area_cylinder(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cylinder.
Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder
Formula: 2 * pi * r * (h + r)
>>> surface_area_cylinder(7, 10)
747.6990515543707
>>> surface_area_cylinder(1.6, 2.6)
42.22300526424682
>>> surface_area_cylinder(0, 0)
0.0
>>> surface_area_cylinder(6, 8)
527.7875658030853
>>> surface_area_cylinder(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cylinder() only accepts non-negative values")
return 2 * pi * radius * (height + radius)
def surface_area_torus(torus_radius: float, tube_radius: float) -> float:
"""Calculate the Area of a Torus.
Wikipedia reference: https://en.wikipedia.org/wiki/Torus
:return 4pi^2 * torus_radius * tube_radius
>>> surface_area_torus(1, 1)
39.47841760435743
>>> surface_area_torus(4, 3)
473.7410112522892
>>> surface_area_torus(3, 4)
Traceback (most recent call last):
...
ValueError: surface_area_torus() does not support spindle or self intersecting tori
>>> surface_area_torus(1.6, 1.6)
101.06474906715503
>>> surface_area_torus(0, 0)
0.0
>>> surface_area_torus(-1, 1)
Traceback (most recent call last):
...
ValueError: surface_area_torus() only accepts non-negative values
>>> surface_area_torus(1, -1)
Traceback (most recent call last):
...
ValueError: surface_area_torus() only accepts non-negative values
"""
if torus_radius < 0 or tube_radius < 0:
raise ValueError("surface_area_torus() only accepts non-negative values")
if torus_radius < tube_radius:
raise ValueError(
"surface_area_torus() does not support spindle or self intersecting tori"
)
return 4 * pow(pi, 2) * torus_radius * tube_radius
def area_rectangle(length: float, width: float) -> float:
"""
Calculate the area of a rectangle.
>>> area_rectangle(10, 20)
200
>>> area_rectangle(1.6, 2.6)
4.16
>>> area_rectangle(0, 0)
0
>>> area_rectangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
"""
if length < 0 or width < 0:
raise ValueError("area_rectangle() only accepts non-negative values")
return length * width
def area_square(side_length: float) -> float:
"""
Calculate the area of a square.
>>> area_square(10)
100
>>> area_square(0)
0
>>> area_square(1.6)
2.5600000000000005
>>> area_square(-1)
Traceback (most recent call last):
...
ValueError: area_square() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("area_square() only accepts non-negative values")
return side_length**2
def area_triangle(base: float, height: float) -> float:
"""
Calculate the area of a triangle given the base and height.
>>> area_triangle(10, 10)
50.0
>>> area_triangle(1.6, 2.6)
2.08
>>> area_triangle(0, 0)
0.0
>>> area_triangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_triangle() only accepts non-negative values")
return (base * height) / 2
def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float:
"""
Calculate area of triangle when the length of 3 sides are known.
This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula
>>> area_triangle_three_sides(5, 12, 13)
30.0
>>> area_triangle_three_sides(10, 11, 12)
51.521233486786784
>>> area_triangle_three_sides(0, 0, 0)
0.0
>>> area_triangle_three_sides(1.6, 2.6, 3.6)
1.8703742940919619
>>> area_triangle_three_sides(-1, -2, -1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(1, -2, 1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(2, 4, 7)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(2, 7, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(7, 2, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
"""
if side1 < 0 or side2 < 0 or side3 < 0:
raise ValueError("area_triangle_three_sides() only accepts non-negative values")
elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1:
raise ValueError("Given three sides do not form a triangle")
semi_perimeter = (side1 + side2 + side3) / 2
area = sqrt(
semi_perimeter
* (semi_perimeter - side1)
* (semi_perimeter - side2)
* (semi_perimeter - side3)
)
return area
def area_parallelogram(base: float, height: float) -> float:
"""
Calculate the area of a parallelogram.
>>> area_parallelogram(10, 20)
200
>>> area_parallelogram(1.6, 2.6)
4.16
>>> area_parallelogram(0, 0)
0
>>> area_parallelogram(-1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(-1, 2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_parallelogram() only accepts non-negative values")
return base * height
def area_trapezium(base1: float, base2: float, height: float) -> float:
"""
Calculate the area of a trapezium.
>>> area_trapezium(10, 20, 30)
450.0
>>> area_trapezium(1.6, 2.6, 3.6)
7.5600000000000005
>>> area_trapezium(0, 0, 0)
0.0
>>> area_trapezium(-1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
"""
if base1 < 0 or base2 < 0 or height < 0:
raise ValueError("area_trapezium() only accepts non-negative values")
return 1 / 2 * (base1 + base2) * height
def area_circle(radius: float) -> float:
"""
Calculate the area of a circle.
>>> area_circle(20)
1256.6370614359173
>>> area_circle(1.6)
8.042477193189871
>>> area_circle(0)
0.0
>>> area_circle(-1)
Traceback (most recent call last):
...
ValueError: area_circle() only accepts non-negative values
"""
if radius < 0:
raise ValueError("area_circle() only accepts non-negative values")
return pi * radius**2
def area_ellipse(radius_x: float, radius_y: float) -> float:
"""
Calculate the area of a ellipse.
>>> area_ellipse(10, 10)
314.1592653589793
>>> area_ellipse(10, 20)
628.3185307179587
>>> area_ellipse(0, 0)
0.0
>>> area_ellipse(1.6, 2.6)
13.06902543893354
>>> area_ellipse(-10, 20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(-10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
"""
if radius_x < 0 or radius_y < 0:
raise ValueError("area_ellipse() only accepts non-negative values")
return pi * radius_x * radius_y
def area_rhombus(diagonal_1: float, diagonal_2: float) -> float:
"""
Calculate the area of a rhombus.
>>> area_rhombus(10, 20)
100.0
>>> area_rhombus(1.6, 2.6)
2.08
>>> area_rhombus(0, 0)
0.0
>>> area_rhombus(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
"""
if diagonal_1 < 0 or diagonal_2 < 0:
raise ValueError("area_rhombus() only accepts non-negative values")
return 1 / 2 * diagonal_1 * diagonal_2
def area_reg_polygon(sides: int, length: float) -> float:
"""
Calculate the area of a regular polygon.
Wikipedia reference: https://en.wikipedia.org/wiki/Polygon#Regular_polygons
Formula: (n*s^2*cot(pi/n))/4
>>> area_reg_polygon(3, 10)
43.301270189221945
>>> area_reg_polygon(4, 10)
100.00000000000001
>>> area_reg_polygon(0, 0)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
>>> area_reg_polygon(-1, -2)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
>>> area_reg_polygon(5, -2)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts non-negative values as \
length of a side
>>> area_reg_polygon(-1, 2)
Traceback (most recent call last):
...
ValueError: area_reg_polygon() only accepts integers greater than or equal to \
three as number of sides
"""
if not isinstance(sides, int) or sides < 3:
raise ValueError(
"area_reg_polygon() only accepts integers greater than or \
equal to three as number of sides"
)
elif length < 0:
raise ValueError(
"area_reg_polygon() only accepts non-negative values as \
length of a side"
)
return (sides * length**2) / (4 * tan(pi / sides))
return (sides * length**2) / (4 * tan(pi / sides))
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) # verbose so we can see methods missing tests
print("[DEMO] Areas of various geometric shapes: \n")
print(f"Rectangle: {area_rectangle(10, 20) = }")
print(f"Square: {area_square(10) = }")
print(f"Triangle: {area_triangle(10, 10) = }")
print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }")
print(f"Parallelogram: {area_parallelogram(10, 20) = }")
print(f"Rhombus: {area_rhombus(10, 20) = }")
print(f"Trapezium: {area_trapezium(10, 20, 30) = }")
print(f"Circle: {area_circle(20) = }")
print(f"Ellipse: {area_ellipse(10, 20) = }")
print("\nSurface Areas of various geometric shapes: \n")
print(f"Cube: {surface_area_cube(20) = }")
print(f"Cuboid: {surface_area_cuboid(10, 20, 30) = }")
print(f"Sphere: {surface_area_sphere(20) = }")
print(f"Hemisphere: {surface_area_hemisphere(20) = }")
print(f"Cone: {surface_area_cone(10, 20) = }")
print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }")
print(f"Cylinder: {surface_area_cylinder(10, 20) = }")
print(f"Torus: {surface_area_torus(20, 10) = }")
print(f"Equilateral Triangle: {area_reg_polygon(3, 10) = }")
print(f"Square: {area_reg_polygon(4, 10) = }")
print(f"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def remove_duplicates(sentence: str) -> str:
"""
Remove duplicates from sentence
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
"""
return " ".join(sorted(set(sentence.split())))
if __name__ == "__main__":
import doctest
doctest.testmod()
| def remove_duplicates(sentence: str) -> str:
"""
Remove duplicates from sentence
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
"""
return " ".join(sorted(set(sentence.split())))
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Graph Coloring also called "m coloring problem"
consists of coloring a given graph with at most m colors
such that no adjacent vertices are assigned the same color
Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
"""
def valid_coloring(
neighbours: list[int], colored_vertices: list[int], color: int
) -> bool:
"""
For each neighbour check if the coloring constraint is satisfied
If any of the neighbours fail the constraint return False
If all neighbours validate the constraint return True
>>> neighbours = [0,1,0,1,0]
>>> colored_vertices = [0, 2, 1, 2, 0]
>>> color = 1
>>> valid_coloring(neighbours, colored_vertices, color)
True
>>> color = 2
>>> valid_coloring(neighbours, colored_vertices, color)
False
"""
# Does any neighbour not satisfy the constraints
return not any(
neighbour == 1 and colored_vertices[i] == color
for i, neighbour in enumerate(neighbours)
)
def util_color(
graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int
) -> bool:
"""
Pseudo-Code
Base Case:
1. Check if coloring is complete
1.1 If complete return True (meaning that we successfully colored the graph)
Recursive Step:
2. Iterates over each color:
Check if the current coloring is valid:
2.1. Color given vertex
2.2. Do recursive call, check if this coloring leads to a solution
2.4. if current coloring leads to a solution return
2.5. Uncolor given vertex
>>> graph = [[0, 1, 0, 0, 0],
... [1, 0, 1, 0, 1],
... [0, 1, 0, 1, 0],
... [0, 1, 1, 0, 0],
... [0, 1, 0, 0, 0]]
>>> max_colors = 3
>>> colored_vertices = [0, 1, 0, 0, 0]
>>> index = 3
>>> util_color(graph, max_colors, colored_vertices, index)
True
>>> max_colors = 2
>>> util_color(graph, max_colors, colored_vertices, index)
False
"""
# Base Case
if index == len(graph):
return True
# Recursive Step
for i in range(max_colors):
if valid_coloring(graph[index], colored_vertices, i):
# Color current vertex
colored_vertices[index] = i
# Validate coloring
if util_color(graph, max_colors, colored_vertices, index + 1):
return True
# Backtrack
colored_vertices[index] = -1
return False
def color(graph: list[list[int]], max_colors: int) -> list[int]:
"""
Wrapper function to call subroutine called util_color
which will either return True or False.
If True is returned colored_vertices list is filled with correct colorings
>>> graph = [[0, 1, 0, 0, 0],
... [1, 0, 1, 0, 1],
... [0, 1, 0, 1, 0],
... [0, 1, 1, 0, 0],
... [0, 1, 0, 0, 0]]
>>> max_colors = 3
>>> color(graph, max_colors)
[0, 1, 0, 2, 0]
>>> max_colors = 2
>>> color(graph, max_colors)
[]
"""
colored_vertices = [-1] * len(graph)
if util_color(graph, max_colors, colored_vertices, 0):
return colored_vertices
return []
| """
Graph Coloring also called "m coloring problem"
consists of coloring a given graph with at most m colors
such that no adjacent vertices are assigned the same color
Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
"""
def valid_coloring(
neighbours: list[int], colored_vertices: list[int], color: int
) -> bool:
"""
For each neighbour check if the coloring constraint is satisfied
If any of the neighbours fail the constraint return False
If all neighbours validate the constraint return True
>>> neighbours = [0,1,0,1,0]
>>> colored_vertices = [0, 2, 1, 2, 0]
>>> color = 1
>>> valid_coloring(neighbours, colored_vertices, color)
True
>>> color = 2
>>> valid_coloring(neighbours, colored_vertices, color)
False
"""
# Does any neighbour not satisfy the constraints
return not any(
neighbour == 1 and colored_vertices[i] == color
for i, neighbour in enumerate(neighbours)
)
def util_color(
graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int
) -> bool:
"""
Pseudo-Code
Base Case:
1. Check if coloring is complete
1.1 If complete return True (meaning that we successfully colored the graph)
Recursive Step:
2. Iterates over each color:
Check if the current coloring is valid:
2.1. Color given vertex
2.2. Do recursive call, check if this coloring leads to a solution
2.4. if current coloring leads to a solution return
2.5. Uncolor given vertex
>>> graph = [[0, 1, 0, 0, 0],
... [1, 0, 1, 0, 1],
... [0, 1, 0, 1, 0],
... [0, 1, 1, 0, 0],
... [0, 1, 0, 0, 0]]
>>> max_colors = 3
>>> colored_vertices = [0, 1, 0, 0, 0]
>>> index = 3
>>> util_color(graph, max_colors, colored_vertices, index)
True
>>> max_colors = 2
>>> util_color(graph, max_colors, colored_vertices, index)
False
"""
# Base Case
if index == len(graph):
return True
# Recursive Step
for i in range(max_colors):
if valid_coloring(graph[index], colored_vertices, i):
# Color current vertex
colored_vertices[index] = i
# Validate coloring
if util_color(graph, max_colors, colored_vertices, index + 1):
return True
# Backtrack
colored_vertices[index] = -1
return False
def color(graph: list[list[int]], max_colors: int) -> list[int]:
"""
Wrapper function to call subroutine called util_color
which will either return True or False.
If True is returned colored_vertices list is filled with correct colorings
>>> graph = [[0, 1, 0, 0, 0],
... [1, 0, 1, 0, 1],
... [0, 1, 0, 1, 0],
... [0, 1, 1, 0, 0],
... [0, 1, 0, 0, 0]]
>>> max_colors = 3
>>> color(graph, max_colors)
[0, 1, 0, 2, 0]
>>> max_colors = 2
>>> color(graph, max_colors)
[]
"""
colored_vertices = [-1] * len(graph)
if util_color(graph, max_colors, colored_vertices, 0):
return colored_vertices
return []
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def perfect_cube(n: int) -> bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val = n ** (1 / 3)
return (val * val * val) == n
if __name__ == "__main__":
print(perfect_cube(27))
print(perfect_cube(4))
| def perfect_cube(n: int) -> bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val = n ** (1 / 3)
return (val * val * val) == n
if __name__ == "__main__":
print(perfect_cube(27))
print(perfect_cube(4))
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Get CO2 emission data from the UK CarbonIntensity API
"""
from datetime import date
import requests
BASE_URL = "https://api.carbonintensity.org.uk/intensity"
# Emission in the last half hour
def fetch_last_half_hour() -> str:
last_half_hour = requests.get(BASE_URL).json()["data"][0]
return last_half_hour["intensity"]["actual"]
# Emissions in a specific date range
def fetch_from_to(start, end) -> list:
return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"]
if __name__ == "__main__":
for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)):
print("from {from} to {to}: {intensity[actual]}".format(**entry))
print(f"{fetch_last_half_hour() = }")
| """
Get CO2 emission data from the UK CarbonIntensity API
"""
from datetime import date
import requests
BASE_URL = "https://api.carbonintensity.org.uk/intensity"
# Emission in the last half hour
def fetch_last_half_hour() -> str:
last_half_hour = requests.get(BASE_URL).json()["data"][0]
return last_half_hour["intensity"]["actual"]
# Emissions in a specific date range
def fetch_from_to(start, end) -> list:
return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"]
if __name__ == "__main__":
for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)):
print("from {from} to {to}: {intensity[actual]}".format(**entry))
print(f"{fetch_last_half_hour() = }")
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import requests
APPID = "" # <-- Put your OpenWeatherMap appid here!
URL_BASE = "https://api.openweathermap.org/data/2.5/"
def current_weather(q: str = "Chicago", appid: str = APPID) -> dict:
"""https://openweathermap.org/api"""
return requests.get(URL_BASE + "weather", params=locals()).json()
def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict:
"""https://openweathermap.org/forecast5"""
return requests.get(URL_BASE + "forecast", params=locals()).json()
def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict:
"""https://openweathermap.org/api/one-call-api"""
return requests.get(URL_BASE + "onecall", params=locals()).json()
if __name__ == "__main__":
from pprint import pprint
while True:
location = input("Enter a location:").strip()
if location:
pprint(current_weather(location))
else:
break
| import requests
APPID = "" # <-- Put your OpenWeatherMap appid here!
URL_BASE = "https://api.openweathermap.org/data/2.5/"
def current_weather(q: str = "Chicago", appid: str = APPID) -> dict:
"""https://openweathermap.org/api"""
return requests.get(URL_BASE + "weather", params=locals()).json()
def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict:
"""https://openweathermap.org/forecast5"""
return requests.get(URL_BASE + "forecast", params=locals()).json()
def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict:
"""https://openweathermap.org/api/one-call-api"""
return requests.get(URL_BASE + "onecall", params=locals()).json()
if __name__ == "__main__":
from pprint import pprint
while True:
location = input("Enter a location:").strip()
if location:
pprint(current_weather(location))
else:
break
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def upper(word: str) -> str:
"""
Will convert the entire string to uppercase letters
>>> upper("wow")
'WOW'
>>> upper("Hello")
'HELLO'
>>> upper("WHAT")
'WHAT'
>>> upper("wh[]32")
'WH[]32'
"""
# Converting to ascii value int value and checking to see if char is a lower letter
# if it is a lowercase letter it is getting shift by 32 which makes it an uppercase
# case letter
return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word)
if __name__ == "__main__":
from doctest import testmod
testmod()
| def upper(word: str) -> str:
"""
Will convert the entire string to uppercase letters
>>> upper("wow")
'WOW'
>>> upper("Hello")
'HELLO'
>>> upper("WHAT")
'WHAT'
>>> upper("wh[]32")
'WH[]32'
"""
# Converting to ascii value int value and checking to see if char is a lower letter
# if it is a lowercase letter it is getting shift by 32 which makes it an uppercase
# case letter
return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word)
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/Check_digit#Algorithms
"""
def get_check_digit(barcode: int) -> int:
"""
Returns the last digit of barcode by excluding the last digit first
and then computing to reach the actual last digit from the remaining
12 digits.
>>> get_check_digit(8718452538119)
9
>>> get_check_digit(87184523)
5
>>> get_check_digit(87193425381086)
9
>>> [get_check_digit(x) for x in range(0, 100, 10)]
[0, 7, 4, 1, 8, 5, 2, 9, 6, 3]
"""
barcode //= 10 # exclude the last digit
checker = False
s = 0
# extract and check each digit
while barcode != 0:
mult = 1 if checker else 3
s += mult * (barcode % 10)
barcode //= 10
checker = not checker
return (10 - (s % 10)) % 10
def is_valid(barcode: int) -> bool:
"""
Checks for length of barcode and last-digit
Returns boolean value of validity of barcode
>>> is_valid(8718452538119)
True
>>> is_valid(87184525)
False
>>> is_valid(87193425381089)
False
>>> is_valid(0)
False
>>> is_valid(dwefgiweuf)
Traceback (most recent call last):
...
NameError: name 'dwefgiweuf' is not defined
"""
return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10
def get_barcode(barcode: str) -> int:
"""
Returns the barcode as an integer
>>> get_barcode("8718452538119")
8718452538119
>>> get_barcode("dwefgiweuf")
Traceback (most recent call last):
...
ValueError: Barcode 'dwefgiweuf' has alphabetic characters.
"""
if str(barcode).isalpha():
raise ValueError(f"Barcode '{barcode}' has alphabetic characters.")
elif int(barcode) < 0:
raise ValueError("The entered barcode has a negative value. Try again.")
else:
return int(barcode)
if __name__ == "__main__":
import doctest
doctest.testmod()
"""
Enter a barcode.
"""
barcode = get_barcode(input("Barcode: ").strip())
if is_valid(barcode):
print(f"'{barcode}' is a valid barcode.")
else:
print(f"'{barcode}' is NOT a valid barcode.")
| """
https://en.wikipedia.org/wiki/Check_digit#Algorithms
"""
def get_check_digit(barcode: int) -> int:
"""
Returns the last digit of barcode by excluding the last digit first
and then computing to reach the actual last digit from the remaining
12 digits.
>>> get_check_digit(8718452538119)
9
>>> get_check_digit(87184523)
5
>>> get_check_digit(87193425381086)
9
>>> [get_check_digit(x) for x in range(0, 100, 10)]
[0, 7, 4, 1, 8, 5, 2, 9, 6, 3]
"""
barcode //= 10 # exclude the last digit
checker = False
s = 0
# extract and check each digit
while barcode != 0:
mult = 1 if checker else 3
s += mult * (barcode % 10)
barcode //= 10
checker = not checker
return (10 - (s % 10)) % 10
def is_valid(barcode: int) -> bool:
"""
Checks for length of barcode and last-digit
Returns boolean value of validity of barcode
>>> is_valid(8718452538119)
True
>>> is_valid(87184525)
False
>>> is_valid(87193425381089)
False
>>> is_valid(0)
False
>>> is_valid(dwefgiweuf)
Traceback (most recent call last):
...
NameError: name 'dwefgiweuf' is not defined
"""
return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10
def get_barcode(barcode: str) -> int:
"""
Returns the barcode as an integer
>>> get_barcode("8718452538119")
8718452538119
>>> get_barcode("dwefgiweuf")
Traceback (most recent call last):
...
ValueError: Barcode 'dwefgiweuf' has alphabetic characters.
"""
if str(barcode).isalpha():
raise ValueError(f"Barcode '{barcode}' has alphabetic characters.")
elif int(barcode) < 0:
raise ValueError("The entered barcode has a negative value. Try again.")
else:
return int(barcode)
if __name__ == "__main__":
import doctest
doctest.testmod()
"""
Enter a barcode.
"""
barcode = get_barcode(input("Barcode: ").strip())
if is_valid(barcode):
print(f"'{barcode}' is a valid barcode.")
else:
print(f"'{barcode}' is NOT a valid barcode.")
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import secrets
from random import shuffle
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation
def password_generator(length: int = 8) -> str:
"""
Password Generator allows you to generate a random password of length N.
>>> len(password_generator())
8
>>> len(password_generator(length=16))
16
>>> len(password_generator(257))
257
>>> len(password_generator(length=0))
0
>>> len(password_generator(-1))
0
"""
chars = ascii_letters + digits + punctuation
return "".join(secrets.choice(chars) for _ in range(length))
# ALTERNATIVE METHODS
# chars_incl= characters that must be in password
# i= how many letters or characters the password length will be
def alternative_password_generator(chars_incl: str, i: int) -> str:
# Password Generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
# Put your code here...
i -= len(chars_incl)
quotient = i // 3
remainder = i % 3
# chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
chars = (
chars_incl
+ random(ascii_letters, quotient + remainder)
+ random(digits, quotient)
+ random(punctuation, quotient)
)
list_of_chars = list(chars)
shuffle(list_of_chars)
return "".join(list_of_chars)
# random is a generalised function for letters, characters and numbers
def random(chars_incl: str, i: int) -> str:
return "".join(secrets.choice(chars_incl) for _ in range(i))
def random_number(chars_incl, i):
pass # Put your code here...
def random_letters(chars_incl, i):
pass # Put your code here...
def random_characters(chars_incl, i):
pass # Put your code here...
# This Will Check Whether A Given Password Is Strong Or Not
# It Follows The Rule that Length Of Password Should Be At Least 8 Characters
# And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character
def is_strong_password(password: str, min_length: int = 8) -> bool:
"""
>>> is_strong_password('Hwea7$2!')
True
>>> is_strong_password('Sh0r1')
False
>>> is_strong_password('Hello123')
False
>>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1')
True
>>> is_strong_password('0')
False
"""
if len(password) < min_length:
# Your Password must be at least 8 characters long
return False
upper = any(char in ascii_uppercase for char in password)
lower = any(char in ascii_lowercase for char in password)
num = any(char in digits for char in password)
spec_char = any(char in punctuation for char in password)
if upper and lower and num and spec_char:
return True
else:
# Passwords should contain UPPERCASE, lowerase
# numbers, and special characters
return False
def main():
length = int(input("Please indicate the max length of your password: ").strip())
chars_incl = input(
"Please indicate the characters that must be in your password: "
).strip()
print("Password generated:", password_generator(length))
print(
"Alternative Password generated:",
alternative_password_generator(chars_incl, length),
)
print("[If you are thinking of using this passsword, You better save it.]")
if __name__ == "__main__":
main()
| import secrets
from random import shuffle
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation
def password_generator(length: int = 8) -> str:
"""
Password Generator allows you to generate a random password of length N.
>>> len(password_generator())
8
>>> len(password_generator(length=16))
16
>>> len(password_generator(257))
257
>>> len(password_generator(length=0))
0
>>> len(password_generator(-1))
0
"""
chars = ascii_letters + digits + punctuation
return "".join(secrets.choice(chars) for _ in range(length))
# ALTERNATIVE METHODS
# chars_incl= characters that must be in password
# i= how many letters or characters the password length will be
def alternative_password_generator(chars_incl: str, i: int) -> str:
# Password Generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
# Put your code here...
i -= len(chars_incl)
quotient = i // 3
remainder = i % 3
# chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
chars = (
chars_incl
+ random(ascii_letters, quotient + remainder)
+ random(digits, quotient)
+ random(punctuation, quotient)
)
list_of_chars = list(chars)
shuffle(list_of_chars)
return "".join(list_of_chars)
# random is a generalised function for letters, characters and numbers
def random(chars_incl: str, i: int) -> str:
return "".join(secrets.choice(chars_incl) for _ in range(i))
def random_number(chars_incl, i):
pass # Put your code here...
def random_letters(chars_incl, i):
pass # Put your code here...
def random_characters(chars_incl, i):
pass # Put your code here...
# This Will Check Whether A Given Password Is Strong Or Not
# It Follows The Rule that Length Of Password Should Be At Least 8 Characters
# And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character
def is_strong_password(password: str, min_length: int = 8) -> bool:
"""
>>> is_strong_password('Hwea7$2!')
True
>>> is_strong_password('Sh0r1')
False
>>> is_strong_password('Hello123')
False
>>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1')
True
>>> is_strong_password('0')
False
"""
if len(password) < min_length:
# Your Password must be at least 8 characters long
return False
upper = any(char in ascii_uppercase for char in password)
lower = any(char in ascii_lowercase for char in password)
num = any(char in digits for char in password)
spec_char = any(char in punctuation for char in password)
if upper and lower and num and spec_char:
return True
else:
# Passwords should contain UPPERCASE, lowerase
# numbers, and special characters
return False
def main():
length = int(input("Please indicate the max length of your password: ").strip())
chars_incl = input(
"Please indicate the characters that must be in your password: "
).strip()
print("Password generated:", password_generator(length))
print(
"Alternative Password generated:",
alternative_password_generator(chars_incl, length),
)
print("[If you are thinking of using this passsword, You better save it.]")
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 31: https://projecteuler.net/problem=31
Coin sums
In England the currency is made up of pound, £, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
Hint:
> There are 100 pence in a pound (£1 = 100p)
> There are coins(in pence) are available: 1, 2, 5, 10, 20, 50, 100 and 200.
> how many different ways you can combine these values to create 200 pence.
Example:
to make 6p there are 5 ways
1,1,1,1,1,1
1,1,1,1,2
1,1,2,2
2,2,2
1,5
to make 5p there are 4 ways
1,1,1,1,1
1,1,1,2
1,2,2
5
"""
def solution(pence: int = 200) -> int:
"""Returns the number of different ways to make X pence using any number of coins.
The solution is based on dynamic programming paradigm in a bottom-up fashion.
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
coins = [1, 2, 5, 10, 20, 50, 100, 200]
number_of_ways = [0] * (pence + 1)
number_of_ways[0] = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(coin, pence + 1, 1):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73682
| """
Problem 31: https://projecteuler.net/problem=31
Coin sums
In England the currency is made up of pound, £, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
Hint:
> There are 100 pence in a pound (£1 = 100p)
> There are coins(in pence) are available: 1, 2, 5, 10, 20, 50, 100 and 200.
> how many different ways you can combine these values to create 200 pence.
Example:
to make 6p there are 5 ways
1,1,1,1,1,1
1,1,1,1,2
1,1,2,2
2,2,2
1,5
to make 5p there are 4 ways
1,1,1,1,1
1,1,1,2
1,2,2
5
"""
def solution(pence: int = 200) -> int:
"""Returns the number of different ways to make X pence using any number of coins.
The solution is based on dynamic programming paradigm in a bottom-up fashion.
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
coins = [1, 2, 5, 10, 20, 50, 100, 200]
number_of_ways = [0] * (pence + 1)
number_of_ways[0] = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(coin, pence + 1, 1):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73682
| -1 |
TheAlgorithms/Python | 7,984 | fix: no implicit optional | https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2022-11-15T03:45:16Z" | "2022-11-15T13:55:14Z" | 316e71b03448b6adb8a32d96cb4d6488ee7b7787 | 3bf86b91e7d438eb2b9ecbab68060c007d270332 | fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html
### Describe your change:
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [ ] This pull request is all my own work -- I have not plagiarized.
* [ ] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
|