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 | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler 62
https://projecteuler.net/problem=62
The cube, 41063625 (345^3), can be permuted to produce two other cubes:
56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube
which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are
cube.
"""
from collections import defaultdict
def solution(max_base: int = 5) -> int:
"""
Iterate through every possible cube and sort the cube's digits in
ascending order. Sorting maintains an ordering of the digits that allows
you to compare permutations. Store each sorted sequence of digits in a
dictionary, whose key is the sequence of digits and value is a list of
numbers that are the base of the cube.
Once you find 5 numbers that produce the same sequence of digits, return
the smallest one, which is at index 0 since we insert each base number in
ascending order.
>>> solution(2)
125
>>> solution(3)
41063625
"""
freqs = defaultdict(list)
num = 0
while True:
digits = get_digits(num)
freqs[digits].append(num)
if len(freqs[digits]) == max_base:
base = freqs[digits][0] ** 3
return base
num += 1
def get_digits(num: int) -> str:
"""
Computes the sorted sequence of digits of the cube of num.
>>> get_digits(3)
'27'
>>> get_digits(99)
'027999'
>>> get_digits(123)
'0166788'
"""
return "".join(sorted(str(num**3)))
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler 62
https://projecteuler.net/problem=62
The cube, 41063625 (345^3), can be permuted to produce two other cubes:
56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube
which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are
cube.
"""
from collections import defaultdict
def solution(max_base: int = 5) -> int:
"""
Iterate through every possible cube and sort the cube's digits in
ascending order. Sorting maintains an ordering of the digits that allows
you to compare permutations. Store each sorted sequence of digits in a
dictionary, whose key is the sequence of digits and value is a list of
numbers that are the base of the cube.
Once you find 5 numbers that produce the same sequence of digits, return
the smallest one, which is at index 0 since we insert each base number in
ascending order.
>>> solution(2)
125
>>> solution(3)
41063625
"""
freqs = defaultdict(list)
num = 0
while True:
digits = get_digits(num)
freqs[digits].append(num)
if len(freqs[digits]) == max_base:
base = freqs[digits][0] ** 3
return base
num += 1
def get_digits(num: int) -> str:
"""
Computes the sorted sequence of digits of the cube of num.
>>> get_digits(3)
'27'
>>> get_digits(99)
'027999'
>>> get_digits(123)
'0166788'
"""
return "".join(sorted(str(num**3)))
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import math
from collections.abc import Iterator
from itertools import takewhile
def is_prime(number: int) -> bool:
"""Checks to see if a number is a prime in O(sqrt(n)).
A number is prime if it has exactly two factors: 1 and itself.
Returns boolean representing primality of given number num (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def prime_generator() -> Iterator[int]:
"""
Generate a list sequence of prime numbers
"""
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
"""
return sum(takewhile(lambda x: x < n, prime_generator()))
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import math
from collections.abc import Iterator
from itertools import takewhile
def is_prime(number: int) -> bool:
"""Checks to see if a number is a prime in O(sqrt(n)).
A number is prime if it has exactly two factors: 1 and itself.
Returns boolean representing primality of given number num (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def prime_generator() -> Iterator[int]:
"""
Generate a list sequence of prime numbers
"""
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
"""
return sum(takewhile(lambda x: x < n, prime_generator()))
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Perceptron
w = w + N * (d(k) - y) * x(k)
Using perceptron network for oil analysis, with Measuring of 3 parameters
that represent chemical characteristics we can classify the oil, in p1 or p2
p1 = -1
p2 = 1
"""
import random
class Perceptron:
def __init__(
self,
sample: list[list[float]],
target: list[int],
learning_rate: float = 0.01,
epoch_number: int = 1000,
bias: float = -1,
) -> None:
"""
Initializes a Perceptron network for oil analysis
:param sample: sample dataset of 3 parameters with shape [30,3]
:param target: variable for classification with two possible states -1 or 1
:param learning_rate: learning rate used in optimizing.
:param epoch_number: number of epochs to train network on.
:param bias: bias value for the network.
>>> p = Perceptron([], (0, 1, 2))
Traceback (most recent call last):
...
ValueError: Sample data can not be empty
>>> p = Perceptron(([0], 1, 2), [])
Traceback (most recent call last):
...
ValueError: Target data can not be empty
>>> p = Perceptron(([0], 1, 2), (0, 1))
Traceback (most recent call last):
...
ValueError: Sample data and Target data do not have matching lengths
"""
self.sample = sample
if len(self.sample) == 0:
raise ValueError("Sample data can not be empty")
self.target = target
if len(self.target) == 0:
raise ValueError("Target data can not be empty")
if len(self.sample) != len(self.target):
raise ValueError("Sample data and Target data do not have matching lengths")
self.learning_rate = learning_rate
self.epoch_number = epoch_number
self.bias = bias
self.number_sample = len(sample)
self.col_sample = len(sample[0]) # number of columns in dataset
self.weight: list = []
def training(self) -> None:
"""
Trains perceptron for epochs <= given number of epochs
:return: None
>>> data = [[2.0149, 0.6192, 10.9263]]
>>> targets = [-1]
>>> perceptron = Perceptron(data,targets)
>>> perceptron.training() # doctest: +ELLIPSIS
('\\nEpoch:\\n', ...)
...
"""
for sample in self.sample:
sample.insert(0, self.bias)
for _ in range(self.col_sample):
self.weight.append(random.random())
self.weight.insert(0, self.bias)
epoch_count = 0
while True:
has_misclassified = False
for i in range(self.number_sample):
u = 0
for j in range(self.col_sample + 1):
u = u + self.weight[j] * self.sample[i][j]
y = self.sign(u)
if y != self.target[i]:
for j in range(self.col_sample + 1):
self.weight[j] = (
self.weight[j]
+ self.learning_rate
* (self.target[i] - y)
* self.sample[i][j]
)
has_misclassified = True
# print('Epoch: \n',epoch_count)
epoch_count = epoch_count + 1
# if you want control the epoch or just by error
if not has_misclassified:
print(("\nEpoch:\n", epoch_count))
print("------------------------\n")
# if epoch_count > self.epoch_number or not error:
break
def sort(self, sample: list[float]) -> None:
"""
:param sample: example row to classify as P1 or P2
:return: None
>>> data = [[2.0149, 0.6192, 10.9263]]
>>> targets = [-1]
>>> perceptron = Perceptron(data,targets)
>>> perceptron.training() # doctest: +ELLIPSIS
('\\nEpoch:\\n', ...)
...
>>> perceptron.sort([-0.6508, 0.1097, 4.0009]) # doctest: +ELLIPSIS
('Sample: ', ...)
classification: P...
"""
if len(self.sample) == 0:
raise ValueError("Sample data can not be empty")
sample.insert(0, self.bias)
u = 0
for i in range(self.col_sample + 1):
u = u + self.weight[i] * sample[i]
y = self.sign(u)
if y == -1:
print(("Sample: ", sample))
print("classification: P1")
else:
print(("Sample: ", sample))
print("classification: P2")
def sign(self, u: float) -> int:
"""
threshold function for classification
:param u: input number
:return: 1 if the input is greater than 0, otherwise -1
>>> data = [[0],[-0.5],[0.5]]
>>> targets = [1,-1,1]
>>> perceptron = Perceptron(data,targets)
>>> perceptron.sign(0)
1
>>> perceptron.sign(-0.5)
-1
>>> perceptron.sign(0.5)
1
"""
return 1 if u >= 0 else -1
samples = [
[-0.6508, 0.1097, 4.0009],
[-1.4492, 0.8896, 4.4005],
[2.0850, 0.6876, 12.0710],
[0.2626, 1.1476, 7.7985],
[0.6418, 1.0234, 7.0427],
[0.2569, 0.6730, 8.3265],
[1.1155, 0.6043, 7.4446],
[0.0914, 0.3399, 7.0677],
[0.0121, 0.5256, 4.6316],
[-0.0429, 0.4660, 5.4323],
[0.4340, 0.6870, 8.2287],
[0.2735, 1.0287, 7.1934],
[0.4839, 0.4851, 7.4850],
[0.4089, -0.1267, 5.5019],
[1.4391, 0.1614, 8.5843],
[-0.9115, -0.1973, 2.1962],
[0.3654, 1.0475, 7.4858],
[0.2144, 0.7515, 7.1699],
[0.2013, 1.0014, 6.5489],
[0.6483, 0.2183, 5.8991],
[-0.1147, 0.2242, 7.2435],
[-0.7970, 0.8795, 3.8762],
[-1.0625, 0.6366, 2.4707],
[0.5307, 0.1285, 5.6883],
[-1.2200, 0.7777, 1.7252],
[0.3957, 0.1076, 5.6623],
[-0.1013, 0.5989, 7.1812],
[2.4482, 0.9455, 11.2095],
[2.0149, 0.6192, 10.9263],
[0.2012, 0.2611, 5.4631],
]
target = [
-1,
-1,
-1,
1,
1,
-1,
1,
-1,
1,
1,
-1,
1,
-1,
-1,
-1,
-1,
1,
1,
1,
1,
-1,
1,
1,
1,
1,
-1,
-1,
1,
-1,
1,
]
if __name__ == "__main__":
import doctest
doctest.testmod()
network = Perceptron(
sample=samples, target=target, learning_rate=0.01, epoch_number=1000, bias=-1
)
network.training()
print("Finished training perceptron")
print("Enter values to predict or q to exit")
while True:
sample: list = []
for i in range(len(samples[0])):
user_input = input("value: ").strip()
if user_input == "q":
break
observation = float(user_input)
sample.insert(i, observation)
network.sort(sample)
| """
Perceptron
w = w + N * (d(k) - y) * x(k)
Using perceptron network for oil analysis, with Measuring of 3 parameters
that represent chemical characteristics we can classify the oil, in p1 or p2
p1 = -1
p2 = 1
"""
import random
class Perceptron:
def __init__(
self,
sample: list[list[float]],
target: list[int],
learning_rate: float = 0.01,
epoch_number: int = 1000,
bias: float = -1,
) -> None:
"""
Initializes a Perceptron network for oil analysis
:param sample: sample dataset of 3 parameters with shape [30,3]
:param target: variable for classification with two possible states -1 or 1
:param learning_rate: learning rate used in optimizing.
:param epoch_number: number of epochs to train network on.
:param bias: bias value for the network.
>>> p = Perceptron([], (0, 1, 2))
Traceback (most recent call last):
...
ValueError: Sample data can not be empty
>>> p = Perceptron(([0], 1, 2), [])
Traceback (most recent call last):
...
ValueError: Target data can not be empty
>>> p = Perceptron(([0], 1, 2), (0, 1))
Traceback (most recent call last):
...
ValueError: Sample data and Target data do not have matching lengths
"""
self.sample = sample
if len(self.sample) == 0:
raise ValueError("Sample data can not be empty")
self.target = target
if len(self.target) == 0:
raise ValueError("Target data can not be empty")
if len(self.sample) != len(self.target):
raise ValueError("Sample data and Target data do not have matching lengths")
self.learning_rate = learning_rate
self.epoch_number = epoch_number
self.bias = bias
self.number_sample = len(sample)
self.col_sample = len(sample[0]) # number of columns in dataset
self.weight: list = []
def training(self) -> None:
"""
Trains perceptron for epochs <= given number of epochs
:return: None
>>> data = [[2.0149, 0.6192, 10.9263]]
>>> targets = [-1]
>>> perceptron = Perceptron(data,targets)
>>> perceptron.training() # doctest: +ELLIPSIS
('\\nEpoch:\\n', ...)
...
"""
for sample in self.sample:
sample.insert(0, self.bias)
for _ in range(self.col_sample):
self.weight.append(random.random())
self.weight.insert(0, self.bias)
epoch_count = 0
while True:
has_misclassified = False
for i in range(self.number_sample):
u = 0
for j in range(self.col_sample + 1):
u = u + self.weight[j] * self.sample[i][j]
y = self.sign(u)
if y != self.target[i]:
for j in range(self.col_sample + 1):
self.weight[j] = (
self.weight[j]
+ self.learning_rate
* (self.target[i] - y)
* self.sample[i][j]
)
has_misclassified = True
# print('Epoch: \n',epoch_count)
epoch_count = epoch_count + 1
# if you want control the epoch or just by error
if not has_misclassified:
print(("\nEpoch:\n", epoch_count))
print("------------------------\n")
# if epoch_count > self.epoch_number or not error:
break
def sort(self, sample: list[float]) -> None:
"""
:param sample: example row to classify as P1 or P2
:return: None
>>> data = [[2.0149, 0.6192, 10.9263]]
>>> targets = [-1]
>>> perceptron = Perceptron(data,targets)
>>> perceptron.training() # doctest: +ELLIPSIS
('\\nEpoch:\\n', ...)
...
>>> perceptron.sort([-0.6508, 0.1097, 4.0009]) # doctest: +ELLIPSIS
('Sample: ', ...)
classification: P...
"""
if len(self.sample) == 0:
raise ValueError("Sample data can not be empty")
sample.insert(0, self.bias)
u = 0
for i in range(self.col_sample + 1):
u = u + self.weight[i] * sample[i]
y = self.sign(u)
if y == -1:
print(("Sample: ", sample))
print("classification: P1")
else:
print(("Sample: ", sample))
print("classification: P2")
def sign(self, u: float) -> int:
"""
threshold function for classification
:param u: input number
:return: 1 if the input is greater than 0, otherwise -1
>>> data = [[0],[-0.5],[0.5]]
>>> targets = [1,-1,1]
>>> perceptron = Perceptron(data,targets)
>>> perceptron.sign(0)
1
>>> perceptron.sign(-0.5)
-1
>>> perceptron.sign(0.5)
1
"""
return 1 if u >= 0 else -1
samples = [
[-0.6508, 0.1097, 4.0009],
[-1.4492, 0.8896, 4.4005],
[2.0850, 0.6876, 12.0710],
[0.2626, 1.1476, 7.7985],
[0.6418, 1.0234, 7.0427],
[0.2569, 0.6730, 8.3265],
[1.1155, 0.6043, 7.4446],
[0.0914, 0.3399, 7.0677],
[0.0121, 0.5256, 4.6316],
[-0.0429, 0.4660, 5.4323],
[0.4340, 0.6870, 8.2287],
[0.2735, 1.0287, 7.1934],
[0.4839, 0.4851, 7.4850],
[0.4089, -0.1267, 5.5019],
[1.4391, 0.1614, 8.5843],
[-0.9115, -0.1973, 2.1962],
[0.3654, 1.0475, 7.4858],
[0.2144, 0.7515, 7.1699],
[0.2013, 1.0014, 6.5489],
[0.6483, 0.2183, 5.8991],
[-0.1147, 0.2242, 7.2435],
[-0.7970, 0.8795, 3.8762],
[-1.0625, 0.6366, 2.4707],
[0.5307, 0.1285, 5.6883],
[-1.2200, 0.7777, 1.7252],
[0.3957, 0.1076, 5.6623],
[-0.1013, 0.5989, 7.1812],
[2.4482, 0.9455, 11.2095],
[2.0149, 0.6192, 10.9263],
[0.2012, 0.2611, 5.4631],
]
target = [
-1,
-1,
-1,
1,
1,
-1,
1,
-1,
1,
1,
-1,
1,
-1,
-1,
-1,
-1,
1,
1,
1,
1,
-1,
1,
1,
1,
1,
-1,
-1,
1,
-1,
1,
]
if __name__ == "__main__":
import doctest
doctest.testmod()
network = Perceptron(
sample=samples, target=target, learning_rate=0.01, epoch_number=1000, bias=-1
)
network.training()
print("Finished training perceptron")
print("Enter values to predict or q to exit")
while True:
sample: list = []
for i in range(len(samples[0])):
user_input = input("value: ").strip()
if user_input == "q":
break
observation = float(user_input)
sample.insert(i, observation)
network.sort(sample)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
In this problem, we want to determine all possible combinations of k
numbers out of 1 ... n. We use backtracking to solve this problem.
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
"""
from __future__ import annotations
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
"""
>>> generate_all_combinations(n=4, k=2)
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
"""
result: list[list[int]] = []
create_all_state(1, n, k, [], result)
return result
def create_all_state(
increment: int,
total_number: int,
level: int,
current_list: list[int],
total_list: list[list[int]],
) -> None:
if level == 0:
total_list.append(current_list[:])
return
for i in range(increment, total_number - level + 2):
current_list.append(i)
create_all_state(i + 1, total_number, level - 1, current_list, total_list)
current_list.pop()
def print_all_state(total_list: list[list[int]]) -> None:
for i in total_list:
print(*i)
if __name__ == "__main__":
n = 4
k = 2
total_list = generate_all_combinations(n, k)
print_all_state(total_list)
| """
In this problem, we want to determine all possible combinations of k
numbers out of 1 ... n. We use backtracking to solve this problem.
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
"""
from __future__ import annotations
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
"""
>>> generate_all_combinations(n=4, k=2)
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
"""
result: list[list[int]] = []
create_all_state(1, n, k, [], result)
return result
def create_all_state(
increment: int,
total_number: int,
level: int,
current_list: list[int],
total_list: list[list[int]],
) -> None:
if level == 0:
total_list.append(current_list[:])
return
for i in range(increment, total_number - level + 2):
current_list.append(i)
create_all_state(i + 1, total_number, level - 1, current_list, total_list)
current_list.pop()
def print_all_state(total_list: list[list[int]]) -> None:
for i in total_list:
print(*i)
if __name__ == "__main__":
n = 4
k = 2
total_list = generate_all_combinations(n, k)
print_all_state(total_list)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Given an array of integers and another integer target,
we are required to find a triplet from the array such that it's sum is equal to
the target.
"""
from __future__ import annotations
from itertools import permutations
from random import randint
from timeit import repeat
def make_dataset() -> tuple[list[int], int]:
arr = [randint(-1000, 1000) for i in range(10)]
r = randint(-5000, 5000)
return (arr, r)
dataset = make_dataset()
def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]:
"""
Returns a triplet in the array with sum equal to target,
else (0, 0, 0).
>>> triplet_sum1([13, 29, 7, 23, 5], 35)
(5, 7, 23)
>>> triplet_sum1([37, 9, 19, 50, 44], 65)
(9, 19, 37)
>>> arr = [6, 47, 27, 1, 15]
>>> target = 11
>>> triplet_sum1(arr, target)
(0, 0, 0)
"""
for triplet in permutations(arr, 3):
if sum(triplet) == target:
return tuple(sorted(triplet))
return (0, 0, 0)
def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]:
"""
Returns a triplet in the array with sum equal to target,
else (0, 0, 0).
>>> triplet_sum2([13, 29, 7, 23, 5], 35)
(5, 7, 23)
>>> triplet_sum2([37, 9, 19, 50, 44], 65)
(9, 19, 37)
>>> arr = [6, 47, 27, 1, 15]
>>> target = 11
>>> triplet_sum2(arr, target)
(0, 0, 0)
"""
arr.sort()
n = len(arr)
for i in range(n - 1):
left, right = i + 1, n - 1
while left < right:
if arr[i] + arr[left] + arr[right] == target:
return (arr[i], arr[left], arr[right])
elif arr[i] + arr[left] + arr[right] < target:
left += 1
elif arr[i] + arr[left] + arr[right] > target:
right -= 1
return (0, 0, 0)
def solution_times() -> tuple[float, float]:
setup_code = """
from __main__ import dataset, triplet_sum1, triplet_sum2
"""
test_code1 = """
triplet_sum1(*dataset)
"""
test_code2 = """
triplet_sum2(*dataset)
"""
times1 = repeat(setup=setup_code, stmt=test_code1, repeat=5, number=10000)
times2 = repeat(setup=setup_code, stmt=test_code2, repeat=5, number=10000)
return (min(times1), min(times2))
if __name__ == "__main__":
from doctest import testmod
testmod()
times = solution_times()
print(f"The time for naive implementation is {times[0]}.")
print(f"The time for optimized implementation is {times[1]}.")
| """
Given an array of integers and another integer target,
we are required to find a triplet from the array such that it's sum is equal to
the target.
"""
from __future__ import annotations
from itertools import permutations
from random import randint
from timeit import repeat
def make_dataset() -> tuple[list[int], int]:
arr = [randint(-1000, 1000) for i in range(10)]
r = randint(-5000, 5000)
return (arr, r)
dataset = make_dataset()
def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]:
"""
Returns a triplet in the array with sum equal to target,
else (0, 0, 0).
>>> triplet_sum1([13, 29, 7, 23, 5], 35)
(5, 7, 23)
>>> triplet_sum1([37, 9, 19, 50, 44], 65)
(9, 19, 37)
>>> arr = [6, 47, 27, 1, 15]
>>> target = 11
>>> triplet_sum1(arr, target)
(0, 0, 0)
"""
for triplet in permutations(arr, 3):
if sum(triplet) == target:
return tuple(sorted(triplet))
return (0, 0, 0)
def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]:
"""
Returns a triplet in the array with sum equal to target,
else (0, 0, 0).
>>> triplet_sum2([13, 29, 7, 23, 5], 35)
(5, 7, 23)
>>> triplet_sum2([37, 9, 19, 50, 44], 65)
(9, 19, 37)
>>> arr = [6, 47, 27, 1, 15]
>>> target = 11
>>> triplet_sum2(arr, target)
(0, 0, 0)
"""
arr.sort()
n = len(arr)
for i in range(n - 1):
left, right = i + 1, n - 1
while left < right:
if arr[i] + arr[left] + arr[right] == target:
return (arr[i], arr[left], arr[right])
elif arr[i] + arr[left] + arr[right] < target:
left += 1
elif arr[i] + arr[left] + arr[right] > target:
right -= 1
return (0, 0, 0)
def solution_times() -> tuple[float, float]:
setup_code = """
from __main__ import dataset, triplet_sum1, triplet_sum2
"""
test_code1 = """
triplet_sum1(*dataset)
"""
test_code2 = """
triplet_sum2(*dataset)
"""
times1 = repeat(setup=setup_code, stmt=test_code1, repeat=5, number=10000)
times2 = repeat(setup=setup_code, stmt=test_code2, repeat=5, number=10000)
return (min(times1), min(times2))
if __name__ == "__main__":
from doctest import testmod
testmod()
times = solution_times()
print(f"The time for naive implementation is {times[0]}.")
print(f"The time for optimized implementation is {times[1]}.")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from datetime import datetime
import requests
from bs4 import BeautifulSoup
if __name__ == "__main__":
url = input("Enter image url: ").strip()
print(f"Downloading image from {url} ...")
soup = BeautifulSoup(requests.get(url).content, "html.parser")
# The image URL is in the content field of the first meta tag with property og:image
image_url = soup.find("meta", {"property": "og:image"})["content"]
image_data = requests.get(image_url).content
file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg"
with open(file_name, "wb") as fp:
fp.write(image_data)
print(f"Done. Image saved to disk as {file_name}.")
| from datetime import datetime
import requests
from bs4 import BeautifulSoup
if __name__ == "__main__":
url = input("Enter image url: ").strip()
print(f"Downloading image from {url} ...")
soup = BeautifulSoup(requests.get(url).content, "html.parser")
# The image URL is in the content field of the first meta tag with property og:image
image_url = soup.find("meta", {"property": "og:image"})["content"]
image_data = requests.get(image_url).content
file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg"
with open(file_name, "wb") as fp:
fp.write(image_data)
print(f"Done. Image saved to disk as {file_name}.")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Conway's Game of Life implemented in Python.
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
"""
from __future__ import annotations
from PIL import Image
# Define glider example
GLIDER = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
]
# Define blinker example
BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
def new_generation(cells: list[list[int]]) -> list[list[int]]:
"""
Generates the next generation for a given state of Conway's Game of Life.
>>> new_generation(BLINKER)
[[0, 0, 0], [1, 1, 1], [0, 0, 0]]
"""
next_generation = []
for i in range(len(cells)):
next_generation_row = []
for j in range(len(cells[i])):
# Get the number of live neighbours
neighbour_count = 0
if i > 0 and j > 0:
neighbour_count += cells[i - 1][j - 1]
if i > 0:
neighbour_count += cells[i - 1][j]
if i > 0 and j < len(cells[i]) - 1:
neighbour_count += cells[i - 1][j + 1]
if j > 0:
neighbour_count += cells[i][j - 1]
if j < len(cells[i]) - 1:
neighbour_count += cells[i][j + 1]
if i < len(cells) - 1 and j > 0:
neighbour_count += cells[i + 1][j - 1]
if i < len(cells) - 1:
neighbour_count += cells[i + 1][j]
if i < len(cells) - 1 and j < len(cells[i]) - 1:
neighbour_count += cells[i + 1][j + 1]
# Rules of the game of life (excerpt from Wikipedia):
# 1. Any live cell with two or three live neighbours survives.
# 2. Any dead cell with three live neighbours becomes a live cell.
# 3. All other live cells die in the next generation.
# Similarly, all other dead cells stay dead.
alive = cells[i][j] == 1
if (
(alive and 2 <= neighbour_count <= 3)
or not alive
and neighbour_count == 3
):
next_generation_row.append(1)
else:
next_generation_row.append(0)
next_generation.append(next_generation_row)
return next_generation
def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]:
"""
Generates a list of images of subsequent Game of Life states.
"""
images = []
for _ in range(frames):
# Create output image
img = Image.new("RGB", (len(cells[0]), len(cells)))
pixels = img.load()
# Save cells to image
for x in range(len(cells)):
for y in range(len(cells[0])):
colour = 255 - cells[y][x] * 255
pixels[x, y] = (colour, colour, colour)
# Save image
images.append(img)
cells = new_generation(cells)
return images
if __name__ == "__main__":
images = generate_images(GLIDER, 16)
images[0].save("out.gif", save_all=True, append_images=images[1:])
| """
Conway's Game of Life implemented in Python.
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
"""
from __future__ import annotations
from PIL import Image
# Define glider example
GLIDER = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
]
# Define blinker example
BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
def new_generation(cells: list[list[int]]) -> list[list[int]]:
"""
Generates the next generation for a given state of Conway's Game of Life.
>>> new_generation(BLINKER)
[[0, 0, 0], [1, 1, 1], [0, 0, 0]]
"""
next_generation = []
for i in range(len(cells)):
next_generation_row = []
for j in range(len(cells[i])):
# Get the number of live neighbours
neighbour_count = 0
if i > 0 and j > 0:
neighbour_count += cells[i - 1][j - 1]
if i > 0:
neighbour_count += cells[i - 1][j]
if i > 0 and j < len(cells[i]) - 1:
neighbour_count += cells[i - 1][j + 1]
if j > 0:
neighbour_count += cells[i][j - 1]
if j < len(cells[i]) - 1:
neighbour_count += cells[i][j + 1]
if i < len(cells) - 1 and j > 0:
neighbour_count += cells[i + 1][j - 1]
if i < len(cells) - 1:
neighbour_count += cells[i + 1][j]
if i < len(cells) - 1 and j < len(cells[i]) - 1:
neighbour_count += cells[i + 1][j + 1]
# Rules of the game of life (excerpt from Wikipedia):
# 1. Any live cell with two or three live neighbours survives.
# 2. Any dead cell with three live neighbours becomes a live cell.
# 3. All other live cells die in the next generation.
# Similarly, all other dead cells stay dead.
alive = cells[i][j] == 1
if (
(alive and 2 <= neighbour_count <= 3)
or not alive
and neighbour_count == 3
):
next_generation_row.append(1)
else:
next_generation_row.append(0)
next_generation.append(next_generation_row)
return next_generation
def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]:
"""
Generates a list of images of subsequent Game of Life states.
"""
images = []
for _ in range(frames):
# Create output image
img = Image.new("RGB", (len(cells[0]), len(cells)))
pixels = img.load()
# Save cells to image
for x in range(len(cells)):
for y in range(len(cells[0])):
colour = 255 - cells[y][x] * 255
pixels[x, y] = (colour, colour, colour)
# Save image
images.append(img)
cells = new_generation(cells)
return images
if __name__ == "__main__":
images = generate_images(GLIDER, 16)
images[0].save("out.gif", save_all=True, append_images=images[1:])
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
This is pure Python implementation of Tabu search algorithm for a Travelling Salesman
Problem, that the distances between the cities are symmetric (the distance between city
'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the
distance between them is represented by the weight of the ark between the nodes.
The .txt file with the graph has the form:
node1 node2 distance_between_node1_and_node2
node1 node3 distance_between_node1_and_node3
...
Be careful node1, node2 and the distance between them, must exist only once. This means
in the .txt file should not exist:
node1 node2 distance_between_node1_and_node2
node2 node1 distance_between_node2_and_node1
For pytests run following command:
pytest
For manual testing run:
python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search \
-s size_of_tabu_search
e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
"""
import argparse
import copy
def generate_neighbours(path):
"""
Pure implementation of generating a dictionary of neighbors and the cost with each
neighbor, given a path file that includes a graph.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:return dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
Example of dict_of_neighbours:
>>) dict_of_neighbours[a]
[[b,20],[c,18],[d,22],[e,26]]
This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
the node 'e' with distance 26.
"""
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = []
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = []
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
"""
Pure implementation of generating the first solution for the Tabu search to start,
with the redundant resolution strategy. That means that we start from the starting
node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node
(let's assume is node 'c'), then we go to the nearest city of the node 'c', etc.
till we have visited all cities and return to the starting node.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:return distance_of_first_solution: The total distance that Travelling Salesman
will travel, if he follows the path in first_solution.
"""
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
"""
Pure implementation of generating the neighborhood (sorted by total distance of
each solution from lowest to highest) of a solution with 1-1 exchange method, that
means we exchange each node in a solution with each other node and generating a
number of solution named neighborhood.
:param solution: The solution in which we want to find the neighborhood.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return neighborhood_of_solution: A list that includes the solutions and the total
distance of each solution (in form of list) that are produced with 1-1 exchange
from the solution that the method took as an input
Example:
>>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
... ) # doctest: +NORMALIZE_WHITESPACE
[['a', 'e', 'b', 'd', 'c', 'a', 90],
['a', 'c', 'd', 'b', 'e', 'a', 90],
['a', 'd', 'b', 'c', 'e', 'a', 93],
['a', 'c', 'b', 'e', 'd', 'a', 102],
['a', 'c', 'e', 'd', 'b', 'a', 113],
['a', 'b', 'c', 'd', 'e', 'a', 119]]
"""
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list])
return neighborhood_of_solution
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
"""
Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
Python.
:param first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:param distance_of_first_solution: The total distance that Travelling Salesman will
travel, if he follows the path in first_solution.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:param iters: The number of iterations that Tabu search will execute.
:param size: The size of Tabu List.
:return best_solution_ever: The solution with the lowest distance that occurred
during the execution of Tabu search.
:return best_cost: The total distance that Travelling Salesman will travel, if he
follows the path in best_solution ever.
"""
count = 1
solution = first_solution
tabu_list = []
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args())
| """
This is pure Python implementation of Tabu search algorithm for a Travelling Salesman
Problem, that the distances between the cities are symmetric (the distance between city
'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the
distance between them is represented by the weight of the ark between the nodes.
The .txt file with the graph has the form:
node1 node2 distance_between_node1_and_node2
node1 node3 distance_between_node1_and_node3
...
Be careful node1, node2 and the distance between them, must exist only once. This means
in the .txt file should not exist:
node1 node2 distance_between_node1_and_node2
node2 node1 distance_between_node2_and_node1
For pytests run following command:
pytest
For manual testing run:
python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search \
-s size_of_tabu_search
e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
"""
import argparse
import copy
def generate_neighbours(path):
"""
Pure implementation of generating a dictionary of neighbors and the cost with each
neighbor, given a path file that includes a graph.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:return dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
Example of dict_of_neighbours:
>>) dict_of_neighbours[a]
[[b,20],[c,18],[d,22],[e,26]]
This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
the node 'e' with distance 26.
"""
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = []
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = []
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
"""
Pure implementation of generating the first solution for the Tabu search to start,
with the redundant resolution strategy. That means that we start from the starting
node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node
(let's assume is node 'c'), then we go to the nearest city of the node 'c', etc.
till we have visited all cities and return to the starting node.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:return distance_of_first_solution: The total distance that Travelling Salesman
will travel, if he follows the path in first_solution.
"""
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
"""
Pure implementation of generating the neighborhood (sorted by total distance of
each solution from lowest to highest) of a solution with 1-1 exchange method, that
means we exchange each node in a solution with each other node and generating a
number of solution named neighborhood.
:param solution: The solution in which we want to find the neighborhood.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return neighborhood_of_solution: A list that includes the solutions and the total
distance of each solution (in form of list) that are produced with 1-1 exchange
from the solution that the method took as an input
Example:
>>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
... ) # doctest: +NORMALIZE_WHITESPACE
[['a', 'e', 'b', 'd', 'c', 'a', 90],
['a', 'c', 'd', 'b', 'e', 'a', 90],
['a', 'd', 'b', 'c', 'e', 'a', 93],
['a', 'c', 'b', 'e', 'd', 'a', 102],
['a', 'c', 'e', 'd', 'b', 'a', 113],
['a', 'b', 'c', 'd', 'e', 'a', 119]]
"""
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list])
return neighborhood_of_solution
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
"""
Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
Python.
:param first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:param distance_of_first_solution: The total distance that Travelling Salesman will
travel, if he follows the path in first_solution.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:param iters: The number of iterations that Tabu search will execute.
:param size: The size of Tabu List.
:return best_solution_ever: The solution with the lowest distance that occurred
during the execution of Tabu search.
:return best_cost: The total distance that Travelling Salesman will travel, if he
follows the path in best_solution ever.
"""
count = 1
solution = first_solution
tabu_list = []
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args())
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 2: https://projecteuler.net/problem=2
Even Fibonacci Numbers
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
References:
- https://en.wikipedia.org/wiki/Fibonacci_number
"""
def solution(n: int = 4000000) -> int:
"""
Returns the sum of all even fibonacci sequence elements that are lower
or equal to n.
>>> solution(10)
10
>>> solution(15)
10
>>> solution(2)
2
>>> solution(1)
0
>>> solution(34)
44
"""
even_fibs = []
a, b = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(b)
a, b = b, a + b
return sum(even_fibs)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 2: https://projecteuler.net/problem=2
Even Fibonacci Numbers
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
References:
- https://en.wikipedia.org/wiki/Fibonacci_number
"""
def solution(n: int = 4000000) -> int:
"""
Returns the sum of all even fibonacci sequence elements that are lower
or equal to n.
>>> solution(10)
10
>>> solution(15)
10
>>> solution(2)
2
>>> solution(1)
0
>>> solution(34)
44
"""
even_fibs = []
a, b = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(b)
a, b = b, a + b
return sum(even_fibs)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Amicable Numbers
Problem 21
Let d(n) be defined as the sum of proper divisors of n (numbers less than n
which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and
each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and
142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
"""
from math import sqrt
def sum_of_divisors(n: int) -> int:
total = 0
for i in range(1, int(sqrt(n) + 1)):
if n % i == 0 and i != sqrt(n):
total += i + n // i
elif i == sqrt(n):
total += i
return total - n
def solution(n: int = 10000) -> int:
"""Returns the sum of all the amicable numbers under n.
>>> solution(10000)
31626
>>> solution(5000)
8442
>>> solution(1000)
504
>>> solution(100)
0
>>> solution(50)
0
"""
total = sum(
i
for i in range(1, n)
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
)
return total
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| """
Amicable Numbers
Problem 21
Let d(n) be defined as the sum of proper divisors of n (numbers less than n
which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and
each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and
142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
"""
from math import sqrt
def sum_of_divisors(n: int) -> int:
total = 0
for i in range(1, int(sqrt(n) + 1)):
if n % i == 0 and i != sqrt(n):
total += i + n // i
elif i == sqrt(n):
total += i
return total - n
def solution(n: int = 10000) -> int:
"""Returns the sum of all the amicable numbers under n.
>>> solution(10000)
31626
>>> solution(5000)
8442
>>> solution(1000)
504
>>> solution(100)
0
>>> solution(50)
0
"""
total = sum(
i
for i in range(1, n)
if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i
)
return total
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Author Anurag Kumar | [email protected] | git/anuragkumarak95
Simple example of fractal generation using recursion.
What is the Sierpiński Triangle?
The Sierpiński triangle (sometimes spelled Sierpinski), also called the
Sierpiński gasket or Sierpiński sieve, is a fractal attractive fixed set with
the overall shape of an equilateral triangle, subdivided recursively into
smaller equilateral triangles. Originally constructed as a curve, this is one of
the basic examples of self-similar sets—that is, it is a mathematically
generated pattern that is reproducible at any magnification or reduction. It is
named after the Polish mathematician Wacław Sierpiński, but appeared as a
decorative pattern many centuries before the work of Sierpiński.
Usage: python sierpinski_triangle.py <int:depth_for_fractal>
Credits:
The above description is taken from
https://en.wikipedia.org/wiki/Sierpi%C5%84ski_triangle
This code was written by editing the code from
https://www.riannetrujillo.com/blog/python-fractal/
"""
import sys
import turtle
def get_mid(p1: tuple[float, float], p2: tuple[float, float]) -> tuple[float, float]:
"""
Find the midpoint of two points
>>> get_mid((0, 0), (2, 2))
(1.0, 1.0)
>>> get_mid((-3, -3), (3, 3))
(0.0, 0.0)
>>> get_mid((1, 0), (3, 2))
(2.0, 1.0)
>>> get_mid((0, 0), (1, 1))
(0.5, 0.5)
>>> get_mid((0, 0), (0, 0))
(0.0, 0.0)
"""
return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2
def triangle(
vertex1: tuple[float, float],
vertex2: tuple[float, float],
vertex3: tuple[float, float],
depth: int,
) -> None:
"""
Recursively draw the Sierpinski triangle given the vertices of the triangle
and the recursion depth
"""
my_pen.up()
my_pen.goto(vertex1[0], vertex1[1])
my_pen.down()
my_pen.goto(vertex2[0], vertex2[1])
my_pen.goto(vertex3[0], vertex3[1])
my_pen.goto(vertex1[0], vertex1[1])
if depth == 0:
return
triangle(vertex1, get_mid(vertex1, vertex2), get_mid(vertex1, vertex3), depth - 1)
triangle(vertex2, get_mid(vertex1, vertex2), get_mid(vertex2, vertex3), depth - 1)
triangle(vertex3, get_mid(vertex3, vertex2), get_mid(vertex1, vertex3), depth - 1)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError(
"Correct format for using this script: "
"python fractals.py <int:depth_for_fractal>"
)
my_pen = turtle.Turtle()
my_pen.ht()
my_pen.speed(5)
my_pen.pencolor("red")
vertices = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle
triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
turtle.Screen().exitonclick()
| """
Author Anurag Kumar | [email protected] | git/anuragkumarak95
Simple example of fractal generation using recursion.
What is the Sierpiński Triangle?
The Sierpiński triangle (sometimes spelled Sierpinski), also called the
Sierpiński gasket or Sierpiński sieve, is a fractal attractive fixed set with
the overall shape of an equilateral triangle, subdivided recursively into
smaller equilateral triangles. Originally constructed as a curve, this is one of
the basic examples of self-similar sets—that is, it is a mathematically
generated pattern that is reproducible at any magnification or reduction. It is
named after the Polish mathematician Wacław Sierpiński, but appeared as a
decorative pattern many centuries before the work of Sierpiński.
Usage: python sierpinski_triangle.py <int:depth_for_fractal>
Credits:
The above description is taken from
https://en.wikipedia.org/wiki/Sierpi%C5%84ski_triangle
This code was written by editing the code from
https://www.riannetrujillo.com/blog/python-fractal/
"""
import sys
import turtle
def get_mid(p1: tuple[float, float], p2: tuple[float, float]) -> tuple[float, float]:
"""
Find the midpoint of two points
>>> get_mid((0, 0), (2, 2))
(1.0, 1.0)
>>> get_mid((-3, -3), (3, 3))
(0.0, 0.0)
>>> get_mid((1, 0), (3, 2))
(2.0, 1.0)
>>> get_mid((0, 0), (1, 1))
(0.5, 0.5)
>>> get_mid((0, 0), (0, 0))
(0.0, 0.0)
"""
return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2
def triangle(
vertex1: tuple[float, float],
vertex2: tuple[float, float],
vertex3: tuple[float, float],
depth: int,
) -> None:
"""
Recursively draw the Sierpinski triangle given the vertices of the triangle
and the recursion depth
"""
my_pen.up()
my_pen.goto(vertex1[0], vertex1[1])
my_pen.down()
my_pen.goto(vertex2[0], vertex2[1])
my_pen.goto(vertex3[0], vertex3[1])
my_pen.goto(vertex1[0], vertex1[1])
if depth == 0:
return
triangle(vertex1, get_mid(vertex1, vertex2), get_mid(vertex1, vertex3), depth - 1)
triangle(vertex2, get_mid(vertex1, vertex2), get_mid(vertex2, vertex3), depth - 1)
triangle(vertex3, get_mid(vertex3, vertex2), get_mid(vertex1, vertex3), depth - 1)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError(
"Correct format for using this script: "
"python fractals.py <int:depth_for_fractal>"
)
my_pen = turtle.Turtle()
my_pen.ht()
my_pen.speed(5)
my_pen.pencolor("red")
vertices = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle
triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
turtle.Screen().exitonclick()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 94: https://projecteuler.net/problem=94
It is easily proved that no equilateral triangle exists with integral length sides and
integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square
units.
We shall define an almost equilateral triangle to be a triangle for which two sides are
equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side
lengths and area and whose perimeters do not exceed one billion (1,000,000,000).
"""
def solution(max_perimeter: int = 10**9) -> int:
"""
Returns the sum of the perimeters of all almost equilateral triangles with integral
side lengths and area and whose perimeters do not exceed max_perimeter
>>> solution(20)
16
"""
prev_value = 1
value = 2
perimeters_sum = 0
i = 0
perimeter = 0
while perimeter <= max_perimeter:
perimeters_sum += perimeter
prev_value += 2 * value
value += prev_value
perimeter = 2 * value + 2 if i % 2 == 0 else 2 * value - 2
i += 1
return perimeters_sum
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 94: https://projecteuler.net/problem=94
It is easily proved that no equilateral triangle exists with integral length sides and
integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square
units.
We shall define an almost equilateral triangle to be a triangle for which two sides are
equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side
lengths and area and whose perimeters do not exceed one billion (1,000,000,000).
"""
def solution(max_perimeter: int = 10**9) -> int:
"""
Returns the sum of the perimeters of all almost equilateral triangles with integral
side lengths and area and whose perimeters do not exceed max_perimeter
>>> solution(20)
16
"""
prev_value = 1
value = 2
perimeters_sum = 0
i = 0
perimeter = 0
while perimeter <= max_perimeter:
perimeters_sum += perimeter
prev_value += 2 * value
value += prev_value
perimeter = 2 * value + 2 if i % 2 == 0 else 2 * value - 2
i += 1
return perimeters_sum
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from typing import Any
class Node:
def __init__(self, data: Any):
"""
Create and initialize Node class instance.
>>> Node(20)
Node(20)
>>> Node("Hello, world!")
Node(Hello, world!)
>>> Node(None)
Node(None)
>>> Node(True)
Node(True)
"""
self.data = data
self.next = None
def __repr__(self) -> str:
"""
Get the string representation of this node.
>>> Node(10).__repr__()
'Node(10)'
"""
return f"Node({self.data})"
class LinkedList:
def __init__(self):
"""
Create and initialize LinkedList class instance.
>>> linked_list = LinkedList()
"""
self.head = None
def __iter__(self) -> Any:
"""
This function is intended for iterators to access
and iterate through data inside linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("tail")
>>> linked_list.insert_tail("tail_1")
>>> linked_list.insert_tail("tail_2")
>>> for node in linked_list: # __iter__ used here.
... node
'tail'
'tail_1'
'tail_2'
"""
node = self.head
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
Return length of linked list i.e. number of nodes
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.insert_tail("tail")
>>> len(linked_list)
1
>>> linked_list.insert_head("head")
>>> len(linked_list)
2
>>> _ = linked_list.delete_tail()
>>> len(linked_list)
1
>>> _ = linked_list.delete_head()
>>> len(linked_list)
0
"""
return sum(1 for _ in self)
def __repr__(self) -> str:
"""
String representation/visualization of a Linked Lists
>>> linked_list = LinkedList()
>>> linked_list.insert_tail(1)
>>> linked_list.insert_tail(3)
>>> linked_list.__repr__()
'1->3'
"""
return "->".join([str(item) for item in self])
def __getitem__(self, index: int) -> Any:
"""
Indexing Support. Used to get a node at particular position
>>> linked_list = LinkedList()
>>> for i in range(0, 10):
... linked_list.insert_nth(i, i)
>>> all(str(linked_list[i]) == str(i) for i in range(0, 10))
True
>>> linked_list[-10]
Traceback (most recent call last):
...
ValueError: list index out of range.
>>> linked_list[len(linked_list)]
Traceback (most recent call last):
...
ValueError: list index out of range.
"""
if not 0 <= index < len(self):
raise ValueError("list index out of range.")
for i, node in enumerate(self):
if i == index:
return node
return None
# Used to change the data of a particular node
def __setitem__(self, index: int, data: Any) -> None:
"""
>>> linked_list = LinkedList()
>>> for i in range(0, 10):
... linked_list.insert_nth(i, i)
>>> linked_list[0] = 666
>>> linked_list[0]
666
>>> linked_list[5] = -666
>>> linked_list[5]
-666
>>> linked_list[-10] = 666
Traceback (most recent call last):
...
ValueError: list index out of range.
>>> linked_list[len(linked_list)] = 666
Traceback (most recent call last):
...
ValueError: list index out of range.
"""
if not 0 <= index < len(self):
raise ValueError("list index out of range.")
current = self.head
for _ in range(index):
current = current.next
current.data = data
def insert_tail(self, data: Any) -> None:
"""
Insert data to the end of linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("tail")
>>> linked_list
tail
>>> linked_list.insert_tail("tail_2")
>>> linked_list
tail->tail_2
>>> linked_list.insert_tail("tail_3")
>>> linked_list
tail->tail_2->tail_3
"""
self.insert_nth(len(self), data)
def insert_head(self, data: Any) -> None:
"""
Insert data to the beginning of linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_head("head")
>>> linked_list
head
>>> linked_list.insert_head("head_2")
>>> linked_list
head_2->head
>>> linked_list.insert_head("head_3")
>>> linked_list
head_3->head_2->head
"""
self.insert_nth(0, data)
def insert_nth(self, index: int, data: Any) -> None:
"""
Insert data at given index.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.insert_nth(1, "fourth")
>>> linked_list
first->fourth->second->third
>>> linked_list.insert_nth(3, "fifth")
>>> linked_list
first->fourth->second->fifth->third
"""
if not 0 <= index <= len(self):
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
self.head = new_node
elif index == 0:
new_node.next = self.head # link new_node to head
self.head = new_node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
new_node.next = temp.next
temp.next = new_node
def print_list(self) -> None: # print every node data
"""
This method prints every node data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
"""
print(self)
def delete_head(self) -> Any:
"""
Delete the first node and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.delete_head()
'first'
>>> linked_list
second->third
>>> linked_list.delete_head()
'second'
>>> linked_list
third
>>> linked_list.delete_head()
'third'
>>> linked_list.delete_head()
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
return self.delete_nth(0)
def delete_tail(self) -> Any: # delete from tail
"""
Delete the tail end node and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.delete_tail()
'third'
>>> linked_list
first->second
>>> linked_list.delete_tail()
'second'
>>> linked_list
first
>>> linked_list.delete_tail()
'first'
>>> linked_list.delete_tail()
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
return self.delete_nth(len(self) - 1)
def delete_nth(self, index: int = 0) -> Any:
"""
Delete node at given index and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.delete_nth(1) # delete middle
'second'
>>> linked_list
first->third
>>> linked_list.delete_nth(5) # this raises error
Traceback (most recent call last):
...
IndexError: List index out of range.
>>> linked_list.delete_nth(-1) # this also raises error
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
if not 0 <= index <= len(self) - 1: # test if index is valid
raise IndexError("List index out of range.")
delete_node = self.head # default first node
if index == 0:
self.head = self.head.next
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
delete_node = temp.next
temp.next = temp.next.next
return delete_node.data
def is_empty(self) -> bool:
"""
Check if linked list is empty.
>>> linked_list = LinkedList()
>>> linked_list.is_empty()
True
>>> linked_list.insert_head("first")
>>> linked_list.is_empty()
False
"""
return self.head is None
def reverse(self) -> None:
"""
This reverses the linked list order.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.reverse()
>>> linked_list
third->second->first
"""
prev = None
current = self.head
while current:
# Store the current node's next node.
next_node = current.next
# Make the current node's next point backwards
current.next = prev
# Make the previous node be the current node
prev = current
# Make the current node the next node (to progress iteration)
current = next_node
# Return prev in order to put the head at the end
self.head = prev
def test_singly_linked_list() -> None:
"""
>>> test_singly_linked_list()
"""
linked_list = LinkedList()
assert linked_list.is_empty() is True
assert str(linked_list) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10):
assert len(linked_list) == i
linked_list.insert_nth(i, i + 1)
assert str(linked_list) == "->".join(str(i) for i in range(1, 11))
linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))
assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
for i in range(0, 9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
def test_singly_linked_list_2() -> None:
"""
This section of the test used varying data types for input.
>>> test_singly_linked_list_2()
"""
test_input = [
-9,
100,
Node(77345112),
"dlrow olleH",
7,
5555,
0,
-192.55555,
"Hello, world!",
77.9,
Node(10),
None,
None,
12.20,
]
linked_list = LinkedList()
for i in test_input:
linked_list.insert_tail(i)
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
result = linked_list.delete_head()
assert result == -9
assert (
str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
result = linked_list.delete_tail()
assert result == 12.2
assert (
str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
result = linked_list.delete_nth(10)
assert result is None
assert (
str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node("Hello again, world!"))
assert (
str(linked_list)
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(None)
assert (
str(linked_list)
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(linked_list)
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def main():
from doctest import testmod
testmod()
linked_list = LinkedList()
linked_list.insert_head(input("Inserting 1st at head ").strip())
linked_list.insert_head(input("Inserting 2nd at head ").strip())
print("\nPrint list:")
linked_list.print_list()
linked_list.insert_tail(input("\nInserting 1st at tail ").strip())
linked_list.insert_tail(input("Inserting 2nd at tail ").strip())
print("\nPrint list:")
linked_list.print_list()
print("\nDelete head")
linked_list.delete_head()
print("Delete tail")
linked_list.delete_tail()
print("\nPrint list:")
linked_list.print_list()
print("\nReverse linked list")
linked_list.reverse()
print("\nPrint list:")
linked_list.print_list()
print("\nString representation of linked list:")
print(linked_list)
print("\nReading/changing Node data using indexing:")
print(f"Element at Position 1: {linked_list[1]}")
linked_list[1] = input("Enter New Value: ").strip()
print("New list:")
print(linked_list)
print(f"length of linked_list is : {len(linked_list)}")
if __name__ == "__main__":
main()
| from typing import Any
class Node:
def __init__(self, data: Any):
"""
Create and initialize Node class instance.
>>> Node(20)
Node(20)
>>> Node("Hello, world!")
Node(Hello, world!)
>>> Node(None)
Node(None)
>>> Node(True)
Node(True)
"""
self.data = data
self.next = None
def __repr__(self) -> str:
"""
Get the string representation of this node.
>>> Node(10).__repr__()
'Node(10)'
"""
return f"Node({self.data})"
class LinkedList:
def __init__(self):
"""
Create and initialize LinkedList class instance.
>>> linked_list = LinkedList()
"""
self.head = None
def __iter__(self) -> Any:
"""
This function is intended for iterators to access
and iterate through data inside linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("tail")
>>> linked_list.insert_tail("tail_1")
>>> linked_list.insert_tail("tail_2")
>>> for node in linked_list: # __iter__ used here.
... node
'tail'
'tail_1'
'tail_2'
"""
node = self.head
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
Return length of linked list i.e. number of nodes
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.insert_tail("tail")
>>> len(linked_list)
1
>>> linked_list.insert_head("head")
>>> len(linked_list)
2
>>> _ = linked_list.delete_tail()
>>> len(linked_list)
1
>>> _ = linked_list.delete_head()
>>> len(linked_list)
0
"""
return sum(1 for _ in self)
def __repr__(self) -> str:
"""
String representation/visualization of a Linked Lists
>>> linked_list = LinkedList()
>>> linked_list.insert_tail(1)
>>> linked_list.insert_tail(3)
>>> linked_list.__repr__()
'1->3'
"""
return "->".join([str(item) for item in self])
def __getitem__(self, index: int) -> Any:
"""
Indexing Support. Used to get a node at particular position
>>> linked_list = LinkedList()
>>> for i in range(0, 10):
... linked_list.insert_nth(i, i)
>>> all(str(linked_list[i]) == str(i) for i in range(0, 10))
True
>>> linked_list[-10]
Traceback (most recent call last):
...
ValueError: list index out of range.
>>> linked_list[len(linked_list)]
Traceback (most recent call last):
...
ValueError: list index out of range.
"""
if not 0 <= index < len(self):
raise ValueError("list index out of range.")
for i, node in enumerate(self):
if i == index:
return node
return None
# Used to change the data of a particular node
def __setitem__(self, index: int, data: Any) -> None:
"""
>>> linked_list = LinkedList()
>>> for i in range(0, 10):
... linked_list.insert_nth(i, i)
>>> linked_list[0] = 666
>>> linked_list[0]
666
>>> linked_list[5] = -666
>>> linked_list[5]
-666
>>> linked_list[-10] = 666
Traceback (most recent call last):
...
ValueError: list index out of range.
>>> linked_list[len(linked_list)] = 666
Traceback (most recent call last):
...
ValueError: list index out of range.
"""
if not 0 <= index < len(self):
raise ValueError("list index out of range.")
current = self.head
for _ in range(index):
current = current.next
current.data = data
def insert_tail(self, data: Any) -> None:
"""
Insert data to the end of linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("tail")
>>> linked_list
tail
>>> linked_list.insert_tail("tail_2")
>>> linked_list
tail->tail_2
>>> linked_list.insert_tail("tail_3")
>>> linked_list
tail->tail_2->tail_3
"""
self.insert_nth(len(self), data)
def insert_head(self, data: Any) -> None:
"""
Insert data to the beginning of linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_head("head")
>>> linked_list
head
>>> linked_list.insert_head("head_2")
>>> linked_list
head_2->head
>>> linked_list.insert_head("head_3")
>>> linked_list
head_3->head_2->head
"""
self.insert_nth(0, data)
def insert_nth(self, index: int, data: Any) -> None:
"""
Insert data at given index.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.insert_nth(1, "fourth")
>>> linked_list
first->fourth->second->third
>>> linked_list.insert_nth(3, "fifth")
>>> linked_list
first->fourth->second->fifth->third
"""
if not 0 <= index <= len(self):
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
self.head = new_node
elif index == 0:
new_node.next = self.head # link new_node to head
self.head = new_node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
new_node.next = temp.next
temp.next = new_node
def print_list(self) -> None: # print every node data
"""
This method prints every node data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
"""
print(self)
def delete_head(self) -> Any:
"""
Delete the first node and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.delete_head()
'first'
>>> linked_list
second->third
>>> linked_list.delete_head()
'second'
>>> linked_list
third
>>> linked_list.delete_head()
'third'
>>> linked_list.delete_head()
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
return self.delete_nth(0)
def delete_tail(self) -> Any: # delete from tail
"""
Delete the tail end node and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.delete_tail()
'third'
>>> linked_list
first->second
>>> linked_list.delete_tail()
'second'
>>> linked_list
first
>>> linked_list.delete_tail()
'first'
>>> linked_list.delete_tail()
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
return self.delete_nth(len(self) - 1)
def delete_nth(self, index: int = 0) -> Any:
"""
Delete node at given index and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.delete_nth(1) # delete middle
'second'
>>> linked_list
first->third
>>> linked_list.delete_nth(5) # this raises error
Traceback (most recent call last):
...
IndexError: List index out of range.
>>> linked_list.delete_nth(-1) # this also raises error
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
if not 0 <= index <= len(self) - 1: # test if index is valid
raise IndexError("List index out of range.")
delete_node = self.head # default first node
if index == 0:
self.head = self.head.next
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
delete_node = temp.next
temp.next = temp.next.next
return delete_node.data
def is_empty(self) -> bool:
"""
Check if linked list is empty.
>>> linked_list = LinkedList()
>>> linked_list.is_empty()
True
>>> linked_list.insert_head("first")
>>> linked_list.is_empty()
False
"""
return self.head is None
def reverse(self) -> None:
"""
This reverses the linked list order.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
>>> linked_list.reverse()
>>> linked_list
third->second->first
"""
prev = None
current = self.head
while current:
# Store the current node's next node.
next_node = current.next
# Make the current node's next point backwards
current.next = prev
# Make the previous node be the current node
prev = current
# Make the current node the next node (to progress iteration)
current = next_node
# Return prev in order to put the head at the end
self.head = prev
def test_singly_linked_list() -> None:
"""
>>> test_singly_linked_list()
"""
linked_list = LinkedList()
assert linked_list.is_empty() is True
assert str(linked_list) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10):
assert len(linked_list) == i
linked_list.insert_nth(i, i + 1)
assert str(linked_list) == "->".join(str(i) for i in range(1, 11))
linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(0, 12))
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))
assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True
for i in range(0, 9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(0, 9)) is True
linked_list.reverse()
assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
def test_singly_linked_list_2() -> None:
"""
This section of the test used varying data types for input.
>>> test_singly_linked_list_2()
"""
test_input = [
-9,
100,
Node(77345112),
"dlrow olleH",
7,
5555,
0,
-192.55555,
"Hello, world!",
77.9,
Node(10),
None,
None,
12.20,
]
linked_list = LinkedList()
for i in test_input:
linked_list.insert_tail(i)
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
result = linked_list.delete_head()
assert result == -9
assert (
str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
result = linked_list.delete_tail()
assert result == 12.2
assert (
str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
result = linked_list.delete_nth(10)
assert result is None
assert (
str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node("Hello again, world!"))
assert (
str(linked_list)
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(None)
assert (
str(linked_list)
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(linked_list)
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def main():
from doctest import testmod
testmod()
linked_list = LinkedList()
linked_list.insert_head(input("Inserting 1st at head ").strip())
linked_list.insert_head(input("Inserting 2nd at head ").strip())
print("\nPrint list:")
linked_list.print_list()
linked_list.insert_tail(input("\nInserting 1st at tail ").strip())
linked_list.insert_tail(input("Inserting 2nd at tail ").strip())
print("\nPrint list:")
linked_list.print_list()
print("\nDelete head")
linked_list.delete_head()
print("Delete tail")
linked_list.delete_tail()
print("\nPrint list:")
linked_list.print_list()
print("\nReverse linked list")
linked_list.reverse()
print("\nPrint list:")
linked_list.print_list()
print("\nString representation of linked list:")
print(linked_list)
print("\nReading/changing Node data using indexing:")
print(f"Element at Position 1: {linked_list[1]}")
linked_list[1] = input("Enter New Value: ").strip()
print("New list:")
print(linked_list)
print(f"length of linked_list is : {len(linked_list)}")
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # Boolean Algebra
Boolean algebra is used to do arithmetic with bits of values True (1) or False (0).
There are three basic operations: 'and', 'or' and 'not'.
* <https://en.wikipedia.org/wiki/Boolean_algebra>
* <https://plato.stanford.edu/entries/boolalg-math/>
| # Boolean Algebra
Boolean algebra is used to do arithmetic with bits of values True (1) or False (0).
There are three basic operations: 'and', 'or' and 'not'.
* <https://en.wikipedia.org/wiki/Boolean_algebra>
* <https://plato.stanford.edu/entries/boolalg-math/>
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # https://en.wikipedia.org/wiki/Hill_climbing
import math
class SearchProblem:
"""
An interface to define search problems.
The interface will be illustrated using the example of mathematical function.
"""
def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
"""
The constructor of the search problem.
x: the x coordinate of the current search state.
y: the y coordinate of the current search state.
step_size: size of the step to take when looking for neighbors.
function_to_optimize: a function to optimize having the signature f(x, y).
"""
self.x = x
self.y = y
self.step_size = step_size
self.function = function_to_optimize
def score(self) -> int:
"""
Returns the output of the function called with current x and y coordinates.
>>> def test_function(x, y):
... return x + y
>>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0
0
>>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12
12
"""
return self.function(self.x, self.y)
def get_neighbors(self):
"""
Returns a list of coordinates of neighbors adjacent to the current coordinates.
Neighbors:
| 0 | 1 | 2 |
| 3 | _ | 4 |
| 5 | 6 | 7 |
"""
step_size = self.step_size
return [
SearchProblem(x, y, step_size, self.function)
for x, y in (
(self.x - step_size, self.y - step_size),
(self.x - step_size, self.y),
(self.x - step_size, self.y + step_size),
(self.x, self.y - step_size),
(self.x, self.y + step_size),
(self.x + step_size, self.y - step_size),
(self.x + step_size, self.y),
(self.x + step_size, self.y + step_size),
)
]
def __hash__(self):
"""
hash the string representation of the current search state.
"""
return hash(str(self))
def __eq__(self, obj):
"""
Check if the 2 objects are equal.
"""
if isinstance(obj, SearchProblem):
return hash(str(self)) == hash(str(obj))
return False
def __str__(self):
"""
string representation of the current search state.
>>> str(SearchProblem(0, 0, 1, None))
'x: 0 y: 0'
>>> str(SearchProblem(2, 5, 1, None))
'x: 2 y: 5'
"""
return f"x: {self.x} y: {self.y}"
def hill_climbing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
max_iter: int = 10000,
) -> SearchProblem:
"""
Implementation of the hill climbling algorithm.
We start with a given state, find all its neighbors,
move towards the neighbor which provides the maximum (or minimum) change.
We keep doing this until we are at a state where we do not have any
neighbors which can improve the solution.
Args:
search_prob: The search state at the start.
find_max: If True, the algorithm should find the maximum else the minimum.
max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y.
visualization: If True, a matplotlib graph is displayed.
max_iter: number of times to run the iteration.
Returns a search state having the maximum (or minimum) score.
"""
current_state = search_prob
scores = [] # list to store the current score at each iteration
iterations = 0
solution_found = False
visited = set()
while not solution_found and iterations < max_iter:
visited.add(current_state)
iterations += 1
current_score = current_state.score()
scores.append(current_score)
neighbors = current_state.get_neighbors()
max_change = -math.inf
min_change = math.inf
next_state = None # to hold the next best neighbor
for neighbor in neighbors:
if neighbor in visited:
continue # do not want to visit the same state again
if (
neighbor.x > max_x
or neighbor.x < min_x
or neighbor.y > max_y
or neighbor.y < min_y
):
continue # neighbor outside our bounds
change = neighbor.score() - current_score
if find_max: # finding max
# going to direction with greatest ascent
if change > max_change and change > 0:
max_change = change
next_state = neighbor
else: # finding min
# to direction with greatest descent
if change < min_change and change < 0:
min_change = change
next_state = neighbor
if next_state is not None:
# we found at least one neighbor which improved the current state
current_state = next_state
else:
# since we have no neighbor that improves the solution we stop the search
solution_found = True
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return current_state
if __name__ == "__main__":
import doctest
doctest.testmod()
def test_f1(x, y):
return (x**2) + (y**2)
# starting the problem with initial coordinates (3, 4)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=False)
print(
"The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: "
f"{local_min.score()}"
)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(
prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
def test_f2(x, y):
return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=True)
print(
"The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: "
f"{local_min.score()}"
)
| # https://en.wikipedia.org/wiki/Hill_climbing
import math
class SearchProblem:
"""
An interface to define search problems.
The interface will be illustrated using the example of mathematical function.
"""
def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
"""
The constructor of the search problem.
x: the x coordinate of the current search state.
y: the y coordinate of the current search state.
step_size: size of the step to take when looking for neighbors.
function_to_optimize: a function to optimize having the signature f(x, y).
"""
self.x = x
self.y = y
self.step_size = step_size
self.function = function_to_optimize
def score(self) -> int:
"""
Returns the output of the function called with current x and y coordinates.
>>> def test_function(x, y):
... return x + y
>>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0
0
>>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12
12
"""
return self.function(self.x, self.y)
def get_neighbors(self):
"""
Returns a list of coordinates of neighbors adjacent to the current coordinates.
Neighbors:
| 0 | 1 | 2 |
| 3 | _ | 4 |
| 5 | 6 | 7 |
"""
step_size = self.step_size
return [
SearchProblem(x, y, step_size, self.function)
for x, y in (
(self.x - step_size, self.y - step_size),
(self.x - step_size, self.y),
(self.x - step_size, self.y + step_size),
(self.x, self.y - step_size),
(self.x, self.y + step_size),
(self.x + step_size, self.y - step_size),
(self.x + step_size, self.y),
(self.x + step_size, self.y + step_size),
)
]
def __hash__(self):
"""
hash the string representation of the current search state.
"""
return hash(str(self))
def __eq__(self, obj):
"""
Check if the 2 objects are equal.
"""
if isinstance(obj, SearchProblem):
return hash(str(self)) == hash(str(obj))
return False
def __str__(self):
"""
string representation of the current search state.
>>> str(SearchProblem(0, 0, 1, None))
'x: 0 y: 0'
>>> str(SearchProblem(2, 5, 1, None))
'x: 2 y: 5'
"""
return f"x: {self.x} y: {self.y}"
def hill_climbing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
max_iter: int = 10000,
) -> SearchProblem:
"""
Implementation of the hill climbling algorithm.
We start with a given state, find all its neighbors,
move towards the neighbor which provides the maximum (or minimum) change.
We keep doing this until we are at a state where we do not have any
neighbors which can improve the solution.
Args:
search_prob: The search state at the start.
find_max: If True, the algorithm should find the maximum else the minimum.
max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y.
visualization: If True, a matplotlib graph is displayed.
max_iter: number of times to run the iteration.
Returns a search state having the maximum (or minimum) score.
"""
current_state = search_prob
scores = [] # list to store the current score at each iteration
iterations = 0
solution_found = False
visited = set()
while not solution_found and iterations < max_iter:
visited.add(current_state)
iterations += 1
current_score = current_state.score()
scores.append(current_score)
neighbors = current_state.get_neighbors()
max_change = -math.inf
min_change = math.inf
next_state = None # to hold the next best neighbor
for neighbor in neighbors:
if neighbor in visited:
continue # do not want to visit the same state again
if (
neighbor.x > max_x
or neighbor.x < min_x
or neighbor.y > max_y
or neighbor.y < min_y
):
continue # neighbor outside our bounds
change = neighbor.score() - current_score
if find_max: # finding max
# going to direction with greatest ascent
if change > max_change and change > 0:
max_change = change
next_state = neighbor
else: # finding min
# to direction with greatest descent
if change < min_change and change < 0:
min_change = change
next_state = neighbor
if next_state is not None:
# we found at least one neighbor which improved the current state
current_state = next_state
else:
# since we have no neighbor that improves the solution we stop the search
solution_found = True
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return current_state
if __name__ == "__main__":
import doctest
doctest.testmod()
def test_f1(x, y):
return (x**2) + (y**2)
# starting the problem with initial coordinates (3, 4)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=False)
print(
"The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: "
f"{local_min.score()}"
)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(
prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
def test_f2(x, y):
return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=True)
print(
"The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: "
f"{local_min.score()}"
)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from scipy.constants import g
"""
Finding the gravitational potential energy of an object with reference
to the earth,by taking its mass and height above the ground as input
Description : Gravitational energy or gravitational potential energy
is the potential energy a massive object has in relation to another
massive object due to gravity. It is the potential energy associated
with the gravitational field, which is released (converted into
kinetic energy) when the objects fall towards each other.
Gravitational potential energy increases when two objects
are brought further apart.
For two pairwise interacting point particles, the gravitational
potential energy U is given by
U=-GMm/R
where M and m are the masses of the two particles, R is the distance
between them, and G is the gravitational constant.
Close to the Earth's surface, the gravitational field is approximately
constant, and the gravitational potential energy of an object reduces to
U=mgh
where m is the object's mass, g=GM/R² is the gravity of Earth, and h is
the height of the object's center of mass above a chosen reference level.
Reference : "https://en.m.wikipedia.org/wiki/Gravitational_energy"
"""
def potential_energy(mass: float, height: float) -> float:
# function will accept mass and height as parameters and return potential energy
"""
>>> potential_energy(10,10)
980.665
>>> potential_energy(0,5)
0.0
>>> potential_energy(8,0)
0.0
>>> potential_energy(10,5)
490.3325
>>> potential_energy(0,0)
0.0
>>> potential_energy(2,8)
156.9064
>>> potential_energy(20,100)
19613.3
"""
if mass < 0:
# handling of negative values of mass
raise ValueError("The mass of a body cannot be negative")
if height < 0:
# handling of negative values of height
raise ValueError("The height above the ground cannot be negative")
return mass * g * height
if __name__ == "__main__":
from doctest import testmod
testmod(name="potential_energy")
| from scipy.constants import g
"""
Finding the gravitational potential energy of an object with reference
to the earth,by taking its mass and height above the ground as input
Description : Gravitational energy or gravitational potential energy
is the potential energy a massive object has in relation to another
massive object due to gravity. It is the potential energy associated
with the gravitational field, which is released (converted into
kinetic energy) when the objects fall towards each other.
Gravitational potential energy increases when two objects
are brought further apart.
For two pairwise interacting point particles, the gravitational
potential energy U is given by
U=-GMm/R
where M and m are the masses of the two particles, R is the distance
between them, and G is the gravitational constant.
Close to the Earth's surface, the gravitational field is approximately
constant, and the gravitational potential energy of an object reduces to
U=mgh
where m is the object's mass, g=GM/R² is the gravity of Earth, and h is
the height of the object's center of mass above a chosen reference level.
Reference : "https://en.m.wikipedia.org/wiki/Gravitational_energy"
"""
def potential_energy(mass: float, height: float) -> float:
# function will accept mass and height as parameters and return potential energy
"""
>>> potential_energy(10,10)
980.665
>>> potential_energy(0,5)
0.0
>>> potential_energy(8,0)
0.0
>>> potential_energy(10,5)
490.3325
>>> potential_energy(0,0)
0.0
>>> potential_energy(2,8)
156.9064
>>> potential_energy(20,100)
19613.3
"""
if mass < 0:
# handling of negative values of mass
raise ValueError("The mass of a body cannot be negative")
if height < 0:
# handling of negative values of height
raise ValueError("The height above the ground cannot be negative")
return mass * g * height
if __name__ == "__main__":
from doctest import testmod
testmod(name="potential_energy")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Author : Turfa Auliarachman
Date : October 12, 2016
This is a pure Python implementation of Dynamic Programming solution to the edit
distance problem.
The problem is :
Given two strings A and B. Find the minimum number of operations to string B such that
A = B. The permitted operations are removal, insertion, and substitution.
"""
class EditDistance:
"""
Use :
solver = EditDistance()
editDistanceResult = solver.solve(firstString, secondString)
"""
def __init__(self):
self.word1 = ""
self.word2 = ""
self.dp = []
def __min_dist_top_down_dp(self, m: int, n: int) -> int:
if m == -1:
return n + 1
elif n == -1:
return m + 1
elif self.dp[m][n] > -1:
return self.dp[m][n]
else:
if self.word1[m] == self.word2[n]:
self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1)
else:
insert = self.__min_dist_top_down_dp(m, n - 1)
delete = self.__min_dist_top_down_dp(m - 1, n)
replace = self.__min_dist_top_down_dp(m - 1, n - 1)
self.dp[m][n] = 1 + min(insert, delete, replace)
return self.dp[m][n]
def min_dist_top_down(self, word1: str, word2: str) -> int:
"""
>>> EditDistance().min_dist_top_down("intention", "execution")
5
>>> EditDistance().min_dist_top_down("intention", "")
9
>>> EditDistance().min_dist_top_down("", "")
0
"""
self.word1 = word1
self.word2 = word2
self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))]
return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1)
def min_dist_bottom_up(self, word1: str, word2: str) -> int:
"""
>>> EditDistance().min_dist_bottom_up("intention", "execution")
5
>>> EditDistance().min_dist_bottom_up("intention", "")
9
>>> EditDistance().min_dist_bottom_up("", "")
0
"""
self.word1 = word1
self.word2 = word2
m = len(word1)
n = len(word2)
self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0: # first string is empty
self.dp[i][j] = j
elif j == 0: # second string is empty
self.dp[i][j] = i
elif word1[i - 1] == word2[j - 1]: # last characters are equal
self.dp[i][j] = self.dp[i - 1][j - 1]
else:
insert = self.dp[i][j - 1]
delete = self.dp[i - 1][j]
replace = self.dp[i - 1][j - 1]
self.dp[i][j] = 1 + min(insert, delete, replace)
return self.dp[m][n]
if __name__ == "__main__":
solver = EditDistance()
print("****************** Testing Edit Distance DP Algorithm ******************")
print()
S1 = input("Enter the first string: ").strip()
S2 = input("Enter the second string: ").strip()
print()
print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}")
print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}")
print()
print("*************** End of Testing Edit Distance DP Algorithm ***************")
| """
Author : Turfa Auliarachman
Date : October 12, 2016
This is a pure Python implementation of Dynamic Programming solution to the edit
distance problem.
The problem is :
Given two strings A and B. Find the minimum number of operations to string B such that
A = B. The permitted operations are removal, insertion, and substitution.
"""
class EditDistance:
"""
Use :
solver = EditDistance()
editDistanceResult = solver.solve(firstString, secondString)
"""
def __init__(self):
self.word1 = ""
self.word2 = ""
self.dp = []
def __min_dist_top_down_dp(self, m: int, n: int) -> int:
if m == -1:
return n + 1
elif n == -1:
return m + 1
elif self.dp[m][n] > -1:
return self.dp[m][n]
else:
if self.word1[m] == self.word2[n]:
self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1)
else:
insert = self.__min_dist_top_down_dp(m, n - 1)
delete = self.__min_dist_top_down_dp(m - 1, n)
replace = self.__min_dist_top_down_dp(m - 1, n - 1)
self.dp[m][n] = 1 + min(insert, delete, replace)
return self.dp[m][n]
def min_dist_top_down(self, word1: str, word2: str) -> int:
"""
>>> EditDistance().min_dist_top_down("intention", "execution")
5
>>> EditDistance().min_dist_top_down("intention", "")
9
>>> EditDistance().min_dist_top_down("", "")
0
"""
self.word1 = word1
self.word2 = word2
self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))]
return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1)
def min_dist_bottom_up(self, word1: str, word2: str) -> int:
"""
>>> EditDistance().min_dist_bottom_up("intention", "execution")
5
>>> EditDistance().min_dist_bottom_up("intention", "")
9
>>> EditDistance().min_dist_bottom_up("", "")
0
"""
self.word1 = word1
self.word2 = word2
m = len(word1)
n = len(word2)
self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0: # first string is empty
self.dp[i][j] = j
elif j == 0: # second string is empty
self.dp[i][j] = i
elif word1[i - 1] == word2[j - 1]: # last characters are equal
self.dp[i][j] = self.dp[i - 1][j - 1]
else:
insert = self.dp[i][j - 1]
delete = self.dp[i - 1][j]
replace = self.dp[i - 1][j - 1]
self.dp[i][j] = 1 + min(insert, delete, replace)
return self.dp[m][n]
if __name__ == "__main__":
solver = EditDistance()
print("****************** Testing Edit Distance DP Algorithm ******************")
print()
S1 = input("Enter the first string: ").strip()
S2 = input("Enter the second string: ").strip()
print()
print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}")
print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}")
print()
print("*************** End of Testing Edit Distance DP Algorithm ***************")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from __future__ import annotations
import math
class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
def left(self, idx: int) -> int:
"""
>>> segment_tree = SegmentTree(15)
>>> segment_tree.left(1)
2
>>> segment_tree.left(2)
4
>>> segment_tree.left(12)
24
"""
return idx * 2
def right(self, idx: int) -> int:
"""
>>> segment_tree = SegmentTree(15)
>>> segment_tree.right(1)
3
>>> segment_tree.right(2)
5
>>> segment_tree.right(12)
25
"""
return idx * 2 + 1
def build(
self, idx: int, left_element: int, right_element: int, a: list[int]
) -> None:
if left_element == right_element:
self.segment_tree[idx] = a[left_element - 1]
else:
mid = (left_element + right_element) // 2
self.build(self.left(idx), left_element, mid, a)
self.build(self.right(idx), mid + 1, right_element, a)
self.segment_tree[idx] = max(
self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)]
)
def update(
self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int
) -> bool:
"""
update with O(lg n) (Normal segment tree without lazy update will take O(nlg n)
for each update)
update(1, 1, size, a, b, v) for update val v to [a,b]
"""
if self.flag[idx] is True:
self.segment_tree[idx] = self.lazy[idx]
self.flag[idx] = False
if left_element != right_element:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if right_element < a or left_element > b:
return True
if left_element >= a and right_element <= b:
self.segment_tree[idx] = val
if left_element != right_element:
self.lazy[self.left(idx)] = val
self.lazy[self.right(idx)] = val
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
return True
mid = (left_element + right_element) // 2
self.update(self.left(idx), left_element, mid, a, b, val)
self.update(self.right(idx), mid + 1, right_element, a, b, val)
self.segment_tree[idx] = max(
self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)]
)
return True
# query with O(lg n)
def query(
self, idx: int, left_element: int, right_element: int, a: int, b: int
) -> int | float:
"""
query(1, 1, size, a, b) for query max of [a,b]
>>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
>>> segment_tree = SegmentTree(15)
>>> segment_tree.build(1, 1, 15, A)
>>> segment_tree.query(1, 1, 15, 4, 6)
7
>>> segment_tree.query(1, 1, 15, 7, 11)
14
>>> segment_tree.query(1, 1, 15, 7, 12)
15
"""
if self.flag[idx] is True:
self.segment_tree[idx] = self.lazy[idx]
self.flag[idx] = False
if left_element != right_element:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if right_element < a or left_element > b:
return -math.inf
if left_element >= a and right_element <= b:
return self.segment_tree[idx]
mid = (left_element + right_element) // 2
q1 = self.query(self.left(idx), left_element, mid, a, b)
q2 = self.query(self.right(idx), mid + 1, right_element, a, b)
return max(q1, q2)
def __str__(self) -> str:
return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)])
if __name__ == "__main__":
A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
size = 15
segt = SegmentTree(size)
segt.build(1, 1, size, A)
print(segt.query(1, 1, size, 4, 6))
print(segt.query(1, 1, size, 7, 11))
print(segt.query(1, 1, size, 7, 12))
segt.update(1, 1, size, 1, 3, 111)
print(segt.query(1, 1, size, 1, 15))
segt.update(1, 1, size, 7, 8, 235)
print(segt)
| from __future__ import annotations
import math
class SegmentTree:
def __init__(self, size: int) -> None:
self.size = size
# approximate the overall size of segment tree with given value
self.segment_tree = [0 for i in range(0, 4 * size)]
# create array to store lazy update
self.lazy = [0 for i in range(0, 4 * size)]
self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
def left(self, idx: int) -> int:
"""
>>> segment_tree = SegmentTree(15)
>>> segment_tree.left(1)
2
>>> segment_tree.left(2)
4
>>> segment_tree.left(12)
24
"""
return idx * 2
def right(self, idx: int) -> int:
"""
>>> segment_tree = SegmentTree(15)
>>> segment_tree.right(1)
3
>>> segment_tree.right(2)
5
>>> segment_tree.right(12)
25
"""
return idx * 2 + 1
def build(
self, idx: int, left_element: int, right_element: int, a: list[int]
) -> None:
if left_element == right_element:
self.segment_tree[idx] = a[left_element - 1]
else:
mid = (left_element + right_element) // 2
self.build(self.left(idx), left_element, mid, a)
self.build(self.right(idx), mid + 1, right_element, a)
self.segment_tree[idx] = max(
self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)]
)
def update(
self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int
) -> bool:
"""
update with O(lg n) (Normal segment tree without lazy update will take O(nlg n)
for each update)
update(1, 1, size, a, b, v) for update val v to [a,b]
"""
if self.flag[idx] is True:
self.segment_tree[idx] = self.lazy[idx]
self.flag[idx] = False
if left_element != right_element:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if right_element < a or left_element > b:
return True
if left_element >= a and right_element <= b:
self.segment_tree[idx] = val
if left_element != right_element:
self.lazy[self.left(idx)] = val
self.lazy[self.right(idx)] = val
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
return True
mid = (left_element + right_element) // 2
self.update(self.left(idx), left_element, mid, a, b, val)
self.update(self.right(idx), mid + 1, right_element, a, b, val)
self.segment_tree[idx] = max(
self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)]
)
return True
# query with O(lg n)
def query(
self, idx: int, left_element: int, right_element: int, a: int, b: int
) -> int | float:
"""
query(1, 1, size, a, b) for query max of [a,b]
>>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
>>> segment_tree = SegmentTree(15)
>>> segment_tree.build(1, 1, 15, A)
>>> segment_tree.query(1, 1, 15, 4, 6)
7
>>> segment_tree.query(1, 1, 15, 7, 11)
14
>>> segment_tree.query(1, 1, 15, 7, 12)
15
"""
if self.flag[idx] is True:
self.segment_tree[idx] = self.lazy[idx]
self.flag[idx] = False
if left_element != right_element:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if right_element < a or left_element > b:
return -math.inf
if left_element >= a and right_element <= b:
return self.segment_tree[idx]
mid = (left_element + right_element) // 2
q1 = self.query(self.left(idx), left_element, mid, a, b)
q2 = self.query(self.right(idx), mid + 1, right_element, a, b)
return max(q1, q2)
def __str__(self) -> str:
return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)])
if __name__ == "__main__":
A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
size = 15
segt = SegmentTree(size)
segt.build(1, 1, size, A)
print(segt.query(1, 1, size, 4, 6))
print(segt.query(1, 1, size, 7, 11))
print(segt.query(1, 1, size, 7, 12))
segt.update(1, 1, size, 1, 3, 111)
print(segt.query(1, 1, size, 1, 15))
segt.update(1, 1, size, 7, 8, 235)
print(segt)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Algorithm that merges two sorted linked lists into one sorted linked list.
"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class Node:
data: int
next_node: Node | None
class SortedLinkedList:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Node | None = None
for i in sorted(ints, reverse=True):
self.head = Node(i, self.head)
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))
True
>>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))
True
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(SortedLinkedList(range(i))) == i
True
True
True
>>> len(SortedLinkedList(test_data_odd))
8
"""
return sum(1 for _ in self)
def __str__(self) -> str:
"""
>>> str(SortedLinkedList([]))
''
>>> str(SortedLinkedList(test_data_odd))
'-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'
>>> str(SortedLinkedList(test_data_even))
'-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'
"""
return " -> ".join([str(node) for node in self])
def merge_lists(
sll_one: SortedLinkedList, sll_two: SortedLinkedList
) -> SortedLinkedList:
"""
>>> SSL = SortedLinkedList
>>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))
>>> len(merged)
16
>>> str(merged)
'-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'
>>> list(merged) == list(sorted(test_data_odd + test_data_even))
True
"""
return SortedLinkedList(list(sll_one) + list(sll_two))
if __name__ == "__main__":
import doctest
doctest.testmod()
SSL = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| """
Algorithm that merges two sorted linked lists into one sorted linked list.
"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class Node:
data: int
next_node: Node | None
class SortedLinkedList:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Node | None = None
for i in sorted(ints, reverse=True):
self.head = Node(i, self.head)
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))
True
>>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))
True
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(SortedLinkedList(range(i))) == i
True
True
True
>>> len(SortedLinkedList(test_data_odd))
8
"""
return sum(1 for _ in self)
def __str__(self) -> str:
"""
>>> str(SortedLinkedList([]))
''
>>> str(SortedLinkedList(test_data_odd))
'-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'
>>> str(SortedLinkedList(test_data_even))
'-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'
"""
return " -> ".join([str(node) for node in self])
def merge_lists(
sll_one: SortedLinkedList, sll_two: SortedLinkedList
) -> SortedLinkedList:
"""
>>> SSL = SortedLinkedList
>>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))
>>> len(merged)
16
>>> str(merged)
'-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'
>>> list(merged) == list(sorted(test_data_odd + test_data_even))
True
"""
return SortedLinkedList(list(sll_one) + list(sll_two))
if __name__ == "__main__":
import doctest
doctest.testmod()
SSL = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
== Liouville Lambda Function ==
The Liouville Lambda function, denoted by λ(n)
and λ(n) is 1 if n is the product of an even number of prime numbers,
and -1 if it is the product of an odd number of primes.
https://en.wikipedia.org/wiki/Liouville_function
"""
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
from maths.prime_factors import prime_factors
def liouville_lambda(number: int) -> int:
"""
This functions takes an integer number as input.
returns 1 if n has even number of prime factors and -1 otherwise.
>>> liouville_lambda(10)
1
>>> liouville_lambda(11)
-1
>>> liouville_lambda(0)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> liouville_lambda(-1)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> liouville_lambda(11.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=11.0] must be an integer
"""
if not isinstance(number, int):
msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1:
raise ValueError("Input must be a positive integer")
return -1 if len(prime_factors(number)) % 2 else 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
== Liouville Lambda Function ==
The Liouville Lambda function, denoted by λ(n)
and λ(n) is 1 if n is the product of an even number of prime numbers,
and -1 if it is the product of an odd number of primes.
https://en.wikipedia.org/wiki/Liouville_function
"""
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
from maths.prime_factors import prime_factors
def liouville_lambda(number: int) -> int:
"""
This functions takes an integer number as input.
returns 1 if n has even number of prime factors and -1 otherwise.
>>> liouville_lambda(10)
1
>>> liouville_lambda(11)
-1
>>> liouville_lambda(0)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> liouville_lambda(-1)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> liouville_lambda(11.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=11.0] must be an integer
"""
if not isinstance(number, int):
msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1:
raise ValueError("Input must be a positive integer")
return -1 if len(prime_factors(number)) % 2 else 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
In the Combination Sum problem, we are given a list consisting of distinct integers.
We need to find all the combinations whose sum equals to target given.
We can use an element more than one.
Time complexity(Average Case): O(n!)
Constraints:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40
"""
def backtrack(
candidates: list, path: list, answer: list, target: int, previous_index: int
) -> None:
"""
A recursive function that searches for possible combinations. Backtracks in case
of a bigger current combination value than the target value.
Parameters
----------
previous_index: Last index from the previous search
target: The value we need to obtain by summing our integers in the path list.
answer: A list of possible combinations
path: Current combination
candidates: A list of integers we can use.
"""
if target == 0:
answer.append(path.copy())
else:
for index in range(previous_index, len(candidates)):
if target >= candidates[index]:
path.append(candidates[index])
backtrack(candidates, path, answer, target - candidates[index], index)
path.pop(len(path) - 1)
def combination_sum(candidates: list, target: int) -> list:
"""
>>> combination_sum([2, 3, 5], 8)
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
>>> combination_sum([2, 3, 6, 7], 7)
[[2, 2, 3], [7]]
>>> combination_sum([-8, 2.3, 0], 1)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded in comparison
"""
path = [] # type: list[int]
answer = [] # type: list[int]
backtrack(candidates, path, answer, target, 0)
return answer
def main() -> None:
print(combination_sum([-8, 2.3, 0], 1))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| """
In the Combination Sum problem, we are given a list consisting of distinct integers.
We need to find all the combinations whose sum equals to target given.
We can use an element more than one.
Time complexity(Average Case): O(n!)
Constraints:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40
"""
def backtrack(
candidates: list, path: list, answer: list, target: int, previous_index: int
) -> None:
"""
A recursive function that searches for possible combinations. Backtracks in case
of a bigger current combination value than the target value.
Parameters
----------
previous_index: Last index from the previous search
target: The value we need to obtain by summing our integers in the path list.
answer: A list of possible combinations
path: Current combination
candidates: A list of integers we can use.
"""
if target == 0:
answer.append(path.copy())
else:
for index in range(previous_index, len(candidates)):
if target >= candidates[index]:
path.append(candidates[index])
backtrack(candidates, path, answer, target - candidates[index], index)
path.pop(len(path) - 1)
def combination_sum(candidates: list, target: int) -> list:
"""
>>> combination_sum([2, 3, 5], 8)
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
>>> combination_sum([2, 3, 6, 7], 7)
[[2, 2, 3], [7]]
>>> combination_sum([-8, 2.3, 0], 1)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded in comparison
"""
path = [] # type: list[int]
answer = [] # type: list[int]
backtrack(candidates, path, answer, target, 0)
return answer
def main() -> None:
print(combination_sum([-8, 2.3, 0], 1))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from __future__ import annotations
def dfs(u):
global graph, reversed_graph, scc, component, visit, stack
if visit[u]:
return
visit[u] = True
for v in graph[u]:
dfs(v)
stack.append(u)
def dfs2(u):
global graph, reversed_graph, scc, component, visit, stack
if visit[u]:
return
visit[u] = True
component.append(u)
for v in reversed_graph[u]:
dfs2(v)
def kosaraju():
global graph, reversed_graph, scc, component, visit, stack
for i in range(n):
dfs(i)
visit = [False] * n
for i in stack[::-1]:
if visit[i]:
continue
component = []
dfs2(i)
scc.append(component)
return scc
if __name__ == "__main__":
# n - no of nodes, m - no of edges
n, m = list(map(int, input().strip().split()))
graph: list[list[int]] = [[] for _ in range(n)] # graph
reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph
# input graph data (edges)
for _ in range(m):
u, v = list(map(int, input().strip().split()))
graph[u].append(v)
reversed_graph[v].append(u)
stack: list[int] = []
visit: list[bool] = [False] * n
scc: list[int] = []
component: list[int] = []
print(kosaraju())
| from __future__ import annotations
def dfs(u):
global graph, reversed_graph, scc, component, visit, stack
if visit[u]:
return
visit[u] = True
for v in graph[u]:
dfs(v)
stack.append(u)
def dfs2(u):
global graph, reversed_graph, scc, component, visit, stack
if visit[u]:
return
visit[u] = True
component.append(u)
for v in reversed_graph[u]:
dfs2(v)
def kosaraju():
global graph, reversed_graph, scc, component, visit, stack
for i in range(n):
dfs(i)
visit = [False] * n
for i in stack[::-1]:
if visit[i]:
continue
component = []
dfs2(i)
scc.append(component)
return scc
if __name__ == "__main__":
# n - no of nodes, m - no of edges
n, m = list(map(int, input().strip().split()))
graph: list[list[int]] = [[] for _ in range(n)] # graph
reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph
# input graph data (edges)
for _ in range(m):
u, v = list(map(int, input().strip().split()))
graph[u].append(v)
reversed_graph[v].append(u)
stack: list[int] = []
visit: list[bool] = [False] * n
scc: list[int] = []
component: list[int] = []
print(kosaraju())
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| #!/usr/bin/env python3
"""
Build a half-adder quantum circuit that takes two bits as input,
encodes them into qubits, then runs the half-adder circuit calculating
the sum and carry qubits, observed over 1000 runs of the experiment
.
References:
https://en.wikipedia.org/wiki/Adder_(electronics)
https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add-
"""
import qiskit
def half_adder(bit0: int, bit1: int) -> qiskit.result.counts.Counts:
"""
>>> half_adder(0, 0)
{'00': 1000}
>>> half_adder(0, 1)
{'01': 1000}
>>> half_adder(1, 0)
{'01': 1000}
>>> half_adder(1, 1)
{'10': 1000}
"""
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
qc_ha = qiskit.QuantumCircuit(4, 2)
# encode inputs in qubits 0 and 1
if bit0 == 1:
qc_ha.x(0)
if bit1 == 1:
qc_ha.x(1)
qc_ha.barrier()
# use cnots to write XOR of the inputs on qubit2
qc_ha.cx(0, 2)
qc_ha.cx(1, 2)
# use ccx / toffoli gate to write AND of the inputs on qubit3
qc_ha.ccx(0, 1, 3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2, 0) # extract XOR value
qc_ha.measure(3, 1) # extract AND value
# Execute the circuit on the qasm simulator
job = qiskit.execute(qc_ha, simulator, shots=1000)
# Return the histogram data of the results of the experiment
return job.result().get_counts(qc_ha)
if __name__ == "__main__":
counts = half_adder(1, 1)
print(f"Half Adder Output Qubit Counts: {counts}")
| #!/usr/bin/env python3
"""
Build a half-adder quantum circuit that takes two bits as input,
encodes them into qubits, then runs the half-adder circuit calculating
the sum and carry qubits, observed over 1000 runs of the experiment
.
References:
https://en.wikipedia.org/wiki/Adder_(electronics)
https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add-
"""
import qiskit
def half_adder(bit0: int, bit1: int) -> qiskit.result.counts.Counts:
"""
>>> half_adder(0, 0)
{'00': 1000}
>>> half_adder(0, 1)
{'01': 1000}
>>> half_adder(1, 0)
{'01': 1000}
>>> half_adder(1, 1)
{'10': 1000}
"""
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
qc_ha = qiskit.QuantumCircuit(4, 2)
# encode inputs in qubits 0 and 1
if bit0 == 1:
qc_ha.x(0)
if bit1 == 1:
qc_ha.x(1)
qc_ha.barrier()
# use cnots to write XOR of the inputs on qubit2
qc_ha.cx(0, 2)
qc_ha.cx(1, 2)
# use ccx / toffoli gate to write AND of the inputs on qubit3
qc_ha.ccx(0, 1, 3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2, 0) # extract XOR value
qc_ha.measure(3, 1) # extract AND value
# Execute the circuit on the qasm simulator
job = qiskit.execute(qc_ha, simulator, shots=1000)
# Return the histogram data of the results of the experiment
return job.result().get_counts(qc_ha)
if __name__ == "__main__":
counts = half_adder(1, 1)
print(f"Half Adder Output Qubit Counts: {counts}")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import sys
from collections import defaultdict
class Heap:
def __init__(self):
self.node_position = []
def get_position(self, vertex):
return self.node_position[vertex]
def set_position(self, vertex, pos):
self.node_position[vertex] = pos
def top_to_bottom(self, heap, start, size, positions):
if start > size // 2 - 1:
return
else:
if 2 * start + 2 >= size:
smallest_child = 2 * start + 1
else:
if heap[2 * start + 1] < heap[2 * start + 2]:
smallest_child = 2 * start + 1
else:
smallest_child = 2 * start + 2
if heap[smallest_child] < heap[start]:
temp, temp1 = heap[smallest_child], positions[smallest_child]
heap[smallest_child], positions[smallest_child] = (
heap[start],
positions[start],
)
heap[start], positions[start] = temp, temp1
temp = self.get_position(positions[smallest_child])
self.set_position(
positions[smallest_child], self.get_position(positions[start])
)
self.set_position(positions[start], temp)
self.top_to_bottom(heap, smallest_child, size, positions)
# Update function if value of any node in min-heap decreases
def bottom_to_top(self, val, index, heap, position):
temp = position[index]
while index != 0:
parent = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
if val < heap[parent]:
heap[index] = heap[parent]
position[index] = position[parent]
self.set_position(position[parent], index)
else:
heap[index] = val
position[index] = temp
self.set_position(temp, index)
break
index = parent
else:
heap[0] = val
position[0] = temp
self.set_position(temp, 0)
def heapify(self, heap, positions):
start = len(heap) // 2 - 1
for i in range(start, -1, -1):
self.top_to_bottom(heap, i, len(heap), positions)
def delete_minimum(self, heap, positions):
temp = positions[0]
heap[0] = sys.maxsize
self.top_to_bottom(heap, 0, len(heap), positions)
return temp
def prisms_algorithm(adjacency_list):
"""
>>> adjacency_list = {0: [[1, 1], [3, 3]],
... 1: [[0, 1], [2, 6], [3, 5], [4, 1]],
... 2: [[1, 6], [4, 5], [5, 2]],
... 3: [[0, 3], [1, 5], [4, 1]],
... 4: [[1, 1], [2, 5], [3, 1], [5, 4]],
... 5: [[2, 2], [4, 4]]}
>>> prisms_algorithm(adjacency_list)
[(0, 1), (1, 4), (4, 3), (4, 5), (5, 2)]
"""
heap = Heap()
visited = [0] * len(adjacency_list)
nbr_tv = [-1] * len(adjacency_list) # Neighboring Tree Vertex of selected vertex
# Minimum Distance of explored vertex with neighboring vertex of partial tree
# formed in graph
distance_tv = [] # Heap of Distance of vertices from their neighboring vertex
positions = []
for vertex in range(len(adjacency_list)):
distance_tv.append(sys.maxsize)
positions.append(vertex)
heap.node_position.append(vertex)
tree_edges = []
visited[0] = 1
distance_tv[0] = sys.maxsize
for neighbor, distance in adjacency_list[0]:
nbr_tv[neighbor] = 0
distance_tv[neighbor] = distance
heap.heapify(distance_tv, positions)
for _ in range(1, len(adjacency_list)):
vertex = heap.delete_minimum(distance_tv, positions)
if visited[vertex] == 0:
tree_edges.append((nbr_tv[vertex], vertex))
visited[vertex] = 1
for neighbor, distance in adjacency_list[vertex]:
if (
visited[neighbor] == 0
and distance < distance_tv[heap.get_position(neighbor)]
):
distance_tv[heap.get_position(neighbor)] = distance
heap.bottom_to_top(
distance, heap.get_position(neighbor), distance_tv, positions
)
nbr_tv[neighbor] = vertex
return tree_edges
if __name__ == "__main__": # pragma: no cover
# < --------- Prims Algorithm --------- >
edges_number = int(input("Enter number of edges: ").strip())
adjacency_list = defaultdict(list)
for _ in range(edges_number):
edge = [int(x) for x in input().strip().split()]
adjacency_list[edge[0]].append([edge[1], edge[2]])
adjacency_list[edge[1]].append([edge[0], edge[2]])
print(prisms_algorithm(adjacency_list))
| import sys
from collections import defaultdict
class Heap:
def __init__(self):
self.node_position = []
def get_position(self, vertex):
return self.node_position[vertex]
def set_position(self, vertex, pos):
self.node_position[vertex] = pos
def top_to_bottom(self, heap, start, size, positions):
if start > size // 2 - 1:
return
else:
if 2 * start + 2 >= size:
smallest_child = 2 * start + 1
else:
if heap[2 * start + 1] < heap[2 * start + 2]:
smallest_child = 2 * start + 1
else:
smallest_child = 2 * start + 2
if heap[smallest_child] < heap[start]:
temp, temp1 = heap[smallest_child], positions[smallest_child]
heap[smallest_child], positions[smallest_child] = (
heap[start],
positions[start],
)
heap[start], positions[start] = temp, temp1
temp = self.get_position(positions[smallest_child])
self.set_position(
positions[smallest_child], self.get_position(positions[start])
)
self.set_position(positions[start], temp)
self.top_to_bottom(heap, smallest_child, size, positions)
# Update function if value of any node in min-heap decreases
def bottom_to_top(self, val, index, heap, position):
temp = position[index]
while index != 0:
parent = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
if val < heap[parent]:
heap[index] = heap[parent]
position[index] = position[parent]
self.set_position(position[parent], index)
else:
heap[index] = val
position[index] = temp
self.set_position(temp, index)
break
index = parent
else:
heap[0] = val
position[0] = temp
self.set_position(temp, 0)
def heapify(self, heap, positions):
start = len(heap) // 2 - 1
for i in range(start, -1, -1):
self.top_to_bottom(heap, i, len(heap), positions)
def delete_minimum(self, heap, positions):
temp = positions[0]
heap[0] = sys.maxsize
self.top_to_bottom(heap, 0, len(heap), positions)
return temp
def prisms_algorithm(adjacency_list):
"""
>>> adjacency_list = {0: [[1, 1], [3, 3]],
... 1: [[0, 1], [2, 6], [3, 5], [4, 1]],
... 2: [[1, 6], [4, 5], [5, 2]],
... 3: [[0, 3], [1, 5], [4, 1]],
... 4: [[1, 1], [2, 5], [3, 1], [5, 4]],
... 5: [[2, 2], [4, 4]]}
>>> prisms_algorithm(adjacency_list)
[(0, 1), (1, 4), (4, 3), (4, 5), (5, 2)]
"""
heap = Heap()
visited = [0] * len(adjacency_list)
nbr_tv = [-1] * len(adjacency_list) # Neighboring Tree Vertex of selected vertex
# Minimum Distance of explored vertex with neighboring vertex of partial tree
# formed in graph
distance_tv = [] # Heap of Distance of vertices from their neighboring vertex
positions = []
for vertex in range(len(adjacency_list)):
distance_tv.append(sys.maxsize)
positions.append(vertex)
heap.node_position.append(vertex)
tree_edges = []
visited[0] = 1
distance_tv[0] = sys.maxsize
for neighbor, distance in adjacency_list[0]:
nbr_tv[neighbor] = 0
distance_tv[neighbor] = distance
heap.heapify(distance_tv, positions)
for _ in range(1, len(adjacency_list)):
vertex = heap.delete_minimum(distance_tv, positions)
if visited[vertex] == 0:
tree_edges.append((nbr_tv[vertex], vertex))
visited[vertex] = 1
for neighbor, distance in adjacency_list[vertex]:
if (
visited[neighbor] == 0
and distance < distance_tv[heap.get_position(neighbor)]
):
distance_tv[heap.get_position(neighbor)] = distance
heap.bottom_to_top(
distance, heap.get_position(neighbor), distance_tv, positions
)
nbr_tv[neighbor] = vertex
return tree_edges
if __name__ == "__main__": # pragma: no cover
# < --------- Prims Algorithm --------- >
edges_number = int(input("Enter number of edges: ").strip())
adjacency_list = defaultdict(list)
for _ in range(edges_number):
edge = [int(x) for x in input().strip().split()]
adjacency_list[edge[0]].append([edge[1], edge[2]])
adjacency_list[edge[1]].append([edge[0], edge[2]])
print(prisms_algorithm(adjacency_list))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import os
from string import ascii_letters
LETTERS_AND_SPACE = ascii_letters + " \t\n"
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words
ENGLISH_WORDS = load_dictionary()
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
matches = len([word for word in possible_words if word in ENGLISH_WORDS])
return float(matches) / len(possible_words)
def remove_non_letters(message: str) -> str:
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
"""
>>> is_english('Hello World')
True
>>> is_english('llold HorWd')
False
"""
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = message_letters_percentage >= letter_percentage
return words_match and letters_match
if __name__ == "__main__":
import doctest
doctest.testmod()
| import os
from string import ascii_letters
LETTERS_AND_SPACE = ascii_letters + " \t\n"
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words
ENGLISH_WORDS = load_dictionary()
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
matches = len([word for word in possible_words if word in ENGLISH_WORDS])
return float(matches) / len(possible_words)
def remove_non_letters(message: str) -> str:
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
"""
>>> is_english('Hello World')
True
>>> is_english('llold HorWd')
False
"""
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = message_letters_percentage >= letter_percentage
return words_match and letters_match
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from math import log
from scipy.constants import Boltzmann, physical_constants
T = 300 # TEMPERATURE (unit = K)
def builtin_voltage(
donor_conc: float, # donor concentration
acceptor_conc: float, # acceptor concentration
intrinsic_conc: float, # intrinsic concentration
) -> float:
"""
This function can calculate the Builtin Voltage of a pn junction diode.
This is calculated from the given three values.
Examples -
>>> builtin_voltage(donor_conc=1e17, acceptor_conc=1e17, intrinsic_conc=1e10)
0.833370010652644
>>> builtin_voltage(donor_conc=0, acceptor_conc=1600, intrinsic_conc=200)
Traceback (most recent call last):
...
ValueError: Donor concentration should be positive
>>> builtin_voltage(donor_conc=1000, acceptor_conc=0, intrinsic_conc=1200)
Traceback (most recent call last):
...
ValueError: Acceptor concentration should be positive
>>> builtin_voltage(donor_conc=1000, acceptor_conc=1000, intrinsic_conc=0)
Traceback (most recent call last):
...
ValueError: Intrinsic concentration should be positive
>>> builtin_voltage(donor_conc=1000, acceptor_conc=3000, intrinsic_conc=2000)
Traceback (most recent call last):
...
ValueError: Donor concentration should be greater than intrinsic concentration
>>> builtin_voltage(donor_conc=3000, acceptor_conc=1000, intrinsic_conc=2000)
Traceback (most recent call last):
...
ValueError: Acceptor concentration should be greater than intrinsic concentration
"""
if donor_conc <= 0:
raise ValueError("Donor concentration should be positive")
elif acceptor_conc <= 0:
raise ValueError("Acceptor concentration should be positive")
elif intrinsic_conc <= 0:
raise ValueError("Intrinsic concentration should be positive")
elif donor_conc <= intrinsic_conc:
raise ValueError(
"Donor concentration should be greater than intrinsic concentration"
)
elif acceptor_conc <= intrinsic_conc:
raise ValueError(
"Acceptor concentration should be greater than intrinsic concentration"
)
else:
return (
Boltzmann
* T
* log((donor_conc * acceptor_conc) / intrinsic_conc**2)
/ physical_constants["electron volt"][0]
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| from math import log
from scipy.constants import Boltzmann, physical_constants
T = 300 # TEMPERATURE (unit = K)
def builtin_voltage(
donor_conc: float, # donor concentration
acceptor_conc: float, # acceptor concentration
intrinsic_conc: float, # intrinsic concentration
) -> float:
"""
This function can calculate the Builtin Voltage of a pn junction diode.
This is calculated from the given three values.
Examples -
>>> builtin_voltage(donor_conc=1e17, acceptor_conc=1e17, intrinsic_conc=1e10)
0.833370010652644
>>> builtin_voltage(donor_conc=0, acceptor_conc=1600, intrinsic_conc=200)
Traceback (most recent call last):
...
ValueError: Donor concentration should be positive
>>> builtin_voltage(donor_conc=1000, acceptor_conc=0, intrinsic_conc=1200)
Traceback (most recent call last):
...
ValueError: Acceptor concentration should be positive
>>> builtin_voltage(donor_conc=1000, acceptor_conc=1000, intrinsic_conc=0)
Traceback (most recent call last):
...
ValueError: Intrinsic concentration should be positive
>>> builtin_voltage(donor_conc=1000, acceptor_conc=3000, intrinsic_conc=2000)
Traceback (most recent call last):
...
ValueError: Donor concentration should be greater than intrinsic concentration
>>> builtin_voltage(donor_conc=3000, acceptor_conc=1000, intrinsic_conc=2000)
Traceback (most recent call last):
...
ValueError: Acceptor concentration should be greater than intrinsic concentration
"""
if donor_conc <= 0:
raise ValueError("Donor concentration should be positive")
elif acceptor_conc <= 0:
raise ValueError("Acceptor concentration should be positive")
elif intrinsic_conc <= 0:
raise ValueError("Intrinsic concentration should be positive")
elif donor_conc <= intrinsic_conc:
raise ValueError(
"Donor concentration should be greater than intrinsic concentration"
)
elif acceptor_conc <= intrinsic_conc:
raise ValueError(
"Acceptor concentration should be greater than intrinsic concentration"
)
else:
return (
Boltzmann
* T
* log((donor_conc * acceptor_conc) / intrinsic_conc**2)
/ physical_constants["electron volt"][0]
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 36
https://projecteuler.net/problem=36
Problem Statement:
Double-base palindromes
Problem 36
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in
base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
"""
from __future__ import annotations
def is_palindrome(n: int | str) -> bool:
"""
Return true if the input n is a palindrome.
Otherwise return false. n can be an integer or a string.
>>> is_palindrome(909)
True
>>> is_palindrome(908)
False
>>> is_palindrome('10101')
True
>>> is_palindrome('10111')
False
"""
n = str(n)
return n == n[::-1]
def solution(n: int = 1000000):
"""Return the sum of all numbers, less than n , which are palindromic in
base 10 and base 2.
>>> solution(1000000)
872187
>>> solution(500000)
286602
>>> solution(100000)
286602
>>> solution(1000)
1772
>>> solution(100)
157
>>> solution(10)
25
>>> solution(2)
1
>>> solution(1)
0
"""
total = 0
for i in range(1, n):
if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| """
Project Euler Problem 36
https://projecteuler.net/problem=36
Problem Statement:
Double-base palindromes
Problem 36
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in
base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
"""
from __future__ import annotations
def is_palindrome(n: int | str) -> bool:
"""
Return true if the input n is a palindrome.
Otherwise return false. n can be an integer or a string.
>>> is_palindrome(909)
True
>>> is_palindrome(908)
False
>>> is_palindrome('10101')
True
>>> is_palindrome('10111')
False
"""
n = str(n)
return n == n[::-1]
def solution(n: int = 1000000):
"""Return the sum of all numbers, less than n , which are palindromic in
base 10 and base 2.
>>> solution(1000000)
872187
>>> solution(500000)
286602
>>> solution(100000)
286602
>>> solution(1000)
1772
>>> solution(100)
157
>>> solution(10)
25
>>> solution(2)
1
>>> solution(1)
0
"""
total = 0
for i in range(1, n):
if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Problem source: https://www.hackerrank.com/challenges/the-power-sum/problem
Find the number of ways that a given integer X, can be expressed as the sum
of the Nth powers of unique, natural numbers. For example, if X=13 and N=2.
We have to find all combinations of unique squares adding up to 13.
The only solution is 2^2+3^2. Constraints: 1<=X<=1000, 2<=N<=10.
"""
from math import pow
def backtrack(
needed_sum: int,
power: int,
current_number: int,
current_sum: int,
solutions_count: int,
) -> tuple[int, int]:
"""
>>> backtrack(13, 2, 1, 0, 0)
(0, 1)
>>> backtrack(100, 2, 1, 0, 0)
(0, 3)
>>> backtrack(100, 3, 1, 0, 0)
(0, 1)
>>> backtrack(800, 2, 1, 0, 0)
(0, 561)
>>> backtrack(1000, 10, 1, 0, 0)
(0, 0)
>>> backtrack(400, 2, 1, 0, 0)
(0, 55)
>>> backtrack(50, 1, 1, 0, 0)
(0, 3658)
"""
if current_sum == needed_sum:
# If the sum of the powers is equal to needed_sum, then we have a solution.
solutions_count += 1
return current_sum, solutions_count
i_to_n = int(pow(current_number, power))
if current_sum + i_to_n <= needed_sum:
# If the sum of the powers is less than needed_sum, then continue adding powers.
current_sum += i_to_n
current_sum, solutions_count = backtrack(
needed_sum, power, current_number + 1, current_sum, solutions_count
)
current_sum -= i_to_n
if i_to_n < needed_sum:
# If the power of i is less than needed_sum, then try with the next power.
current_sum, solutions_count = backtrack(
needed_sum, power, current_number + 1, current_sum, solutions_count
)
return current_sum, solutions_count
def solve(needed_sum: int, power: int) -> int:
"""
>>> solve(13, 2)
1
>>> solve(100, 2)
3
>>> solve(100, 3)
1
>>> solve(800, 2)
561
>>> solve(1000, 10)
0
>>> solve(400, 2)
55
>>> solve(50, 1)
Traceback (most recent call last):
...
ValueError: Invalid input
needed_sum must be between 1 and 1000, power between 2 and 10.
>>> solve(-10, 5)
Traceback (most recent call last):
...
ValueError: Invalid input
needed_sum must be between 1 and 1000, power between 2 and 10.
"""
if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
raise ValueError(
"Invalid input\n"
"needed_sum must be between 1 and 1000, power between 2 and 10."
)
return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Problem source: https://www.hackerrank.com/challenges/the-power-sum/problem
Find the number of ways that a given integer X, can be expressed as the sum
of the Nth powers of unique, natural numbers. For example, if X=13 and N=2.
We have to find all combinations of unique squares adding up to 13.
The only solution is 2^2+3^2. Constraints: 1<=X<=1000, 2<=N<=10.
"""
from math import pow
def backtrack(
needed_sum: int,
power: int,
current_number: int,
current_sum: int,
solutions_count: int,
) -> tuple[int, int]:
"""
>>> backtrack(13, 2, 1, 0, 0)
(0, 1)
>>> backtrack(100, 2, 1, 0, 0)
(0, 3)
>>> backtrack(100, 3, 1, 0, 0)
(0, 1)
>>> backtrack(800, 2, 1, 0, 0)
(0, 561)
>>> backtrack(1000, 10, 1, 0, 0)
(0, 0)
>>> backtrack(400, 2, 1, 0, 0)
(0, 55)
>>> backtrack(50, 1, 1, 0, 0)
(0, 3658)
"""
if current_sum == needed_sum:
# If the sum of the powers is equal to needed_sum, then we have a solution.
solutions_count += 1
return current_sum, solutions_count
i_to_n = int(pow(current_number, power))
if current_sum + i_to_n <= needed_sum:
# If the sum of the powers is less than needed_sum, then continue adding powers.
current_sum += i_to_n
current_sum, solutions_count = backtrack(
needed_sum, power, current_number + 1, current_sum, solutions_count
)
current_sum -= i_to_n
if i_to_n < needed_sum:
# If the power of i is less than needed_sum, then try with the next power.
current_sum, solutions_count = backtrack(
needed_sum, power, current_number + 1, current_sum, solutions_count
)
return current_sum, solutions_count
def solve(needed_sum: int, power: int) -> int:
"""
>>> solve(13, 2)
1
>>> solve(100, 2)
3
>>> solve(100, 3)
1
>>> solve(800, 2)
561
>>> solve(1000, 10)
0
>>> solve(400, 2)
55
>>> solve(50, 1)
Traceback (most recent call last):
...
ValueError: Invalid input
needed_sum must be between 1 and 1000, power between 2 and 10.
>>> solve(-10, 5)
Traceback (most recent call last):
...
ValueError: Invalid input
needed_sum must be between 1 and 1000, power between 2 and 10.
"""
if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
raise ValueError(
"Invalid input\n"
"needed_sum must be between 1 and 1000, power between 2 and 10."
)
return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Author : Alexander Pantyukhin
Date : December 12, 2022
Task:
Given a string and a list of words, return true if the string can be
segmented into a space-separated sequence of one or more words.
Note that the same word may be reused
multiple times in the segmentation.
Implementation notes: Trie + Dynamic programming up -> down.
The Trie will be used to store the words. It will be useful for scanning
available words for the current position in the string.
Leetcode:
https://leetcode.com/problems/word-break/description/
Runtime: O(n * n)
Space: O(n)
"""
import functools
from typing import Any
def word_break(string: str, words: list[str]) -> bool:
"""
Return True if numbers have opposite signs False otherwise.
>>> word_break("applepenapple", ["apple","pen"])
True
>>> word_break("catsandog", ["cats","dog","sand","and","cat"])
False
>>> word_break("cars", ["car","ca","rs"])
True
>>> word_break('abc', [])
False
>>> word_break(123, ['a'])
Traceback (most recent call last):
...
ValueError: the string should be not empty string
>>> word_break('', ['a'])
Traceback (most recent call last):
...
ValueError: the string should be not empty string
>>> word_break('abc', [123])
Traceback (most recent call last):
...
ValueError: the words should be a list of non-empty strings
>>> word_break('abc', [''])
Traceback (most recent call last):
...
ValueError: the words should be a list of non-empty strings
"""
# Validation
if not isinstance(string, str) or len(string) == 0:
raise ValueError("the string should be not empty string")
if not isinstance(words, list) or not all(
isinstance(item, str) and len(item) > 0 for item in words
):
raise ValueError("the words should be a list of non-empty strings")
# Build trie
trie: dict[str, Any] = {}
word_keeper_key = "WORD_KEEPER"
for word in words:
trie_node = trie
for c in word:
if c not in trie_node:
trie_node[c] = {}
trie_node = trie_node[c]
trie_node[word_keeper_key] = True
len_string = len(string)
# Dynamic programming method
@functools.cache
def is_breakable(index: int) -> bool:
"""
>>> string = 'a'
>>> is_breakable(1)
True
"""
if index == len_string:
return True
trie_node = trie
for i in range(index, len_string):
trie_node = trie_node.get(string[i], None)
if trie_node is None:
return False
if trie_node.get(word_keeper_key, False) and is_breakable(i + 1):
return True
return False
return is_breakable(0)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Author : Alexander Pantyukhin
Date : December 12, 2022
Task:
Given a string and a list of words, return true if the string can be
segmented into a space-separated sequence of one or more words.
Note that the same word may be reused
multiple times in the segmentation.
Implementation notes: Trie + Dynamic programming up -> down.
The Trie will be used to store the words. It will be useful for scanning
available words for the current position in the string.
Leetcode:
https://leetcode.com/problems/word-break/description/
Runtime: O(n * n)
Space: O(n)
"""
import functools
from typing import Any
def word_break(string: str, words: list[str]) -> bool:
"""
Return True if numbers have opposite signs False otherwise.
>>> word_break("applepenapple", ["apple","pen"])
True
>>> word_break("catsandog", ["cats","dog","sand","and","cat"])
False
>>> word_break("cars", ["car","ca","rs"])
True
>>> word_break('abc', [])
False
>>> word_break(123, ['a'])
Traceback (most recent call last):
...
ValueError: the string should be not empty string
>>> word_break('', ['a'])
Traceback (most recent call last):
...
ValueError: the string should be not empty string
>>> word_break('abc', [123])
Traceback (most recent call last):
...
ValueError: the words should be a list of non-empty strings
>>> word_break('abc', [''])
Traceback (most recent call last):
...
ValueError: the words should be a list of non-empty strings
"""
# Validation
if not isinstance(string, str) or len(string) == 0:
raise ValueError("the string should be not empty string")
if not isinstance(words, list) or not all(
isinstance(item, str) and len(item) > 0 for item in words
):
raise ValueError("the words should be a list of non-empty strings")
# Build trie
trie: dict[str, Any] = {}
word_keeper_key = "WORD_KEEPER"
for word in words:
trie_node = trie
for c in word:
if c not in trie_node:
trie_node[c] = {}
trie_node = trie_node[c]
trie_node[word_keeper_key] = True
len_string = len(string)
# Dynamic programming method
@functools.cache
def is_breakable(index: int) -> bool:
"""
>>> string = 'a'
>>> is_breakable(1)
True
"""
if index == len_string:
return True
trie_node = trie
for i in range(index, len_string):
trie_node = trie_node.get(string[i], None)
if trie_node is None:
return False
if trie_node.get(word_keeper_key, False) and is_breakable(i + 1):
return True
return False
return is_breakable(0)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from __future__ import annotations
def mean(nums: list) -> float:
"""
Find mean of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Mean
>>> mean([3, 6, 9, 12, 15, 18, 21])
12.0
>>> mean([5, 10, 15, 20, 25, 30, 35])
20.0
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
4.5
>>> mean([])
Traceback (most recent call last):
...
ValueError: List is empty
"""
if not nums:
raise ValueError("List is empty")
return sum(nums) / len(nums)
if __name__ == "__main__":
import doctest
doctest.testmod()
| from __future__ import annotations
def mean(nums: list) -> float:
"""
Find mean of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Mean
>>> mean([3, 6, 9, 12, 15, 18, 21])
12.0
>>> mean([5, 10, 15, 20, 25, 30, 35])
20.0
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
4.5
>>> mean([])
Traceback (most recent call last):
...
ValueError: List is empty
"""
if not nums:
raise ValueError("List is empty")
return sum(nums) / len(nums)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
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 | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import os
import sys
from . import rsa_key_generator as rkg
DEFAULT_BLOCK_SIZE = 128
BYTE_SIZE = 256
def get_blocks_from_text(
message: str, block_size: int = DEFAULT_BLOCK_SIZE
) -> list[int]:
message_bytes = message.encode("ascii")
block_ints = []
for block_start in range(0, len(message_bytes), block_size):
block_int = 0
for i in range(block_start, min(block_start + block_size, len(message_bytes))):
block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
block_ints.append(block_int)
return block_ints
def get_text_from_blocks(
block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE
) -> str:
message: list[str] = []
for block_int in block_ints:
block_message: list[str] = []
for i in range(block_size - 1, -1, -1):
if len(message) + i < message_length:
ascii_number = block_int // (BYTE_SIZE**i)
block_int = block_int % (BYTE_SIZE**i)
block_message.insert(0, chr(ascii_number))
message.extend(block_message)
return "".join(message)
def encrypt_message(
message: str, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE
) -> list[int]:
encrypted_blocks = []
n, e = key
for block in get_blocks_from_text(message, block_size):
encrypted_blocks.append(pow(block, e, n))
return encrypted_blocks
def decrypt_message(
encrypted_blocks: list[int],
message_length: int,
key: tuple[int, int],
block_size: int = DEFAULT_BLOCK_SIZE,
) -> str:
decrypted_blocks = []
n, d = key
for block in encrypted_blocks:
decrypted_blocks.append(pow(block, d, n))
return get_text_from_blocks(decrypted_blocks, message_length, block_size)
def read_key_file(key_filename: str) -> tuple[int, int, int]:
with open(key_filename) as fo:
content = fo.read()
key_size, n, eor_d = content.split(",")
return (int(key_size), int(n), int(eor_d))
def encrypt_and_write_to_file(
message_filename: str,
key_filename: str,
message: str,
block_size: int = DEFAULT_BLOCK_SIZE,
) -> str:
key_size, n, e = read_key_file(key_filename)
if key_size < block_size * 8:
sys.exit(
"ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
"requires the block size to be equal to or greater than the key size. "
"Either decrease the block size or use different keys.".format(
block_size * 8, key_size
)
)
encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)]
encrypted_content = ",".join(encrypted_blocks)
encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}"
with open(message_filename, "w") as fo:
fo.write(encrypted_content)
return encrypted_content
def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str:
key_size, n, d = read_key_file(key_filename)
with open(message_filename) as fo:
content = fo.read()
message_length_str, block_size_str, encrypted_message = content.split("_")
message_length = int(message_length_str)
block_size = int(block_size_str)
if key_size < block_size * 8:
sys.exit(
"ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
"requires the block size to be equal to or greater than the key size. "
"Did you specify the correct key file and encrypted file?".format(
block_size * 8, key_size
)
)
encrypted_blocks = []
for block in encrypted_message.split(","):
encrypted_blocks.append(int(block))
return decrypt_message(encrypted_blocks, message_length, (n, d), block_size)
def main() -> None:
filename = "encrypted_file.txt"
response = input(r"Encrypt\Decrypt [e\d]: ")
if response.lower().startswith("e"):
mode = "encrypt"
elif response.lower().startswith("d"):
mode = "decrypt"
if mode == "encrypt":
if not os.path.exists("rsa_pubkey.txt"):
rkg.make_key_files("rsa", 1024)
message = input("\nEnter message: ")
pubkey_filename = "rsa_pubkey.txt"
print(f"Encrypting and writing to {filename}...")
encrypted_text = encrypt_and_write_to_file(filename, pubkey_filename, message)
print("\nEncrypted text:")
print(encrypted_text)
elif mode == "decrypt":
privkey_filename = "rsa_privkey.txt"
print(f"Reading from {filename} and decrypting...")
decrypted_text = read_from_file_and_decrypt(filename, privkey_filename)
print("writing decryption to rsa_decryption.txt...")
with open("rsa_decryption.txt", "w") as dec:
dec.write(decrypted_text)
print("\nDecryption:")
print(decrypted_text)
if __name__ == "__main__":
main()
| import os
import sys
from . import rsa_key_generator as rkg
DEFAULT_BLOCK_SIZE = 128
BYTE_SIZE = 256
def get_blocks_from_text(
message: str, block_size: int = DEFAULT_BLOCK_SIZE
) -> list[int]:
message_bytes = message.encode("ascii")
block_ints = []
for block_start in range(0, len(message_bytes), block_size):
block_int = 0
for i in range(block_start, min(block_start + block_size, len(message_bytes))):
block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
block_ints.append(block_int)
return block_ints
def get_text_from_blocks(
block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE
) -> str:
message: list[str] = []
for block_int in block_ints:
block_message: list[str] = []
for i in range(block_size - 1, -1, -1):
if len(message) + i < message_length:
ascii_number = block_int // (BYTE_SIZE**i)
block_int = block_int % (BYTE_SIZE**i)
block_message.insert(0, chr(ascii_number))
message.extend(block_message)
return "".join(message)
def encrypt_message(
message: str, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE
) -> list[int]:
encrypted_blocks = []
n, e = key
for block in get_blocks_from_text(message, block_size):
encrypted_blocks.append(pow(block, e, n))
return encrypted_blocks
def decrypt_message(
encrypted_blocks: list[int],
message_length: int,
key: tuple[int, int],
block_size: int = DEFAULT_BLOCK_SIZE,
) -> str:
decrypted_blocks = []
n, d = key
for block in encrypted_blocks:
decrypted_blocks.append(pow(block, d, n))
return get_text_from_blocks(decrypted_blocks, message_length, block_size)
def read_key_file(key_filename: str) -> tuple[int, int, int]:
with open(key_filename) as fo:
content = fo.read()
key_size, n, eor_d = content.split(",")
return (int(key_size), int(n), int(eor_d))
def encrypt_and_write_to_file(
message_filename: str,
key_filename: str,
message: str,
block_size: int = DEFAULT_BLOCK_SIZE,
) -> str:
key_size, n, e = read_key_file(key_filename)
if key_size < block_size * 8:
sys.exit(
"ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
"requires the block size to be equal to or greater than the key size. "
"Either decrease the block size or use different keys.".format(
block_size * 8, key_size
)
)
encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)]
encrypted_content = ",".join(encrypted_blocks)
encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}"
with open(message_filename, "w") as fo:
fo.write(encrypted_content)
return encrypted_content
def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str:
key_size, n, d = read_key_file(key_filename)
with open(message_filename) as fo:
content = fo.read()
message_length_str, block_size_str, encrypted_message = content.split("_")
message_length = int(message_length_str)
block_size = int(block_size_str)
if key_size < block_size * 8:
sys.exit(
"ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
"requires the block size to be equal to or greater than the key size. "
"Did you specify the correct key file and encrypted file?".format(
block_size * 8, key_size
)
)
encrypted_blocks = []
for block in encrypted_message.split(","):
encrypted_blocks.append(int(block))
return decrypt_message(encrypted_blocks, message_length, (n, d), block_size)
def main() -> None:
filename = "encrypted_file.txt"
response = input(r"Encrypt\Decrypt [e\d]: ")
if response.lower().startswith("e"):
mode = "encrypt"
elif response.lower().startswith("d"):
mode = "decrypt"
if mode == "encrypt":
if not os.path.exists("rsa_pubkey.txt"):
rkg.make_key_files("rsa", 1024)
message = input("\nEnter message: ")
pubkey_filename = "rsa_pubkey.txt"
print(f"Encrypting and writing to {filename}...")
encrypted_text = encrypt_and_write_to_file(filename, pubkey_filename, message)
print("\nEncrypted text:")
print(encrypted_text)
elif mode == "decrypt":
privkey_filename = "rsa_privkey.txt"
print(f"Reading from {filename} and decrypting...")
decrypted_text = read_from_file_and_decrypt(filename, privkey_filename)
print("writing decryption to rsa_decryption.txt...")
with open("rsa_decryption.txt", "w") as dec:
dec.write(decrypted_text)
print("\nDecryption:")
print(decrypted_text)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| r"""
Problem: Given root of a binary tree, return the:
1. binary-tree-right-side-view
2. binary-tree-left-side-view
3. binary-tree-top-side-view
4. binary-tree-bottom-side-view
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: TreeNode | None = None
right: TreeNode | None = None
def make_tree() -> TreeNode:
"""
>>> make_tree().val
3
"""
return TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
def binary_tree_right_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the right side view of binary tree.
3 <- 3
/ \
9 20 <- 20
/ \
15 7 <- 7
>>> binary_tree_right_side_view(make_tree())
[3, 20, 7]
>>> binary_tree_right_side_view(None)
[]
"""
def depth_first_search(
root: TreeNode | None, depth: int, right_view: list[int]
) -> None:
"""
A depth first search preorder traversal to append the values at
right side of tree.
"""
if not root:
return
if depth == len(right_view):
right_view.append(root.val)
depth_first_search(root.right, depth + 1, right_view)
depth_first_search(root.left, depth + 1, right_view)
right_view: list = []
if not root:
return right_view
depth_first_search(root, 0, right_view)
return right_view
def binary_tree_left_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the left side view of binary tree.
3 -> 3
/ \
9 -> 9 20
/ \
15 -> 15 7
>>> binary_tree_left_side_view(make_tree())
[3, 9, 15]
>>> binary_tree_left_side_view(None)
[]
"""
def depth_first_search(
root: TreeNode | None, depth: int, left_view: list[int]
) -> None:
"""
A depth first search preorder traversal to append the values
at left side of tree.
"""
if not root:
return
if depth == len(left_view):
left_view.append(root.val)
depth_first_search(root.left, depth + 1, left_view)
depth_first_search(root.right, depth + 1, left_view)
left_view: list = []
if not root:
return left_view
depth_first_search(root, 0, left_view)
return left_view
def binary_tree_top_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the top side view of binary tree.
9 3 20 7
⬇ ⬇ ⬇ ⬇
3
/ \
9 20
/ \
15 7
>>> binary_tree_top_side_view(make_tree())
[9, 3, 20, 7]
>>> binary_tree_top_side_view(None)
[]
"""
def breadth_first_search(root: TreeNode, top_view: list[int]) -> None:
"""
A breadth first search traversal with defaultdict ds to append
the values of tree from top view
"""
queue = [(root, 0)]
lookup = defaultdict(list)
while queue:
first = queue.pop(0)
node, hd = first
lookup[hd].append(node.val)
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
for pair in sorted(lookup.items(), key=lambda each: each[0]):
top_view.append(pair[1][0])
top_view: list = []
if not root:
return top_view
breadth_first_search(root, top_view)
return top_view
def binary_tree_bottom_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the bottom side view of binary tree
3
/ \
9 20
/ \
15 7
↑ ↑ ↑ ↑
9 15 20 7
>>> binary_tree_bottom_side_view(make_tree())
[9, 15, 20, 7]
>>> binary_tree_bottom_side_view(None)
[]
"""
from collections import defaultdict
def breadth_first_search(root: TreeNode, bottom_view: list[int]) -> None:
"""
A breadth first search traversal with defaultdict ds to append
the values of tree from bottom view
"""
queue = [(root, 0)]
lookup = defaultdict(list)
while queue:
first = queue.pop(0)
node, hd = first
lookup[hd].append(node.val)
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
for pair in sorted(lookup.items(), key=lambda each: each[0]):
bottom_view.append(pair[1][-1])
bottom_view: list = []
if not root:
return bottom_view
breadth_first_search(root, bottom_view)
return bottom_view
if __name__ == "__main__":
import doctest
doctest.testmod()
| r"""
Problem: Given root of a binary tree, return the:
1. binary-tree-right-side-view
2. binary-tree-left-side-view
3. binary-tree-top-side-view
4. binary-tree-bottom-side-view
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: TreeNode | None = None
right: TreeNode | None = None
def make_tree() -> TreeNode:
"""
>>> make_tree().val
3
"""
return TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
def binary_tree_right_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the right side view of binary tree.
3 <- 3
/ \
9 20 <- 20
/ \
15 7 <- 7
>>> binary_tree_right_side_view(make_tree())
[3, 20, 7]
>>> binary_tree_right_side_view(None)
[]
"""
def depth_first_search(
root: TreeNode | None, depth: int, right_view: list[int]
) -> None:
"""
A depth first search preorder traversal to append the values at
right side of tree.
"""
if not root:
return
if depth == len(right_view):
right_view.append(root.val)
depth_first_search(root.right, depth + 1, right_view)
depth_first_search(root.left, depth + 1, right_view)
right_view: list = []
if not root:
return right_view
depth_first_search(root, 0, right_view)
return right_view
def binary_tree_left_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the left side view of binary tree.
3 -> 3
/ \
9 -> 9 20
/ \
15 -> 15 7
>>> binary_tree_left_side_view(make_tree())
[3, 9, 15]
>>> binary_tree_left_side_view(None)
[]
"""
def depth_first_search(
root: TreeNode | None, depth: int, left_view: list[int]
) -> None:
"""
A depth first search preorder traversal to append the values
at left side of tree.
"""
if not root:
return
if depth == len(left_view):
left_view.append(root.val)
depth_first_search(root.left, depth + 1, left_view)
depth_first_search(root.right, depth + 1, left_view)
left_view: list = []
if not root:
return left_view
depth_first_search(root, 0, left_view)
return left_view
def binary_tree_top_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the top side view of binary tree.
9 3 20 7
⬇ ⬇ ⬇ ⬇
3
/ \
9 20
/ \
15 7
>>> binary_tree_top_side_view(make_tree())
[9, 3, 20, 7]
>>> binary_tree_top_side_view(None)
[]
"""
def breadth_first_search(root: TreeNode, top_view: list[int]) -> None:
"""
A breadth first search traversal with defaultdict ds to append
the values of tree from top view
"""
queue = [(root, 0)]
lookup = defaultdict(list)
while queue:
first = queue.pop(0)
node, hd = first
lookup[hd].append(node.val)
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
for pair in sorted(lookup.items(), key=lambda each: each[0]):
top_view.append(pair[1][0])
top_view: list = []
if not root:
return top_view
breadth_first_search(root, top_view)
return top_view
def binary_tree_bottom_side_view(root: TreeNode) -> list[int]:
r"""
Function returns the bottom side view of binary tree
3
/ \
9 20
/ \
15 7
↑ ↑ ↑ ↑
9 15 20 7
>>> binary_tree_bottom_side_view(make_tree())
[9, 15, 20, 7]
>>> binary_tree_bottom_side_view(None)
[]
"""
from collections import defaultdict
def breadth_first_search(root: TreeNode, bottom_view: list[int]) -> None:
"""
A breadth first search traversal with defaultdict ds to append
the values of tree from bottom view
"""
queue = [(root, 0)]
lookup = defaultdict(list)
while queue:
first = queue.pop(0)
node, hd = first
lookup[hd].append(node.val)
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
for pair in sorted(lookup.items(), key=lambda each: each[0]):
bottom_view.append(pair[1][-1])
bottom_view: list = []
if not root:
return bottom_view
breadth_first_search(root, bottom_view)
return bottom_view
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import math
"""
Finding the intensity of light transmitted through a polariser using Malus Law
and by taking initial intensity and angle between polariser and axis as input
Description : Malus's law, which is named after Étienne-Louis Malus,
says that when a perfect polarizer is placed in a polarized
beam of light, the irradiance, I, of the light that passes
through is given by
I=I'cos²θ
where I' is the initial intensity and θ is the angle between the light's
initial polarization direction and the axis of the polarizer.
A beam of unpolarized light can be thought of as containing a
uniform mixture of linear polarizations at all possible angles.
Since the average value of cos²θ is 1/2, the transmission coefficient becomes
I/I' = 1/2
In practice, some light is lost in the polarizer and the actual transmission
will be somewhat lower than this, around 38% for Polaroid-type polarizers but
considerably higher (>49.9%) for some birefringent prism types.
If two polarizers are placed one after another (the second polarizer is
generally called an analyzer), the mutual angle between their polarizing axes
gives the value of θ in Malus's law. If the two axes are orthogonal, the
polarizers are crossed and in theory no light is transmitted, though again
practically speaking no polarizer is perfect and the transmission is not exactly
zero (for example, crossed Polaroid sheets appear slightly blue in colour because
their extinction ratio is better in the red). If a transparent object is placed
between the crossed polarizers, any polarization effects present in the sample
(such as birefringence) will be shown as an increase in transmission.
This effect is used in polarimetry to measure the optical activity of a sample.
Real polarizers are also not perfect blockers of the polarization orthogonal to
their polarization axis; the ratio of the transmission of the unwanted component
to the wanted component is called the extinction ratio, and varies from around
1:500 for Polaroid to about 1:106 for Glan–Taylor prism polarizers.
Reference : "https://en.wikipedia.org/wiki/Polarizer#Malus's_law_and_other_properties"
"""
def malus_law(initial_intensity: float, angle: float) -> float:
"""
>>> round(malus_law(10,45),2)
5.0
>>> round(malus_law(100,60),2)
25.0
>>> round(malus_law(50,150),2)
37.5
>>> round(malus_law(75,270),2)
0.0
>>> round(malus_law(10,-900),2)
Traceback (most recent call last):
...
ValueError: In Malus Law, the angle is in the range 0-360 degrees
>>> round(malus_law(10,900),2)
Traceback (most recent call last):
...
ValueError: In Malus Law, the angle is in the range 0-360 degrees
>>> round(malus_law(-100,900),2)
Traceback (most recent call last):
...
ValueError: The value of intensity cannot be negative
>>> round(malus_law(100,180),2)
100.0
>>> round(malus_law(100,360),2)
100.0
"""
if initial_intensity < 0:
raise ValueError("The value of intensity cannot be negative")
# handling of negative values of initial intensity
if angle < 0 or angle > 360:
raise ValueError("In Malus Law, the angle is in the range 0-360 degrees")
# handling of values out of allowed range
return initial_intensity * (math.cos(math.radians(angle)) ** 2)
if __name__ == "__main__":
import doctest
doctest.testmod(name="malus_law")
| import math
"""
Finding the intensity of light transmitted through a polariser using Malus Law
and by taking initial intensity and angle between polariser and axis as input
Description : Malus's law, which is named after Étienne-Louis Malus,
says that when a perfect polarizer is placed in a polarized
beam of light, the irradiance, I, of the light that passes
through is given by
I=I'cos²θ
where I' is the initial intensity and θ is the angle between the light's
initial polarization direction and the axis of the polarizer.
A beam of unpolarized light can be thought of as containing a
uniform mixture of linear polarizations at all possible angles.
Since the average value of cos²θ is 1/2, the transmission coefficient becomes
I/I' = 1/2
In practice, some light is lost in the polarizer and the actual transmission
will be somewhat lower than this, around 38% for Polaroid-type polarizers but
considerably higher (>49.9%) for some birefringent prism types.
If two polarizers are placed one after another (the second polarizer is
generally called an analyzer), the mutual angle between their polarizing axes
gives the value of θ in Malus's law. If the two axes are orthogonal, the
polarizers are crossed and in theory no light is transmitted, though again
practically speaking no polarizer is perfect and the transmission is not exactly
zero (for example, crossed Polaroid sheets appear slightly blue in colour because
their extinction ratio is better in the red). If a transparent object is placed
between the crossed polarizers, any polarization effects present in the sample
(such as birefringence) will be shown as an increase in transmission.
This effect is used in polarimetry to measure the optical activity of a sample.
Real polarizers are also not perfect blockers of the polarization orthogonal to
their polarization axis; the ratio of the transmission of the unwanted component
to the wanted component is called the extinction ratio, and varies from around
1:500 for Polaroid to about 1:106 for Glan–Taylor prism polarizers.
Reference : "https://en.wikipedia.org/wiki/Polarizer#Malus's_law_and_other_properties"
"""
def malus_law(initial_intensity: float, angle: float) -> float:
"""
>>> round(malus_law(10,45),2)
5.0
>>> round(malus_law(100,60),2)
25.0
>>> round(malus_law(50,150),2)
37.5
>>> round(malus_law(75,270),2)
0.0
>>> round(malus_law(10,-900),2)
Traceback (most recent call last):
...
ValueError: In Malus Law, the angle is in the range 0-360 degrees
>>> round(malus_law(10,900),2)
Traceback (most recent call last):
...
ValueError: In Malus Law, the angle is in the range 0-360 degrees
>>> round(malus_law(-100,900),2)
Traceback (most recent call last):
...
ValueError: The value of intensity cannot be negative
>>> round(malus_law(100,180),2)
100.0
>>> round(malus_law(100,360),2)
100.0
"""
if initial_intensity < 0:
raise ValueError("The value of intensity cannot be negative")
# handling of negative values of initial intensity
if angle < 0 or angle > 360:
raise ValueError("In Malus Law, the angle is in the range 0-360 degrees")
# handling of values out of allowed range
return initial_intensity * (math.cos(math.radians(angle)) ** 2)
if __name__ == "__main__":
import doctest
doctest.testmod(name="malus_law")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Hash map with open addressing.
https://en.wikipedia.org/wiki/Hash_table
Another hash map implementation, with a good explanation.
Modern Dictionaries by Raymond Hettinger
https://www.youtube.com/watch?v=p33CVV29OG8
"""
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
KEY = TypeVar("KEY")
VAL = TypeVar("VAL")
@dataclass(frozen=True, slots=True)
class _Item(Generic[KEY, VAL]):
key: KEY
val: VAL
class _DeletedItem(_Item):
def __init__(self) -> None:
super().__init__(None, None)
def __bool__(self) -> bool:
return False
_deleted = _DeletedItem()
class HashMap(MutableMapping[KEY, VAL]):
"""
Hash map with open addressing.
"""
def __init__(
self, initial_block_size: int = 8, capacity_factor: float = 0.75
) -> None:
self._initial_block_size = initial_block_size
self._buckets: list[_Item | None] = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
self._capacity_factor = capacity_factor
self._len = 0
def _get_bucket_index(self, key: KEY) -> int:
return hash(key) % len(self._buckets)
def _get_next_ind(self, ind: int) -> int:
"""
Get next index.
Implements linear open addressing.
"""
return (ind + 1) % len(self._buckets)
def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:
"""
Try to add value to the bucket.
If bucket is empty or key is the same, does insert and return True.
If bucket has another key or deleted placeholder,
that means that we need to check next bucket.
"""
stored = self._buckets[ind]
if not stored:
self._buckets[ind] = _Item(key, val)
self._len += 1
return True
elif stored.key == key:
self._buckets[ind] = _Item(key, val)
return True
else:
return False
def _is_full(self) -> bool:
"""
Return true if we have reached safe capacity.
So we need to increase the number of buckets to avoid collisions.
"""
limit = len(self._buckets) * self._capacity_factor
return len(self) >= int(limit)
def _is_sparse(self) -> bool:
"""Return true if we need twice fewer buckets when we have now."""
if len(self._buckets) <= self._initial_block_size:
return False
limit = len(self._buckets) * self._capacity_factor / 2
return len(self) < limit
def _resize(self, new_size: int) -> None:
old_buckets = self._buckets
self._buckets = [None] * new_size
self._len = 0
for item in old_buckets:
if item:
self._add_item(item.key, item.val)
def _size_up(self) -> None:
self._resize(len(self._buckets) * 2)
def _size_down(self) -> None:
self._resize(len(self._buckets) // 2)
def _iterate_buckets(self, key: KEY) -> Iterator[int]:
ind = self._get_bucket_index(key)
for _ in range(len(self._buckets)):
yield ind
ind = self._get_next_ind(ind)
def _add_item(self, key: KEY, val: VAL) -> None:
for ind in self._iterate_buckets(key):
if self._try_set(ind, key, val):
break
def __setitem__(self, key: KEY, val: VAL) -> None:
if self._is_full():
self._size_up()
self._add_item(key, val)
def __delitem__(self, key: KEY) -> None:
for ind in self._iterate_buckets(key):
item = self._buckets[ind]
if item is None:
raise KeyError(key)
if item is _deleted:
continue
if item.key == key:
self._buckets[ind] = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__(self, key: KEY) -> VAL:
for ind in self._iterate_buckets(key):
item = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(key)
def __len__(self) -> int:
return self._len
def __iter__(self) -> Iterator[KEY]:
yield from (item.key for item in self._buckets if item)
def __repr__(self) -> str:
val_string = " ,".join(
f"{item.key}: {item.val}" for item in self._buckets if item
)
return f"HashMap({val_string})"
| """
Hash map with open addressing.
https://en.wikipedia.org/wiki/Hash_table
Another hash map implementation, with a good explanation.
Modern Dictionaries by Raymond Hettinger
https://www.youtube.com/watch?v=p33CVV29OG8
"""
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
KEY = TypeVar("KEY")
VAL = TypeVar("VAL")
@dataclass(frozen=True, slots=True)
class _Item(Generic[KEY, VAL]):
key: KEY
val: VAL
class _DeletedItem(_Item):
def __init__(self) -> None:
super().__init__(None, None)
def __bool__(self) -> bool:
return False
_deleted = _DeletedItem()
class HashMap(MutableMapping[KEY, VAL]):
"""
Hash map with open addressing.
"""
def __init__(
self, initial_block_size: int = 8, capacity_factor: float = 0.75
) -> None:
self._initial_block_size = initial_block_size
self._buckets: list[_Item | None] = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
self._capacity_factor = capacity_factor
self._len = 0
def _get_bucket_index(self, key: KEY) -> int:
return hash(key) % len(self._buckets)
def _get_next_ind(self, ind: int) -> int:
"""
Get next index.
Implements linear open addressing.
"""
return (ind + 1) % len(self._buckets)
def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:
"""
Try to add value to the bucket.
If bucket is empty or key is the same, does insert and return True.
If bucket has another key or deleted placeholder,
that means that we need to check next bucket.
"""
stored = self._buckets[ind]
if not stored:
self._buckets[ind] = _Item(key, val)
self._len += 1
return True
elif stored.key == key:
self._buckets[ind] = _Item(key, val)
return True
else:
return False
def _is_full(self) -> bool:
"""
Return true if we have reached safe capacity.
So we need to increase the number of buckets to avoid collisions.
"""
limit = len(self._buckets) * self._capacity_factor
return len(self) >= int(limit)
def _is_sparse(self) -> bool:
"""Return true if we need twice fewer buckets when we have now."""
if len(self._buckets) <= self._initial_block_size:
return False
limit = len(self._buckets) * self._capacity_factor / 2
return len(self) < limit
def _resize(self, new_size: int) -> None:
old_buckets = self._buckets
self._buckets = [None] * new_size
self._len = 0
for item in old_buckets:
if item:
self._add_item(item.key, item.val)
def _size_up(self) -> None:
self._resize(len(self._buckets) * 2)
def _size_down(self) -> None:
self._resize(len(self._buckets) // 2)
def _iterate_buckets(self, key: KEY) -> Iterator[int]:
ind = self._get_bucket_index(key)
for _ in range(len(self._buckets)):
yield ind
ind = self._get_next_ind(ind)
def _add_item(self, key: KEY, val: VAL) -> None:
for ind in self._iterate_buckets(key):
if self._try_set(ind, key, val):
break
def __setitem__(self, key: KEY, val: VAL) -> None:
if self._is_full():
self._size_up()
self._add_item(key, val)
def __delitem__(self, key: KEY) -> None:
for ind in self._iterate_buckets(key):
item = self._buckets[ind]
if item is None:
raise KeyError(key)
if item is _deleted:
continue
if item.key == key:
self._buckets[ind] = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__(self, key: KEY) -> VAL:
for ind in self._iterate_buckets(key):
item = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(key)
def __len__(self) -> int:
return self._len
def __iter__(self) -> Iterator[KEY]:
yield from (item.key for item in self._buckets if item)
def __repr__(self) -> str:
val_string = " ,".join(
f"{item.key}: {item.val}" for item in self._buckets if item
)
return f"HashMap({val_string})"
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
"""
def solution(n: int = 20) -> int:
"""
Returns the smallest positive number that is evenly divisible (divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(22)
232792560
>>> solution(3.4)
6
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
i += n * (n - 1)
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
return None
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
"""
def solution(n: int = 20) -> int:
"""
Returns the smallest positive number that is evenly divisible (divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(22)
232792560
>>> solution(3.4)
6
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
i += n * (n - 1)
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
return None
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
This is an implementation of odd-even transposition sort.
It works by performing a series of parallel swaps between odd and even pairs of
variables in the list.
This implementation represents each variable in the list with a process and
each process communicates with its neighboring processes in the list to perform
comparisons.
They are synchronized with locks and message passing but other forms of
synchronization could be used.
"""
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
process_lock = Lock()
"""
The function run by the processes that sorts the list
position = the position in the list the process represents, used to know which
neighbor we pass our value to
value = the initial value at list[position]
LSend, RSend = the pipes we use to send to our left and right neighbors
LRcv, RRcv = the pipes we use to receive from our left and right neighbors
resultPipe = the pipe used to send results back to main
"""
def oe_process(position, value, l_send, r_send, lr_cv, rr_cv, result_pipe):
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(value)
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
temp = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
value = min(value, temp)
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(value)
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
temp = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
value = max(value, temp)
# after all swaps are performed, send the values back to main
result_pipe[1].send(value)
"""
the function which creates the processes that perform the parallel swaps
arr = the list to be sorted
"""
def odd_even_transposition(arr):
process_array_ = []
result_pipe = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe())
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
temp_rs = Pipe()
temp_rr = Pipe()
process_array_.append(
Process(
target=oe_process,
args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
for i in range(1, len(arr) - 1):
temp_rs = Pipe()
temp_rr = Pipe()
process_array_.append(
Process(
target=oe_process,
args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
process_array_.append(
Process(
target=oe_process,
args=(
len(arr) - 1,
arr[len(arr) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(arr) - 1],
),
)
)
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0, len(result_pipe)):
arr[p] = result_pipe[p][0].recv()
process_array_[p].join()
return arr
# creates a reverse sorted list and sorts it
def main():
arr = list(range(10, 0, -1))
print("Initial List")
print(*arr)
arr = odd_even_transposition(arr)
print("Sorted List\n")
print(*arr)
if __name__ == "__main__":
main()
| """
This is an implementation of odd-even transposition sort.
It works by performing a series of parallel swaps between odd and even pairs of
variables in the list.
This implementation represents each variable in the list with a process and
each process communicates with its neighboring processes in the list to perform
comparisons.
They are synchronized with locks and message passing but other forms of
synchronization could be used.
"""
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
process_lock = Lock()
"""
The function run by the processes that sorts the list
position = the position in the list the process represents, used to know which
neighbor we pass our value to
value = the initial value at list[position]
LSend, RSend = the pipes we use to send to our left and right neighbors
LRcv, RRcv = the pipes we use to receive from our left and right neighbors
resultPipe = the pipe used to send results back to main
"""
def oe_process(position, value, l_send, r_send, lr_cv, rr_cv, result_pipe):
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(value)
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
temp = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
value = min(value, temp)
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(value)
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
temp = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
value = max(value, temp)
# after all swaps are performed, send the values back to main
result_pipe[1].send(value)
"""
the function which creates the processes that perform the parallel swaps
arr = the list to be sorted
"""
def odd_even_transposition(arr):
process_array_ = []
result_pipe = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe())
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
temp_rs = Pipe()
temp_rr = Pipe()
process_array_.append(
Process(
target=oe_process,
args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
for i in range(1, len(arr) - 1):
temp_rs = Pipe()
temp_rr = Pipe()
process_array_.append(
Process(
target=oe_process,
args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
process_array_.append(
Process(
target=oe_process,
args=(
len(arr) - 1,
arr[len(arr) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(arr) - 1],
),
)
)
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0, len(result_pipe)):
arr[p] = result_pipe[p][0].recv()
process_array_[p].join()
return arr
# creates a reverse sorted list and sorts it
def main():
arr = list(range(10, 0, -1))
print("Initial List")
print(*arr)
arr = odd_even_transposition(arr)
print("Sorted List\n")
print(*arr)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 64: https://projecteuler.net/problem=64
All square roots are periodic when written as continued fractions.
For example, let us consider sqrt(23).
It can be seen that the sequence is repeating.
For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)],
to indicate that the block (1,3,1,8) repeats indefinitely.
Exactly four continued fractions, for N<=13, have an odd period.
How many continued fractions for N<=10000 have an odd period?
References:
- https://en.wikipedia.org/wiki/Continued_fraction
"""
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
"""
Returns the continued fraction period of a number n.
>>> continuous_fraction_period(2)
1
>>> continuous_fraction_period(5)
1
>>> continuous_fraction_period(7)
4
>>> continuous_fraction_period(11)
2
>>> continuous_fraction_period(13)
5
"""
numerator = 0.0
denominator = 1.0
root = int(sqrt(n))
integer_part = root
period = 0
while integer_part != 2 * root:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((root + numerator) / denominator)
period += 1
return period
def solution(n: int = 10000) -> int:
"""
Returns the count of numbers <= 10000 with odd periods.
This function calls continuous_fraction_period for numbers which are
not perfect squares.
This is checked in if sr - floor(sr) != 0 statement.
If an odd period is returned by continuous_fraction_period,
count_odd_periods is increased by 1.
>>> solution(2)
1
>>> solution(5)
2
>>> solution(7)
2
>>> solution(11)
3
>>> solution(13)
4
"""
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1:
count_odd_periods += 1
return count_odd_periods
if __name__ == "__main__":
print(f"{solution(int(input().strip()))}")
| """
Project Euler Problem 64: https://projecteuler.net/problem=64
All square roots are periodic when written as continued fractions.
For example, let us consider sqrt(23).
It can be seen that the sequence is repeating.
For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)],
to indicate that the block (1,3,1,8) repeats indefinitely.
Exactly four continued fractions, for N<=13, have an odd period.
How many continued fractions for N<=10000 have an odd period?
References:
- https://en.wikipedia.org/wiki/Continued_fraction
"""
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
"""
Returns the continued fraction period of a number n.
>>> continuous_fraction_period(2)
1
>>> continuous_fraction_period(5)
1
>>> continuous_fraction_period(7)
4
>>> continuous_fraction_period(11)
2
>>> continuous_fraction_period(13)
5
"""
numerator = 0.0
denominator = 1.0
root = int(sqrt(n))
integer_part = root
period = 0
while integer_part != 2 * root:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((root + numerator) / denominator)
period += 1
return period
def solution(n: int = 10000) -> int:
"""
Returns the count of numbers <= 10000 with odd periods.
This function calls continuous_fraction_period for numbers which are
not perfect squares.
This is checked in if sr - floor(sr) != 0 statement.
If an odd period is returned by continuous_fraction_period,
count_odd_periods is increased by 1.
>>> solution(2)
1
>>> solution(5)
2
>>> solution(7)
2
>>> solution(11)
3
>>> solution(13)
4
"""
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1:
count_odd_periods += 1
return count_odd_periods
if __name__ == "__main__":
print(f"{solution(int(input().strip()))}")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| #
| #
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
https://en.wikipedia.org/wiki/Combination
"""
from math import factorial
def combinations(n: int, k: int) -> int:
"""
Returns the number of different combinations of k length which can
be made from n values, where n >= k.
Examples:
>>> combinations(10,5)
252
>>> combinations(6,3)
20
>>> combinations(20,5)
15504
>>> combinations(52, 5)
2598960
>>> combinations(0, 0)
1
>>> combinations(-4, -5)
...
Traceback (most recent call last):
ValueError: Please enter positive integers for n and k where n >= k
"""
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(n) // (factorial(k) * factorial(n - k))
if __name__ == "__main__":
print(
"The number of five-card hands possible from a standard",
f"fifty-two card deck is: {combinations(52, 5)}\n",
)
print(
"If a class of 40 students must be arranged into groups of",
f"4 for group projects, there are {combinations(40, 4)} ways",
"to arrange them.\n",
)
print(
"If 10 teams are competing in a Formula One race, there",
f"are {combinations(10, 3)} ways that first, second and",
"third place can be awarded.",
)
| """
https://en.wikipedia.org/wiki/Combination
"""
from math import factorial
def combinations(n: int, k: int) -> int:
"""
Returns the number of different combinations of k length which can
be made from n values, where n >= k.
Examples:
>>> combinations(10,5)
252
>>> combinations(6,3)
20
>>> combinations(20,5)
15504
>>> combinations(52, 5)
2598960
>>> combinations(0, 0)
1
>>> combinations(-4, -5)
...
Traceback (most recent call last):
ValueError: Please enter positive integers for n and k where n >= k
"""
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(n) // (factorial(k) * factorial(n - k))
if __name__ == "__main__":
print(
"The number of five-card hands possible from a standard",
f"fifty-two card deck is: {combinations(52, 5)}\n",
)
print(
"If a class of 40 students must be arranged into groups of",
f"4 for group projects, there are {combinations(40, 4)} ways",
"to arrange them.\n",
)
print(
"If 10 teams are competing in a Formula One race, there",
f"are {combinations(10, 3)} ways that first, second and",
"third place can be awarded.",
)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
def longest_distance(graph):
indegree = [0] * len(graph)
queue = []
long_dist = [1] * len(graph)
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(indegree)):
if indegree[i] == 0:
queue.append(i)
while queue:
vertex = queue.pop(0)
for x in graph[vertex]:
indegree[x] -= 1
if long_dist[vertex] + 1 > long_dist[x]:
long_dist[x] = long_dist[vertex] + 1
if indegree[x] == 0:
queue.append(x)
print(max(long_dist))
# Adjacency list of Graph
graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
longest_distance(graph)
| # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
def longest_distance(graph):
indegree = [0] * len(graph)
queue = []
long_dist = [1] * len(graph)
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(indegree)):
if indegree[i] == 0:
queue.append(i)
while queue:
vertex = queue.pop(0)
for x in graph[vertex]:
indegree[x] -= 1
if long_dist[vertex] + 1 > long_dist[x]:
long_dist[x] = long_dist[vertex] + 1
if indegree[x] == 0:
queue.append(x)
print(max(long_dist))
# Adjacency list of Graph
graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
longest_distance(graph)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Author: Mohit Radadiya
"""
from string import ascii_uppercase
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
dict2 = dict(enumerate(ascii_uppercase))
# This function generates the key in
# a cyclic manner until it's length isn't
# equal to the length of original text
def generate_key(message: str, key: str) -> str:
"""
>>> generate_key("THE GERMAN ATTACK","SECRET")
'SECRETSECRETSECRE'
"""
x = len(message)
i = 0
while True:
if x == i:
i = 0
if len(key) == len(message):
break
key += key[i]
i += 1
return key
# This function returns the encrypted text
# generated with the help of the key
def cipher_text(message: str, key_new: str) -> str:
"""
>>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE")
'BDC PAYUWL JPAIYI'
"""
cipher_text = ""
i = 0
for letter in message:
if letter == " ":
cipher_text += " "
else:
x = (dict1[letter] - dict1[key_new[i]]) % 26
i += 1
cipher_text += dict2[x]
return cipher_text
# This function decrypts the encrypted text
# and returns the original text
def original_text(cipher_text: str, key_new: str) -> str:
"""
>>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE")
'THE GERMAN ATTACK'
"""
or_txt = ""
i = 0
for letter in cipher_text:
if letter == " ":
or_txt += " "
else:
x = (dict1[letter] + dict1[key_new[i]] + 26) % 26
i += 1
or_txt += dict2[x]
return or_txt
def main() -> None:
message = "THE GERMAN ATTACK"
key = "SECRET"
key_new = generate_key(message, key)
s = cipher_text(message, key_new)
print(f"Encrypted Text = {s}")
print(f"Original Text = {original_text(s, key_new)}")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| """
Author: Mohit Radadiya
"""
from string import ascii_uppercase
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
dict2 = dict(enumerate(ascii_uppercase))
# This function generates the key in
# a cyclic manner until it's length isn't
# equal to the length of original text
def generate_key(message: str, key: str) -> str:
"""
>>> generate_key("THE GERMAN ATTACK","SECRET")
'SECRETSECRETSECRE'
"""
x = len(message)
i = 0
while True:
if x == i:
i = 0
if len(key) == len(message):
break
key += key[i]
i += 1
return key
# This function returns the encrypted text
# generated with the help of the key
def cipher_text(message: str, key_new: str) -> str:
"""
>>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE")
'BDC PAYUWL JPAIYI'
"""
cipher_text = ""
i = 0
for letter in message:
if letter == " ":
cipher_text += " "
else:
x = (dict1[letter] - dict1[key_new[i]]) % 26
i += 1
cipher_text += dict2[x]
return cipher_text
# This function decrypts the encrypted text
# and returns the original text
def original_text(cipher_text: str, key_new: str) -> str:
"""
>>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE")
'THE GERMAN ATTACK'
"""
or_txt = ""
i = 0
for letter in cipher_text:
if letter == " ":
or_txt += " "
else:
x = (dict1[letter] + dict1[key_new[i]] + 26) % 26
i += 1
or_txt += dict2[x]
return or_txt
def main() -> None:
message = "THE GERMAN ATTACK"
key = "SECRET"
key_new = generate_key(message, key)
s = cipher_text(message, key_new)
print(f"Encrypted Text = {s}")
print(f"Original Text = {original_text(s, key_new)}")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Picks the random index as the pivot
"""
import random
def partition(a, left_index, right_index):
pivot = a[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if a[j] < pivot:
a[j], a[i] = a[i], a[j]
i += 1
a[left_index], a[i - 1] = a[i - 1], a[left_index]
return i - 1
def quick_sort_random(a, left, right):
if left < right:
pivot = random.randint(left, right - 1)
a[pivot], a[left] = (
a[left],
a[pivot],
) # switches the pivot with the left most bound
pivot_index = partition(a, left, right)
quick_sort_random(
a, left, pivot_index
) # recursive quicksort to the left of the pivot point
quick_sort_random(
a, pivot_index + 1, right
) # recursive quicksort to the right of the pivot point
def main():
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
quick_sort_random(arr, 0, len(arr))
print(arr)
if __name__ == "__main__":
main()
| """
Picks the random index as the pivot
"""
import random
def partition(a, left_index, right_index):
pivot = a[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if a[j] < pivot:
a[j], a[i] = a[i], a[j]
i += 1
a[left_index], a[i - 1] = a[i - 1], a[left_index]
return i - 1
def quick_sort_random(a, left, right):
if left < right:
pivot = random.randint(left, right - 1)
a[pivot], a[left] = (
a[left],
a[pivot],
) # switches the pivot with the left most bound
pivot_index = partition(a, left, right)
quick_sort_random(
a, left, pivot_index
) # recursive quicksort to the left of the pivot point
quick_sort_random(
a, pivot_index + 1, right
) # recursive quicksort to the right of the pivot point
def main():
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
quick_sort_random(arr, 0, len(arr))
print(arr)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Forward propagation explanation:
https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250
"""
import math
import random
# Sigmoid
def sigmoid_function(value: float, deriv: bool = False) -> float:
"""Return the sigmoid function of a float.
>>> sigmoid_function(3.5)
0.9706877692486436
>>> sigmoid_function(3.5, True)
-8.75
"""
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value))
# Initial Value
INITIAL_VALUE = 0.02
def forward_propagation(expected: int, number_propagations: int) -> float:
"""Return the value found after the forward propagation training.
>>> res = forward_propagation(32, 10000000)
>>> res > 31 and res < 33
True
>>> res = forward_propagation(32, 1000)
>>> res > 31 and res < 33
False
"""
# Random weight
weight = float(2 * (random.randint(1, 100)) - 1)
for _ in range(number_propagations):
# Forward propagation
layer_1 = sigmoid_function(INITIAL_VALUE * weight)
# How much did we miss?
layer_1_error = (expected / 100) - layer_1
# Error delta
layer_1_delta = layer_1_error * sigmoid_function(layer_1, True)
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_1 * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
expected = int(input("Expected value: "))
number_propagations = int(input("Number of propagations: "))
print(forward_propagation(expected, number_propagations))
| """
Forward propagation explanation:
https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250
"""
import math
import random
# Sigmoid
def sigmoid_function(value: float, deriv: bool = False) -> float:
"""Return the sigmoid function of a float.
>>> sigmoid_function(3.5)
0.9706877692486436
>>> sigmoid_function(3.5, True)
-8.75
"""
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value))
# Initial Value
INITIAL_VALUE = 0.02
def forward_propagation(expected: int, number_propagations: int) -> float:
"""Return the value found after the forward propagation training.
>>> res = forward_propagation(32, 10000000)
>>> res > 31 and res < 33
True
>>> res = forward_propagation(32, 1000)
>>> res > 31 and res < 33
False
"""
# Random weight
weight = float(2 * (random.randint(1, 100)) - 1)
for _ in range(number_propagations):
# Forward propagation
layer_1 = sigmoid_function(INITIAL_VALUE * weight)
# How much did we miss?
layer_1_error = (expected / 100) - layer_1
# Error delta
layer_1_delta = layer_1_error * sigmoid_function(layer_1, True)
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_1 * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
expected = int(input("Expected value: "))
number_propagations = int(input("Number of propagations: "))
print(forward_propagation(expected, number_propagations))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Test cases:
Do you want to enter your denominations ? (Y/N) :N
Enter the change you want to make in Indian Currency: 987
Following is minimal change for 987 :
500 100 100 100 100 50 20 10 5 2
Do you want to enter your denominations ? (Y/N) :Y
Enter number of denomination:10
1
5
10
20
50
100
200
500
1000
2000
Enter the change you want to make: 18745
Following is minimal change for 18745 :
2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5
Do you want to enter your denominations ? (Y/N) :N
Enter the change you want to make: 0
The total value cannot be zero or negative.
Do you want to enter your denominations ? (Y/N) :N
Enter the change you want to make: -98
The total value cannot be zero or negative.
Do you want to enter your denominations ? (Y/N) :Y
Enter number of denomination:5
1
5
100
500
1000
Enter the change you want to make: 456
Following is minimal change for 456 :
100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1
"""
def find_minimum_change(denominations: list[int], value: str) -> list[int]:
"""
Find the minimum change from the given denominations and value
>>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745)
[2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5]
>>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987)
[500, 100, 100, 100, 100, 50, 20, 10, 5, 2]
>>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0)
[]
>>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98)
[]
>>> find_minimum_change([1, 5, 100, 500, 1000], 456)
[100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1]
"""
total_value = int(value)
# Initialize Result
answer = []
# Traverse through all denomination
for denomination in reversed(denominations):
# Find denominations
while int(total_value) >= int(denomination):
total_value -= int(denomination)
answer.append(denomination) # Append the "answers" array
return answer
# Driver Code
if __name__ == "__main__":
denominations = []
value = "0"
if (
input("Do you want to enter your denominations ? (yY/n): ").strip().lower()
== "y"
):
n = int(input("Enter the number of denominations you want to add: ").strip())
for i in range(0, n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
# All denominations of Indian Currency if user does not enter
denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000]
value = input("Enter the change you want to make: ").strip()
if int(value) == 0 or int(value) < 0:
print("The total value cannot be zero or negative.")
else:
print(f"Following is minimal change for {value}: ")
answer = find_minimum_change(denominations, value)
# Print result
for i in range(len(answer)):
print(answer[i], end=" ")
| """
Test cases:
Do you want to enter your denominations ? (Y/N) :N
Enter the change you want to make in Indian Currency: 987
Following is minimal change for 987 :
500 100 100 100 100 50 20 10 5 2
Do you want to enter your denominations ? (Y/N) :Y
Enter number of denomination:10
1
5
10
20
50
100
200
500
1000
2000
Enter the change you want to make: 18745
Following is minimal change for 18745 :
2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5
Do you want to enter your denominations ? (Y/N) :N
Enter the change you want to make: 0
The total value cannot be zero or negative.
Do you want to enter your denominations ? (Y/N) :N
Enter the change you want to make: -98
The total value cannot be zero or negative.
Do you want to enter your denominations ? (Y/N) :Y
Enter number of denomination:5
1
5
100
500
1000
Enter the change you want to make: 456
Following is minimal change for 456 :
100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1
"""
def find_minimum_change(denominations: list[int], value: str) -> list[int]:
"""
Find the minimum change from the given denominations and value
>>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745)
[2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5]
>>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987)
[500, 100, 100, 100, 100, 50, 20, 10, 5, 2]
>>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0)
[]
>>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98)
[]
>>> find_minimum_change([1, 5, 100, 500, 1000], 456)
[100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1]
"""
total_value = int(value)
# Initialize Result
answer = []
# Traverse through all denomination
for denomination in reversed(denominations):
# Find denominations
while int(total_value) >= int(denomination):
total_value -= int(denomination)
answer.append(denomination) # Append the "answers" array
return answer
# Driver Code
if __name__ == "__main__":
denominations = []
value = "0"
if (
input("Do you want to enter your denominations ? (yY/n): ").strip().lower()
== "y"
):
n = int(input("Enter the number of denominations you want to add: ").strip())
for i in range(0, n):
denominations.append(int(input(f"Denomination {i}: ").strip()))
value = input("Enter the change you want to make in Indian Currency: ").strip()
else:
# All denominations of Indian Currency if user does not enter
denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000]
value = input("Enter the change you want to make: ").strip()
if int(value) == 0 or int(value) < 0:
print("The total value cannot be zero or negative.")
else:
print(f"Following is minimal change for {value}: ")
answer = find_minimum_change(denominations, value)
# Print result
for i in range(len(answer)):
print(answer[i], end=" ")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str:
"""
Implement a popular pi-digit-extraction algorithm known as the
Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi.
Wikipedia page:
https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
@param digit_position: a positive integer representing the position of the digit to
extract.
The digit immediately after the decimal point is located at position 1.
@param precision: number of terms in the second summation to calculate.
A higher number reduces the chance of an error but increases the runtime.
@return: a hexadecimal digit representing the digit at the nth position
in pi's decimal expansion.
>>> "".join(bailey_borwein_plouffe(i) for i in range(1, 11))
'243f6a8885'
>>> bailey_borwein_plouffe(5, 10000)
'6'
>>> bailey_borwein_plouffe(-10)
Traceback (most recent call last):
...
ValueError: Digit position must be a positive integer
>>> bailey_borwein_plouffe(0)
Traceback (most recent call last):
...
ValueError: Digit position must be a positive integer
>>> bailey_borwein_plouffe(1.7)
Traceback (most recent call last):
...
ValueError: Digit position must be a positive integer
>>> bailey_borwein_plouffe(2, -10)
Traceback (most recent call last):
...
ValueError: Precision must be a nonnegative integer
>>> bailey_borwein_plouffe(2, 1.6)
Traceback (most recent call last):
...
ValueError: Precision must be a nonnegative integer
"""
if (not isinstance(digit_position, int)) or (digit_position <= 0):
raise ValueError("Digit position must be a positive integer")
elif (not isinstance(precision, int)) or (precision < 0):
raise ValueError("Precision must be a nonnegative integer")
# compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly
# accurate
sum_result = (
4 * _subsum(digit_position, 1, precision)
- 2 * _subsum(digit_position, 4, precision)
- _subsum(digit_position, 5, precision)
- _subsum(digit_position, 6, precision)
)
# return the first hex digit of the fractional part of the result
return hex(int((sum_result % 1) * 16))[2:]
def _subsum(
digit_pos_to_extract: int, denominator_addend: int, precision: int
) -> float:
# only care about first digit of fractional part; don't need decimal
"""
Private helper function to implement the summation
functionality.
@param digit_pos_to_extract: digit position to extract
@param denominator_addend: added to denominator of fractions in the formula
@param precision: same as precision in main function
@return: floating-point number whose integer part is not important
"""
total = 0.0
for sum_index in range(digit_pos_to_extract + precision):
denominator = 8 * sum_index + denominator_addend
if sum_index < digit_pos_to_extract:
# if the exponential term is an integer and we mod it by the denominator
# before dividing, only the integer part of the sum will change;
# the fractional part will not
exponential_term = pow(
16, digit_pos_to_extract - 1 - sum_index, denominator
)
else:
exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index)
total += exponential_term / denominator
return total
if __name__ == "__main__":
import doctest
doctest.testmod()
| def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str:
"""
Implement a popular pi-digit-extraction algorithm known as the
Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi.
Wikipedia page:
https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
@param digit_position: a positive integer representing the position of the digit to
extract.
The digit immediately after the decimal point is located at position 1.
@param precision: number of terms in the second summation to calculate.
A higher number reduces the chance of an error but increases the runtime.
@return: a hexadecimal digit representing the digit at the nth position
in pi's decimal expansion.
>>> "".join(bailey_borwein_plouffe(i) for i in range(1, 11))
'243f6a8885'
>>> bailey_borwein_plouffe(5, 10000)
'6'
>>> bailey_borwein_plouffe(-10)
Traceback (most recent call last):
...
ValueError: Digit position must be a positive integer
>>> bailey_borwein_plouffe(0)
Traceback (most recent call last):
...
ValueError: Digit position must be a positive integer
>>> bailey_borwein_plouffe(1.7)
Traceback (most recent call last):
...
ValueError: Digit position must be a positive integer
>>> bailey_borwein_plouffe(2, -10)
Traceback (most recent call last):
...
ValueError: Precision must be a nonnegative integer
>>> bailey_borwein_plouffe(2, 1.6)
Traceback (most recent call last):
...
ValueError: Precision must be a nonnegative integer
"""
if (not isinstance(digit_position, int)) or (digit_position <= 0):
raise ValueError("Digit position must be a positive integer")
elif (not isinstance(precision, int)) or (precision < 0):
raise ValueError("Precision must be a nonnegative integer")
# compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly
# accurate
sum_result = (
4 * _subsum(digit_position, 1, precision)
- 2 * _subsum(digit_position, 4, precision)
- _subsum(digit_position, 5, precision)
- _subsum(digit_position, 6, precision)
)
# return the first hex digit of the fractional part of the result
return hex(int((sum_result % 1) * 16))[2:]
def _subsum(
digit_pos_to_extract: int, denominator_addend: int, precision: int
) -> float:
# only care about first digit of fractional part; don't need decimal
"""
Private helper function to implement the summation
functionality.
@param digit_pos_to_extract: digit position to extract
@param denominator_addend: added to denominator of fractions in the formula
@param precision: same as precision in main function
@return: floating-point number whose integer part is not important
"""
total = 0.0
for sum_index in range(digit_pos_to_extract + precision):
denominator = 8 * sum_index + denominator_addend
if sum_index < digit_pos_to_extract:
# if the exponential term is an integer and we mod it by the denominator
# before dividing, only the integer part of the sum will change;
# the fractional part will not
exponential_term = pow(
16, digit_pos_to_extract - 1 - sum_index, denominator
)
else:
exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index)
total += exponential_term / denominator
return total
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # https://en.wikipedia.org/wiki/Ohm%27s_law
from __future__ import annotations
def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]:
"""
Apply Ohm's Law, on any two given electrical values, which can be voltage, current,
and resistance, and then in a Python dict return name/value pair of the zero value.
>>> ohms_law(voltage=10, resistance=5, current=0)
{'current': 2.0}
>>> ohms_law(voltage=0, current=0, resistance=10)
Traceback (most recent call last):
...
ValueError: One and only one argument must be 0
>>> ohms_law(voltage=0, current=1, resistance=-2)
Traceback (most recent call last):
...
ValueError: Resistance cannot be negative
>>> ohms_law(resistance=0, voltage=-10, current=1)
{'resistance': -10.0}
>>> ohms_law(voltage=0, current=-1.5, resistance=2)
{'voltage': -3.0}
"""
if (voltage, current, resistance).count(0) != 1:
raise ValueError("One and only one argument must be 0")
if resistance < 0:
raise ValueError("Resistance cannot be negative")
if voltage == 0:
return {"voltage": float(current * resistance)}
elif current == 0:
return {"current": voltage / resistance}
elif resistance == 0:
return {"resistance": voltage / current}
else:
raise ValueError("Exactly one argument must be 0")
if __name__ == "__main__":
import doctest
doctest.testmod()
| # https://en.wikipedia.org/wiki/Ohm%27s_law
from __future__ import annotations
def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]:
"""
Apply Ohm's Law, on any two given electrical values, which can be voltage, current,
and resistance, and then in a Python dict return name/value pair of the zero value.
>>> ohms_law(voltage=10, resistance=5, current=0)
{'current': 2.0}
>>> ohms_law(voltage=0, current=0, resistance=10)
Traceback (most recent call last):
...
ValueError: One and only one argument must be 0
>>> ohms_law(voltage=0, current=1, resistance=-2)
Traceback (most recent call last):
...
ValueError: Resistance cannot be negative
>>> ohms_law(resistance=0, voltage=-10, current=1)
{'resistance': -10.0}
>>> ohms_law(voltage=0, current=-1.5, resistance=2)
{'voltage': -3.0}
"""
if (voltage, current, resistance).count(0) != 1:
raise ValueError("One and only one argument must be 0")
if resistance < 0:
raise ValueError("Resistance cannot be negative")
if voltage == 0:
return {"voltage": float(current * resistance)}
elif current == 0:
return {"current": voltage / resistance}
elif resistance == 0:
return {"resistance": voltage / current}
else:
raise ValueError("Exactly one argument must be 0")
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import random
class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def is_in_unit_circle(self) -> bool:
"""
True, if the point lies in the unit circle
False, otherwise
"""
return (self.x**2 + self.y**2) <= 1
@classmethod
def random_unit_square(cls):
"""
Generates a point randomly drawn from the unit square [0, 1) x [0, 1).
"""
return cls(x=random.random(), y=random.random())
def estimate_pi(number_of_simulations: int) -> float:
"""
Generates an estimate of the mathematical constant PI.
See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview
The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from
the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is:
P[U in unit circle] = 1/4 PI
and therefore
PI = 4 * P[U in unit circle]
We can get an estimate of the probability P[U in unit circle].
See https://en.wikipedia.org/wiki/Empirical_probability by:
1. Draw a point uniformly from the unit square.
2. Repeat the first step n times and count the number of points in the unit
circle, which is called m.
3. An estimate of P[U in unit circle] is m/n
"""
if number_of_simulations < 1:
raise ValueError("At least one simulation is necessary to estimate PI.")
number_in_unit_circle = 0
for _ in range(number_of_simulations):
random_point = Point.random_unit_square()
if random_point.is_in_unit_circle():
number_in_unit_circle += 1
return 4 * number_in_unit_circle / number_of_simulations
if __name__ == "__main__":
# import doctest
# doctest.testmod()
from math import pi
prompt = "Please enter the desired number of Monte Carlo simulations: "
my_pi = estimate_pi(int(input(prompt).strip()))
print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
| import random
class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def is_in_unit_circle(self) -> bool:
"""
True, if the point lies in the unit circle
False, otherwise
"""
return (self.x**2 + self.y**2) <= 1
@classmethod
def random_unit_square(cls):
"""
Generates a point randomly drawn from the unit square [0, 1) x [0, 1).
"""
return cls(x=random.random(), y=random.random())
def estimate_pi(number_of_simulations: int) -> float:
"""
Generates an estimate of the mathematical constant PI.
See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview
The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from
the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is:
P[U in unit circle] = 1/4 PI
and therefore
PI = 4 * P[U in unit circle]
We can get an estimate of the probability P[U in unit circle].
See https://en.wikipedia.org/wiki/Empirical_probability by:
1. Draw a point uniformly from the unit square.
2. Repeat the first step n times and count the number of points in the unit
circle, which is called m.
3. An estimate of P[U in unit circle] is m/n
"""
if number_of_simulations < 1:
raise ValueError("At least one simulation is necessary to estimate PI.")
number_in_unit_circle = 0
for _ in range(number_of_simulations):
random_point = Point.random_unit_square()
if random_point.is_in_unit_circle():
number_in_unit_circle += 1
return 4 * number_in_unit_circle / number_of_simulations
if __name__ == "__main__":
# import doctest
# doctest.testmod()
from math import pi
prompt = "Please enter the desired number of Monte Carlo simulations: "
my_pi = estimate_pi(int(input(prompt).strip()))
print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # Created by susmith98
from collections import Counter
from timeit import timeit
# Problem Description:
# Check if characters of the given string can be rearranged to form a palindrome.
# Counter is faster for long strings and non-Counter is faster for short strings.
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome_counter("Momo")
True
>>> can_string_be_rearranged_as_palindrome_counter("Mother")
False
>>> can_string_be_rearranged_as_palindrome_counter("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome("Momo")
True
>>> can_string_be_rearranged_as_palindrome("Mother")
False
>>> can_string_be_rearranged_as_palindrome("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
for character in lower_case_input_str:
character_freq_dict[character] = character_freq_dict.get(character, 0) + 1
"""
Above line of code is equivalent to:
1) Getting the frequency of current character till previous index
>>> character_freq = character_freq_dict.get(character, 0)
2) Incrementing the frequency of current character by 1
>>> character_freq = character_freq + 1
3) Updating the frequency of current character
>>> character_freq_dict[character] = character_freq
"""
"""
OBSERVATIONS:
Even length palindrome
-> Every character appears even no.of times.
Odd length palindrome
-> Every character appears even no.of times except for one character.
LOGIC:
Step 1: We'll count number of characters that appear odd number of times i.e oddChar
Step 2:If we find more than 1 character that appears odd number of times,
It is not possible to rearrange as a palindrome
"""
odd_char = 0
for character_count in character_freq_dict.values():
if character_count % 2:
odd_char += 1
if odd_char > 1:
return False
return True
def benchmark(input_str: str = "") -> None:
"""
Benchmark code for comparing above 2 functions
"""
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome_counter(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
print(
"> can_string_be_rearranged_as_palindrome()",
"\tans =",
can_string_be_rearranged_as_palindrome(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
if __name__ == "__main__":
check_str = input(
"Enter string to determine if it can be rearranged as a palindrome or not: "
).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
| # Created by susmith98
from collections import Counter
from timeit import timeit
# Problem Description:
# Check if characters of the given string can be rearranged to form a palindrome.
# Counter is faster for long strings and non-Counter is faster for short strings.
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome_counter("Momo")
True
>>> can_string_be_rearranged_as_palindrome_counter("Mother")
False
>>> can_string_be_rearranged_as_palindrome_counter("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome("Momo")
True
>>> can_string_be_rearranged_as_palindrome("Mother")
False
>>> can_string_be_rearranged_as_palindrome("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
for character in lower_case_input_str:
character_freq_dict[character] = character_freq_dict.get(character, 0) + 1
"""
Above line of code is equivalent to:
1) Getting the frequency of current character till previous index
>>> character_freq = character_freq_dict.get(character, 0)
2) Incrementing the frequency of current character by 1
>>> character_freq = character_freq + 1
3) Updating the frequency of current character
>>> character_freq_dict[character] = character_freq
"""
"""
OBSERVATIONS:
Even length palindrome
-> Every character appears even no.of times.
Odd length palindrome
-> Every character appears even no.of times except for one character.
LOGIC:
Step 1: We'll count number of characters that appear odd number of times i.e oddChar
Step 2:If we find more than 1 character that appears odd number of times,
It is not possible to rearrange as a palindrome
"""
odd_char = 0
for character_count in character_freq_dict.values():
if character_count % 2:
odd_char += 1
if odd_char > 1:
return False
return True
def benchmark(input_str: str = "") -> None:
"""
Benchmark code for comparing above 2 functions
"""
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome_counter(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
print(
"> can_string_be_rearranged_as_palindrome()",
"\tans =",
can_string_be_rearranged_as_palindrome(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
if __name__ == "__main__":
check_str = input(
"Enter string to determine if it can be rearranged as a palindrome or not: "
).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
def hex_to_decimal(hex_string: str) -> int:
"""
Convert a hexadecimal value to its decimal equivalent
#https://www.programiz.com/python-programming/methods/built-in/hex
>>> hex_to_decimal("a")
10
>>> hex_to_decimal("12f")
303
>>> hex_to_decimal(" 12f ")
303
>>> hex_to_decimal("FfFf")
65535
>>> hex_to_decimal("-Ff")
-255
>>> hex_to_decimal("F-f")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
>>> hex_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> hex_to_decimal("12m")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
"""
hex_string = hex_string.strip().lower()
if not hex_string:
raise ValueError("Empty string was passed to the function")
is_negative = hex_string[0] == "-"
if is_negative:
hex_string = hex_string[1:]
if not all(char in hex_table for char in hex_string):
raise ValueError("Non-hexadecimal value was passed to the function")
decimal_number = 0
for char in hex_string:
decimal_number = 16 * decimal_number + hex_table[char]
return -decimal_number if is_negative else decimal_number
if __name__ == "__main__":
from doctest import testmod
testmod()
| hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
def hex_to_decimal(hex_string: str) -> int:
"""
Convert a hexadecimal value to its decimal equivalent
#https://www.programiz.com/python-programming/methods/built-in/hex
>>> hex_to_decimal("a")
10
>>> hex_to_decimal("12f")
303
>>> hex_to_decimal(" 12f ")
303
>>> hex_to_decimal("FfFf")
65535
>>> hex_to_decimal("-Ff")
-255
>>> hex_to_decimal("F-f")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
>>> hex_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> hex_to_decimal("12m")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
"""
hex_string = hex_string.strip().lower()
if not hex_string:
raise ValueError("Empty string was passed to the function")
is_negative = hex_string[0] == "-"
if is_negative:
hex_string = hex_string[1:]
if not all(char in hex_table for char in hex_string):
raise ValueError("Non-hexadecimal value was passed to the function")
decimal_number = 0
for char in hex_string:
decimal_number = 16 * decimal_number + hex_table[char]
return -decimal_number if is_negative else decimal_number
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
0-1-graph is the weighted graph with the weights equal to 0 or 1.
Link: https://codeforces.com/blog/entry/22276
"""
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Edge:
"""Weighted directed graph edge."""
destination_vertex: int
weight: int
class AdjacencyList:
"""Graph adjacency list."""
def __init__(self, size: int):
self._graph: list[list[Edge]] = [[] for _ in range(size)]
self._size = size
def __getitem__(self, vertex: int) -> Iterator[Edge]:
"""Get all the vertices adjacent to the given one."""
return iter(self._graph[vertex])
@property
def size(self):
return self._size
def add_edge(self, from_vertex: int, to_vertex: int, weight: int):
"""
>>> g = AdjacencyList(2)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(1, 0, 1)
>>> list(g[0])
[Edge(destination_vertex=1, weight=0)]
>>> list(g[1])
[Edge(destination_vertex=0, weight=1)]
>>> g.add_edge(0, 1, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.add_edge(0, 2, 1)
Traceback (most recent call last):
...
ValueError: Vertex indexes must be in [0; size).
"""
if weight not in (0, 1):
raise ValueError("Edge weight must be either 0 or 1.")
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError("Vertex indexes must be in [0; size).")
self._graph[from_vertex].append(Edge(to_vertex, weight))
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
"""
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
1 1 1
0--------->3 6--------7>------->8
| ^ ^ ^ |1
| | | |0 v
0| |0 1| 9-------->10
| | | ^ 1
v | | |0
1--------->2<-------4------->5
0 1 1
>>> g = AdjacencyList(11)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(0, 3, 1)
>>> g.add_edge(1, 2, 0)
>>> g.add_edge(2, 3, 0)
>>> g.add_edge(4, 2, 1)
>>> g.add_edge(4, 5, 1)
>>> g.add_edge(4, 6, 1)
>>> g.add_edge(5, 9, 0)
>>> g.add_edge(6, 7, 1)
>>> g.add_edge(7, 8, 1)
>>> g.add_edge(8, 10, 1)
>>> g.add_edge(9, 7, 0)
>>> g.add_edge(9, 10, 1)
>>> g.add_edge(1, 2, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.get_shortest_path(0, 3)
0
>>> g.get_shortest_path(0, 4)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
>>> g.get_shortest_path(4, 10)
2
>>> g.get_shortest_path(4, 8)
2
>>> g.get_shortest_path(0, 1)
0
>>> g.get_shortest_path(1, 0)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
"""
queue = deque([start_vertex])
distances: list[int | None] = [None] * self.size
distances[start_vertex] = 0
while queue:
current_vertex = queue.popleft()
current_distance = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
new_distance = current_distance + edge.weight
dest_vertex_distance = distances[edge.destination_vertex]
if (
isinstance(dest_vertex_distance, int)
and new_distance >= dest_vertex_distance
):
continue
distances[edge.destination_vertex] = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex)
else:
queue.append(edge.destination_vertex)
if distances[finish_vertex] is None:
raise ValueError("No path from start_vertex to finish_vertex.")
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
0-1-graph is the weighted graph with the weights equal to 0 or 1.
Link: https://codeforces.com/blog/entry/22276
"""
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Edge:
"""Weighted directed graph edge."""
destination_vertex: int
weight: int
class AdjacencyList:
"""Graph adjacency list."""
def __init__(self, size: int):
self._graph: list[list[Edge]] = [[] for _ in range(size)]
self._size = size
def __getitem__(self, vertex: int) -> Iterator[Edge]:
"""Get all the vertices adjacent to the given one."""
return iter(self._graph[vertex])
@property
def size(self):
return self._size
def add_edge(self, from_vertex: int, to_vertex: int, weight: int):
"""
>>> g = AdjacencyList(2)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(1, 0, 1)
>>> list(g[0])
[Edge(destination_vertex=1, weight=0)]
>>> list(g[1])
[Edge(destination_vertex=0, weight=1)]
>>> g.add_edge(0, 1, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.add_edge(0, 2, 1)
Traceback (most recent call last):
...
ValueError: Vertex indexes must be in [0; size).
"""
if weight not in (0, 1):
raise ValueError("Edge weight must be either 0 or 1.")
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError("Vertex indexes must be in [0; size).")
self._graph[from_vertex].append(Edge(to_vertex, weight))
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
"""
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
1 1 1
0--------->3 6--------7>------->8
| ^ ^ ^ |1
| | | |0 v
0| |0 1| 9-------->10
| | | ^ 1
v | | |0
1--------->2<-------4------->5
0 1 1
>>> g = AdjacencyList(11)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(0, 3, 1)
>>> g.add_edge(1, 2, 0)
>>> g.add_edge(2, 3, 0)
>>> g.add_edge(4, 2, 1)
>>> g.add_edge(4, 5, 1)
>>> g.add_edge(4, 6, 1)
>>> g.add_edge(5, 9, 0)
>>> g.add_edge(6, 7, 1)
>>> g.add_edge(7, 8, 1)
>>> g.add_edge(8, 10, 1)
>>> g.add_edge(9, 7, 0)
>>> g.add_edge(9, 10, 1)
>>> g.add_edge(1, 2, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.get_shortest_path(0, 3)
0
>>> g.get_shortest_path(0, 4)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
>>> g.get_shortest_path(4, 10)
2
>>> g.get_shortest_path(4, 8)
2
>>> g.get_shortest_path(0, 1)
0
>>> g.get_shortest_path(1, 0)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
"""
queue = deque([start_vertex])
distances: list[int | None] = [None] * self.size
distances[start_vertex] = 0
while queue:
current_vertex = queue.popleft()
current_distance = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
new_distance = current_distance + edge.weight
dest_vertex_distance = distances[edge.destination_vertex]
if (
isinstance(dest_vertex_distance, int)
and new_distance >= dest_vertex_distance
):
continue
distances[edge.destination_vertex] = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex)
else:
queue.append(edge.destination_vertex)
if distances[finish_vertex] is None:
raise ValueError("No path from start_vertex to finish_vertex.")
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| #!/usr/bin/env python3
from .number_theory.prime_numbers import next_prime
class HashTable:
"""
Basic Hash Table example with open addressing and linear probing
"""
def __init__(
self,
size_table: int,
charge_factor: int | None = None,
lim_charge: float | None = None,
) -> None:
self.size_table = size_table
self.values = [None] * self.size_table
self.lim_charge = 0.75 if lim_charge is None else lim_charge
self.charge_factor = 1 if charge_factor is None else charge_factor
self.__aux_list: list = []
self._keys: dict = {}
def keys(self):
return self._keys
def balanced_factor(self):
return sum(1 for slot in self.values if slot is not None) / (
self.size_table * self.charge_factor
)
def hash_function(self, key):
return key % self.size_table
def _step_by_step(self, step_ord):
print(f"step {step_ord}")
print(list(range(len(self.values))))
print(self.values)
def bulk_insert(self, values):
i = 1
self.__aux_list = values
for value in values:
self.insert_data(value)
self._step_by_step(i)
i += 1
def _set_value(self, key, data):
self.values[key] = data
self._keys[key] = data
def _collision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
else:
new_key = None
break
return new_key
def rehashing(self):
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/
for value in survivor_values:
self.insert_data(value)
def insert_data(self, data):
key = self.hash_function(data)
if self.values[key] is None:
self._set_value(key, data)
elif self.values[key] == data:
pass
else:
collision_resolution = self._collision_resolution(key, data)
if collision_resolution is not None:
self._set_value(collision_resolution, data)
else:
self.rehashing()
self.insert_data(data)
| #!/usr/bin/env python3
from .number_theory.prime_numbers import next_prime
class HashTable:
"""
Basic Hash Table example with open addressing and linear probing
"""
def __init__(
self,
size_table: int,
charge_factor: int | None = None,
lim_charge: float | None = None,
) -> None:
self.size_table = size_table
self.values = [None] * self.size_table
self.lim_charge = 0.75 if lim_charge is None else lim_charge
self.charge_factor = 1 if charge_factor is None else charge_factor
self.__aux_list: list = []
self._keys: dict = {}
def keys(self):
return self._keys
def balanced_factor(self):
return sum(1 for slot in self.values if slot is not None) / (
self.size_table * self.charge_factor
)
def hash_function(self, key):
return key % self.size_table
def _step_by_step(self, step_ord):
print(f"step {step_ord}")
print(list(range(len(self.values))))
print(self.values)
def bulk_insert(self, values):
i = 1
self.__aux_list = values
for value in values:
self.insert_data(value)
self._step_by_step(i)
i += 1
def _set_value(self, key, data):
self.values[key] = data
self._keys[key] = data
def _collision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
else:
new_key = None
break
return new_key
def rehashing(self):
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/
for value in survivor_values:
self.insert_data(value)
def insert_data(self, data):
key = self.hash_function(data)
if self.values[key] is None:
self._set_value(key, data)
elif self.values[key] == data:
pass
else:
collision_resolution = self._collision_resolution(key, data)
if collision_resolution is not None:
self._set_value(collision_resolution, data)
else:
self.rehashing()
self.insert_data(data)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """Borůvka's algorithm.
Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm.
Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a
connected graph, or a minimum spanning forest if a graph that is not connected.
The time complexity of this algorithm is O(ELogV), where E represents the number
of edges, while V represents the number of nodes.
O(number_of_edges Log number_of_nodes)
The space complexity of this algorithm is O(V + E), since we have to keep a couple
of lists whose sizes are equal to the number of nodes, as well as keep all the
edges of a graph inside of the data structure itself.
Borůvka's algorithm gives us pretty much the same result as other MST Algorithms -
they all find the minimum spanning tree, and the time complexity is approximately
the same.
One advantage that Borůvka's algorithm has compared to the alternatives is that it
doesn't need to presort the edges or maintain a priority queue in order to find the
minimum spanning tree.
Even though that doesn't help its complexity, since it still passes the edges logE
times, it is a bit simpler to code.
Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm
"""
from __future__ import annotations
from typing import Any
class Graph:
def __init__(self, num_of_nodes: int) -> None:
"""
Arguments:
num_of_nodes - the number of nodes in the graph
Attributes:
m_num_of_nodes - the number of nodes in the graph.
m_edges - the list of edges.
m_component - the dictionary which stores the index of the component which
a node belongs to.
"""
self.m_num_of_nodes = num_of_nodes
self.m_edges: list[list[int]] = []
self.m_component: dict[int, int] = {}
def add_edge(self, u_node: int, v_node: int, weight: int) -> None:
"""Adds an edge in the format [first, second, edge weight] to graph."""
self.m_edges.append([u_node, v_node, weight])
def find_component(self, u_node: int) -> int:
"""Propagates a new component throughout a given component."""
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node])
def set_component(self, u_node: int) -> None:
"""Finds the component index of a given node"""
if self.m_component[u_node] != u_node:
for k in self.m_component:
self.m_component[k] = self.find_component(k)
def union(self, component_size: list[int], u_node: int, v_node: int) -> None:
"""Union finds the roots of components for two nodes, compares the components
in terms of size, and attaches the smaller one to the larger one to form
single component"""
if component_size[u_node] <= component_size[v_node]:
self.m_component[u_node] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(u_node)
elif component_size[u_node] >= component_size[v_node]:
self.m_component[v_node] = self.find_component(u_node)
component_size[u_node] += component_size[v_node]
self.set_component(v_node)
def boruvka(self) -> None:
"""Performs Borůvka's algorithm to find MST."""
# Initialize additional lists required to algorithm.
component_size = []
mst_weight = 0
minimum_weight_edge: list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes):
self.m_component.update({node: node})
component_size.append(1)
num_of_components = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
u, v, w = edge
u_component = self.m_component[u]
v_component = self.m_component[v]
if u_component != v_component:
"""If the current minimum weight edge of component u doesn't
exist (is -1), or if it's greater than the edge we're
observing right now, we will assign the value of the edge
we're observing to it.
If the current minimum weight edge of component v doesn't
exist (is -1), or if it's greater than the edge we're
observing right now, we will assign the value of the edge
we're observing to it"""
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
minimum_weight_edge[component] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(edge, list):
u, v, w = edge
u_component = self.m_component[u]
v_component = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(component_size, u_component, v_component)
print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n")
num_of_components -= 1
minimum_weight_edge = [-1] * self.m_num_of_nodes
print(f"The total weight of the minimal spanning tree is: {mst_weight}")
def test_vector() -> None:
"""
>>> g = Graph(8)
>>> for u_v_w in ((0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4),
... (3, 4, 8), (4, 5, 10), (4, 6, 6), (4, 7, 5), (5, 7, 15), (6, 7, 4)):
... g.add_edge(*u_v_w)
>>> g.boruvka()
Added edge [0 - 3]
Added weight: 5
<BLANKLINE>
Added edge [0 - 1]
Added weight: 10
<BLANKLINE>
Added edge [2 - 3]
Added weight: 4
<BLANKLINE>
Added edge [4 - 7]
Added weight: 5
<BLANKLINE>
Added edge [4 - 5]
Added weight: 10
<BLANKLINE>
Added edge [6 - 7]
Added weight: 4
<BLANKLINE>
Added edge [3 - 4]
Added weight: 8
<BLANKLINE>
The total weight of the minimal spanning tree is: 46
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| """Borůvka's algorithm.
Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm.
Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a
connected graph, or a minimum spanning forest if a graph that is not connected.
The time complexity of this algorithm is O(ELogV), where E represents the number
of edges, while V represents the number of nodes.
O(number_of_edges Log number_of_nodes)
The space complexity of this algorithm is O(V + E), since we have to keep a couple
of lists whose sizes are equal to the number of nodes, as well as keep all the
edges of a graph inside of the data structure itself.
Borůvka's algorithm gives us pretty much the same result as other MST Algorithms -
they all find the minimum spanning tree, and the time complexity is approximately
the same.
One advantage that Borůvka's algorithm has compared to the alternatives is that it
doesn't need to presort the edges or maintain a priority queue in order to find the
minimum spanning tree.
Even though that doesn't help its complexity, since it still passes the edges logE
times, it is a bit simpler to code.
Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm
"""
from __future__ import annotations
from typing import Any
class Graph:
def __init__(self, num_of_nodes: int) -> None:
"""
Arguments:
num_of_nodes - the number of nodes in the graph
Attributes:
m_num_of_nodes - the number of nodes in the graph.
m_edges - the list of edges.
m_component - the dictionary which stores the index of the component which
a node belongs to.
"""
self.m_num_of_nodes = num_of_nodes
self.m_edges: list[list[int]] = []
self.m_component: dict[int, int] = {}
def add_edge(self, u_node: int, v_node: int, weight: int) -> None:
"""Adds an edge in the format [first, second, edge weight] to graph."""
self.m_edges.append([u_node, v_node, weight])
def find_component(self, u_node: int) -> int:
"""Propagates a new component throughout a given component."""
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node])
def set_component(self, u_node: int) -> None:
"""Finds the component index of a given node"""
if self.m_component[u_node] != u_node:
for k in self.m_component:
self.m_component[k] = self.find_component(k)
def union(self, component_size: list[int], u_node: int, v_node: int) -> None:
"""Union finds the roots of components for two nodes, compares the components
in terms of size, and attaches the smaller one to the larger one to form
single component"""
if component_size[u_node] <= component_size[v_node]:
self.m_component[u_node] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(u_node)
elif component_size[u_node] >= component_size[v_node]:
self.m_component[v_node] = self.find_component(u_node)
component_size[u_node] += component_size[v_node]
self.set_component(v_node)
def boruvka(self) -> None:
"""Performs Borůvka's algorithm to find MST."""
# Initialize additional lists required to algorithm.
component_size = []
mst_weight = 0
minimum_weight_edge: list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes):
self.m_component.update({node: node})
component_size.append(1)
num_of_components = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
u, v, w = edge
u_component = self.m_component[u]
v_component = self.m_component[v]
if u_component != v_component:
"""If the current minimum weight edge of component u doesn't
exist (is -1), or if it's greater than the edge we're
observing right now, we will assign the value of the edge
we're observing to it.
If the current minimum weight edge of component v doesn't
exist (is -1), or if it's greater than the edge we're
observing right now, we will assign the value of the edge
we're observing to it"""
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
minimum_weight_edge[component] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(edge, list):
u, v, w = edge
u_component = self.m_component[u]
v_component = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(component_size, u_component, v_component)
print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n")
num_of_components -= 1
minimum_weight_edge = [-1] * self.m_num_of_nodes
print(f"The total weight of the minimal spanning tree is: {mst_weight}")
def test_vector() -> None:
"""
>>> g = Graph(8)
>>> for u_v_w in ((0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4),
... (3, 4, 8), (4, 5, 10), (4, 6, 6), (4, 7, 5), (5, 7, 15), (6, 7, 4)):
... g.add_edge(*u_v_w)
>>> g.boruvka()
Added edge [0 - 3]
Added weight: 5
<BLANKLINE>
Added edge [0 - 1]
Added weight: 10
<BLANKLINE>
Added edge [2 - 3]
Added weight: 4
<BLANKLINE>
Added edge [4 - 7]
Added weight: 5
<BLANKLINE>
Added edge [4 - 5]
Added weight: 10
<BLANKLINE>
Added edge [6 - 7]
Added weight: 4
<BLANKLINE>
Added edge [3 - 4]
Added weight: 8
<BLANKLINE>
The total weight of the minimal spanning tree is: 46
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from collections.abc import Callable
import numpy as np
def explicit_euler(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
) -> np.ndarray:
"""Calculate numeric solution at each step to an ODE using Euler's Method
For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method.
Args:
ode_func (Callable): The ordinary differential equation
as a function of x and y.
y0 (float): The initial value for y.
x0 (float): The initial value for x.
step_size (float): The increment value for x.
x_end (float): The final value of x to be calculated.
Returns:
np.ndarray: Solution of y for every step in x.
>>> # the exact solution is math.exp(x)
>>> def f(x, y):
... return y
>>> y0 = 1
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
>>> y[-1]
144.77277243257308
"""
n = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((n + 1,))
y[0] = y0
x = x0
for k in range(n):
y[k + 1] = y[k] + step_size * ode_func(x, y[k])
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| from collections.abc import Callable
import numpy as np
def explicit_euler(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
) -> np.ndarray:
"""Calculate numeric solution at each step to an ODE using Euler's Method
For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method.
Args:
ode_func (Callable): The ordinary differential equation
as a function of x and y.
y0 (float): The initial value for y.
x0 (float): The initial value for x.
step_size (float): The increment value for x.
x_end (float): The final value of x to be calculated.
Returns:
np.ndarray: Solution of y for every step in x.
>>> # the exact solution is math.exp(x)
>>> def f(x, y):
... return y
>>> y0 = 1
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
>>> y[-1]
144.77277243257308
"""
n = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((n + 1,))
y[0] = y0
x = x0
for k in range(n):
y[k + 1] = y[k] + step_size * ode_func(x, y[k])
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms
"""
def is_isogram(string: str) -> bool:
"""
An isogram is a word in which no letter is repeated.
Examples of isograms are uncopyrightable and ambidextrously.
>>> is_isogram('Uncopyrightable')
True
>>> is_isogram('allowance')
False
>>> is_isogram('copy1')
Traceback (most recent call last):
...
ValueError: String must only contain alphabetic characters.
"""
if not all(x.isalpha() for x in string):
raise ValueError("String must only contain alphabetic characters.")
letters = sorted(string.lower())
return len(letters) == len(set(letters))
if __name__ == "__main__":
input_str = input("Enter a string ").strip()
isogram = is_isogram(input_str)
print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
| """
wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms
"""
def is_isogram(string: str) -> bool:
"""
An isogram is a word in which no letter is repeated.
Examples of isograms are uncopyrightable and ambidextrously.
>>> is_isogram('Uncopyrightable')
True
>>> is_isogram('allowance')
False
>>> is_isogram('copy1')
Traceback (most recent call last):
...
ValueError: String must only contain alphabetic characters.
"""
if not all(x.isalpha() for x in string):
raise ValueError("String must only contain alphabetic characters.")
letters = sorted(string.lower())
return len(letters) == len(set(letters))
if __name__ == "__main__":
input_str = input("Enter a string ").strip()
isogram = is_isogram(input_str)
print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # https://en.wikipedia.org/wiki/Simulated_annealing
import math
import random
from typing import Any
from .hill_climbing import SearchProblem
def simulated_annealing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
start_temperate: float = 100,
rate_of_decrease: float = 0.01,
threshold_temp: float = 1,
) -> Any:
"""
Implementation of the simulated annealing algorithm. We start with a given state,
find all its neighbors. Pick a random neighbor, if that neighbor improves the
solution, we move in that direction, if that neighbor does not improve the solution,
we generate a random real number between 0 and 1, if the number is within a certain
range (calculated using temperature) we move in that direction, else we pick
another neighbor randomly and repeat the process.
Args:
search_prob: The search state at the start.
find_max: If True, the algorithm should find the minimum else the minimum.
max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y.
visualization: If True, a matplotlib graph is displayed.
start_temperate: the initial temperate of the system when the program starts.
rate_of_decrease: the rate at which the temperate decreases in each iteration.
threshold_temp: the threshold temperature below which we end the search
Returns a search state having the maximum (or minimum) score.
"""
search_end = False
current_state = search_prob
current_temp = start_temperate
scores = []
iterations = 0
best_state = None
while not search_end:
current_score = current_state.score()
if best_state is None or current_score > best_state.score():
best_state = current_state
scores.append(current_score)
iterations += 1
next_state = None
neighbors = current_state.get_neighbors()
while (
next_state is None and neighbors
): # till we do not find a neighbor that we can move to
index = random.randint(0, len(neighbors) - 1) # picking a random neighbor
picked_neighbor = neighbors.pop(index)
change = picked_neighbor.score() - current_score
if (
picked_neighbor.x > max_x
or picked_neighbor.x < min_x
or picked_neighbor.y > max_y
or picked_neighbor.y < min_y
):
continue # neighbor outside our bounds
if not find_max:
change = change * -1 # in case we are finding minimum
if change > 0: # improves the solution
next_state = picked_neighbor
else:
probability = (math.e) ** (
change / current_temp
) # probability generation function
if random.random() < probability: # random number within probability
next_state = picked_neighbor
current_temp = current_temp - (current_temp * rate_of_decrease)
if current_temp < threshold_temp or next_state is None:
# temperature below threshold, or could not find a suitable neighbor
search_end = True
else:
current_state = next_state
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return best_state
if __name__ == "__main__":
def test_f1(x, y):
return (x**2) + (y**2)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(
prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(
prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
def test_f2(x, y):
return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=False, visualization=True)
print(
"The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: "
f"{local_min.score()}"
)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=True, visualization=True)
print(
"The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: "
f"{local_min.score()}"
)
| # https://en.wikipedia.org/wiki/Simulated_annealing
import math
import random
from typing import Any
from .hill_climbing import SearchProblem
def simulated_annealing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
start_temperate: float = 100,
rate_of_decrease: float = 0.01,
threshold_temp: float = 1,
) -> Any:
"""
Implementation of the simulated annealing algorithm. We start with a given state,
find all its neighbors. Pick a random neighbor, if that neighbor improves the
solution, we move in that direction, if that neighbor does not improve the solution,
we generate a random real number between 0 and 1, if the number is within a certain
range (calculated using temperature) we move in that direction, else we pick
another neighbor randomly and repeat the process.
Args:
search_prob: The search state at the start.
find_max: If True, the algorithm should find the minimum else the minimum.
max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y.
visualization: If True, a matplotlib graph is displayed.
start_temperate: the initial temperate of the system when the program starts.
rate_of_decrease: the rate at which the temperate decreases in each iteration.
threshold_temp: the threshold temperature below which we end the search
Returns a search state having the maximum (or minimum) score.
"""
search_end = False
current_state = search_prob
current_temp = start_temperate
scores = []
iterations = 0
best_state = None
while not search_end:
current_score = current_state.score()
if best_state is None or current_score > best_state.score():
best_state = current_state
scores.append(current_score)
iterations += 1
next_state = None
neighbors = current_state.get_neighbors()
while (
next_state is None and neighbors
): # till we do not find a neighbor that we can move to
index = random.randint(0, len(neighbors) - 1) # picking a random neighbor
picked_neighbor = neighbors.pop(index)
change = picked_neighbor.score() - current_score
if (
picked_neighbor.x > max_x
or picked_neighbor.x < min_x
or picked_neighbor.y > max_y
or picked_neighbor.y < min_y
):
continue # neighbor outside our bounds
if not find_max:
change = change * -1 # in case we are finding minimum
if change > 0: # improves the solution
next_state = picked_neighbor
else:
probability = (math.e) ** (
change / current_temp
) # probability generation function
if random.random() < probability: # random number within probability
next_state = picked_neighbor
current_temp = current_temp - (current_temp * rate_of_decrease)
if current_temp < threshold_temp or next_state is None:
# temperature below threshold, or could not find a suitable neighbor
search_end = True
else:
current_state = next_state
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return best_state
if __name__ == "__main__":
def test_f1(x, y):
return (x**2) + (y**2)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(
prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(
prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
def test_f2(x, y):
return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=False, visualization=True)
print(
"The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: "
f"{local_min.score()}"
)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=True, visualization=True)
print(
"The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: "
f"{local_min.score()}"
)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
T = TypeVar("T")
class LRUCache(Generic[T]):
"""
Page Replacement Algorithm, Least Recently Used (LRU) Caching.
>>> lru_cache: LRUCache[str | int] = LRUCache(4)
>>> lru_cache.refer("A")
>>> lru_cache.refer(2)
>>> lru_cache.refer(3)
>>> lru_cache
LRUCache(4) => [3, 2, 'A']
>>> lru_cache.refer("A")
>>> lru_cache
LRUCache(4) => ['A', 3, 2]
>>> lru_cache.refer(4)
>>> lru_cache.refer(5)
>>> lru_cache
LRUCache(4) => [5, 4, 'A', 3]
"""
dq_store: deque[T] # Cache store of keys
key_reference: set[T] # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache
def __init__(self, n: int) -> None:
"""Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference = set()
if not n:
LRUCache._MAX_CAPACITY = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0.")
else:
LRUCache._MAX_CAPACITY = n
def refer(self, x: T) -> None:
"""
Looks for a page in the cache store and adds reference to the set.
Remove the least recently used key if the store is full.
Update store to reflect recent access.
"""
if x not in self.key_reference:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference.remove(last_element)
else:
self.dq_store.remove(x)
self.dq_store.appendleft(x)
self.key_reference.add(x)
def display(self) -> None:
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)
def __repr__(self) -> str:
return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}"
if __name__ == "__main__":
import doctest
doctest.testmod()
lru_cache: LRUCache[str | int] = LRUCache(4)
lru_cache.refer("A")
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer("A")
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
T = TypeVar("T")
class LRUCache(Generic[T]):
"""
Page Replacement Algorithm, Least Recently Used (LRU) Caching.
>>> lru_cache: LRUCache[str | int] = LRUCache(4)
>>> lru_cache.refer("A")
>>> lru_cache.refer(2)
>>> lru_cache.refer(3)
>>> lru_cache
LRUCache(4) => [3, 2, 'A']
>>> lru_cache.refer("A")
>>> lru_cache
LRUCache(4) => ['A', 3, 2]
>>> lru_cache.refer(4)
>>> lru_cache.refer(5)
>>> lru_cache
LRUCache(4) => [5, 4, 'A', 3]
"""
dq_store: deque[T] # Cache store of keys
key_reference: set[T] # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache
def __init__(self, n: int) -> None:
"""Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference = set()
if not n:
LRUCache._MAX_CAPACITY = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0.")
else:
LRUCache._MAX_CAPACITY = n
def refer(self, x: T) -> None:
"""
Looks for a page in the cache store and adds reference to the set.
Remove the least recently used key if the store is full.
Update store to reflect recent access.
"""
if x not in self.key_reference:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference.remove(last_element)
else:
self.dq_store.remove(x)
self.dq_store.appendleft(x)
self.key_reference.add(x)
def display(self) -> None:
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)
def __repr__(self) -> str:
return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}"
if __name__ == "__main__":
import doctest
doctest.testmod()
lru_cache: LRUCache[str | int] = LRUCache(4)
lru_cache.refer("A")
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer("A")
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
The algorithm finds distance between closest pair of points
in the given n points.
Approach used -> Divide and conquer
The points are sorted based on Xco-ords and
then based on Yco-ords separately.
And by applying divide and conquer approach,
minimum distance is obtained recursively.
>> Closest points can lie on different sides of partition.
This case handled by forming a strip of points
whose Xco-ords distance is less than closest_pair_dis
from mid-point's Xco-ords. Points sorted based on Yco-ords
are used in this step to reduce sorting time.
Closest pair distance is found in the strip of points. (closest_in_strip)
min(closest_pair_dis, closest_in_strip) would be the final answer.
Time complexity: O(n * log n)
"""
def euclidean_distance_sqr(point1, point2):
"""
>>> euclidean_distance_sqr([1,2],[2,4])
5
"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def column_based_sort(array, column=0):
"""
>>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1)
[(3, 0), (5, 1), (4, 2)]
"""
return sorted(array, key=lambda x: x[column])
def dis_between_closest_pair(points, points_counts, min_dis=float("inf")):
"""
brute force approach to find distance between closest pair points
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance between closest pair of points
>>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
5
"""
for i in range(points_counts - 1):
for j in range(i + 1, points_counts):
current_dis = euclidean_distance_sqr(points[i], points[j])
if current_dis < min_dis:
min_dis = current_dis
return min_dis
def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")):
"""
closest pair of points in strip
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance btw closest pair of points in the strip (< min_dis)
>>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
85
"""
for i in range(min(6, points_counts - 1), points_counts):
for j in range(max(0, i - 6), i):
current_dis = euclidean_distance_sqr(points[i], points[j])
if current_dis < min_dis:
min_dis = current_dis
return min_dis
def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
"""divide and conquer approach
Parameters :
points, points_count (list(tuple(int, int)), int)
Returns :
(float): distance btw closest pair of points
>>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2)
8
"""
# base case
if points_counts <= 3:
return dis_between_closest_pair(points_sorted_on_x, points_counts)
# recursion
mid = points_counts // 2
closest_in_left = closest_pair_of_points_sqr(
points_sorted_on_x, points_sorted_on_y[:mid], mid
)
closest_in_right = closest_pair_of_points_sqr(
points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid
)
closest_pair_dis = min(closest_in_left, closest_in_right)
"""
cross_strip contains the points, whose Xcoords are at a
distance(< closest_pair_dis) from mid's Xcoord
"""
cross_strip = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis:
cross_strip.append(point)
closest_in_strip = dis_between_closest_in_strip(
cross_strip, len(cross_strip), closest_pair_dis
)
return min(closest_pair_dis, closest_in_strip)
def closest_pair_of_points(points, points_counts):
"""
>>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)]))
28.792360097775937
"""
points_sorted_on_x = column_based_sort(points, column=0)
points_sorted_on_y = column_based_sort(points, column=1)
return (
closest_pair_of_points_sqr(
points_sorted_on_x, points_sorted_on_y, points_counts
)
) ** 0.5
if __name__ == "__main__":
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print("Distance:", closest_pair_of_points(points, len(points)))
| """
The algorithm finds distance between closest pair of points
in the given n points.
Approach used -> Divide and conquer
The points are sorted based on Xco-ords and
then based on Yco-ords separately.
And by applying divide and conquer approach,
minimum distance is obtained recursively.
>> Closest points can lie on different sides of partition.
This case handled by forming a strip of points
whose Xco-ords distance is less than closest_pair_dis
from mid-point's Xco-ords. Points sorted based on Yco-ords
are used in this step to reduce sorting time.
Closest pair distance is found in the strip of points. (closest_in_strip)
min(closest_pair_dis, closest_in_strip) would be the final answer.
Time complexity: O(n * log n)
"""
def euclidean_distance_sqr(point1, point2):
"""
>>> euclidean_distance_sqr([1,2],[2,4])
5
"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def column_based_sort(array, column=0):
"""
>>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1)
[(3, 0), (5, 1), (4, 2)]
"""
return sorted(array, key=lambda x: x[column])
def dis_between_closest_pair(points, points_counts, min_dis=float("inf")):
"""
brute force approach to find distance between closest pair points
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance between closest pair of points
>>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
5
"""
for i in range(points_counts - 1):
for j in range(i + 1, points_counts):
current_dis = euclidean_distance_sqr(points[i], points[j])
if current_dis < min_dis:
min_dis = current_dis
return min_dis
def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")):
"""
closest pair of points in strip
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance btw closest pair of points in the strip (< min_dis)
>>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
85
"""
for i in range(min(6, points_counts - 1), points_counts):
for j in range(max(0, i - 6), i):
current_dis = euclidean_distance_sqr(points[i], points[j])
if current_dis < min_dis:
min_dis = current_dis
return min_dis
def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
"""divide and conquer approach
Parameters :
points, points_count (list(tuple(int, int)), int)
Returns :
(float): distance btw closest pair of points
>>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2)
8
"""
# base case
if points_counts <= 3:
return dis_between_closest_pair(points_sorted_on_x, points_counts)
# recursion
mid = points_counts // 2
closest_in_left = closest_pair_of_points_sqr(
points_sorted_on_x, points_sorted_on_y[:mid], mid
)
closest_in_right = closest_pair_of_points_sqr(
points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid
)
closest_pair_dis = min(closest_in_left, closest_in_right)
"""
cross_strip contains the points, whose Xcoords are at a
distance(< closest_pair_dis) from mid's Xcoord
"""
cross_strip = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis:
cross_strip.append(point)
closest_in_strip = dis_between_closest_in_strip(
cross_strip, len(cross_strip), closest_pair_dis
)
return min(closest_pair_dis, closest_in_strip)
def closest_pair_of_points(points, points_counts):
"""
>>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)]))
28.792360097775937
"""
points_sorted_on_x = column_based_sort(points, column=0)
points_sorted_on_y = column_based_sort(points, column=1)
return (
closest_pair_of_points_sqr(
points_sorted_on_x, points_sorted_on_y, points_counts
)
) ** 0.5
if __name__ == "__main__":
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print("Distance:", closest_pair_of_points(points, len(points)))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| #!/usr/bin/env python3
# Author: OMKAR PATHAK, Nwachukwu Chidiebere
# Use a Python dictionary to construct the graph.
from __future__ import annotations
from pprint import pformat
from typing import Generic, TypeVar
T = TypeVar("T")
class GraphAdjacencyList(Generic[T]):
"""
Adjacency List type Graph Data Structure that accounts for directed and undirected
Graphs. Initialize graph object indicating whether it's directed or undirected.
Directed graph example:
>>> d_graph = GraphAdjacencyList()
>>> print(d_graph)
{}
>>> d_graph.add_edge(0, 1)
{0: [1], 1: []}
>>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5)
{0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []}
>>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7)
{0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}
>>> d_graph
{0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}
>>> print(repr(d_graph))
{0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}
Undirected graph example:
>>> u_graph = GraphAdjacencyList(directed=False)
>>> u_graph.add_edge(0, 1)
{0: [1], 1: [0]}
>>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5)
{0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]}
>>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7)
{0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]}
>>> u_graph.add_edge(4, 5)
{0: [1, 2],
1: [0, 2, 4, 5],
2: [1, 0, 6, 7],
4: [1, 5],
5: [1, 4],
6: [2],
7: [2]}
>>> print(u_graph)
{0: [1, 2],
1: [0, 2, 4, 5],
2: [1, 0, 6, 7],
4: [1, 5],
5: [1, 4],
6: [2],
7: [2]}
>>> print(repr(u_graph))
{0: [1, 2],
1: [0, 2, 4, 5],
2: [1, 0, 6, 7],
4: [1, 5],
5: [1, 4],
6: [2],
7: [2]}
>>> char_graph = GraphAdjacencyList(directed=False)
>>> char_graph.add_edge('a', 'b')
{'a': ['b'], 'b': ['a']}
>>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f')
{'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']}
>>> char_graph
{'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']}
"""
def __init__(self, directed: bool = True) -> None:
"""
Parameters:
directed: (bool) Indicates if graph is directed or undirected. Default is True.
"""
self.adj_list: dict[T, list[T]] = {} # dictionary of lists
self.directed = directed
def add_edge(
self, source_vertex: T, destination_vertex: T
) -> GraphAdjacencyList[T]:
"""
Connects vertices together. Creates and Edge from source vertex to destination
vertex.
Vertices will be created if not found in graph
"""
if not self.directed: # For undirected graphs
# if both source vertex and destination vertex are both present in the
# adjacency list, add destination vertex to source vertex list of adjacent
# vertices and add source vertex to destination vertex list of adjacent
# vertices.
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
self.adj_list[destination_vertex].append(source_vertex)
# if only source vertex is present in adjacency list, add destination vertex
# to source vertex list of adjacent vertices, then create a new vertex with
# destination vertex as key and assign a list containing the source vertex
# as it's first adjacent vertex.
elif source_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
self.adj_list[destination_vertex] = [source_vertex]
# if only destination vertex is present in adjacency list, add source vertex
# to destination vertex list of adjacent vertices, then create a new vertex
# with source vertex as key and assign a list containing the source vertex
# as it's first adjacent vertex.
elif destination_vertex in self.adj_list:
self.adj_list[destination_vertex].append(source_vertex)
self.adj_list[source_vertex] = [destination_vertex]
# if both source vertex and destination vertex are not present in adjacency
# list, create a new vertex with source vertex as key and assign a list
# containing the destination vertex as it's first adjacent vertex also
# create a new vertex with destination vertex as key and assign a list
# containing the source vertex as it's first adjacent vertex.
else:
self.adj_list[source_vertex] = [destination_vertex]
self.adj_list[destination_vertex] = [source_vertex]
else: # For directed graphs
# if both source vertex and destination vertex are present in adjacency
# list, add destination vertex to source vertex list of adjacent vertices.
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
# if only source vertex is present in adjacency list, add destination
# vertex to source vertex list of adjacent vertices and create a new vertex
# with destination vertex as key, which has no adjacent vertex
elif source_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
self.adj_list[destination_vertex] = []
# if only destination vertex is present in adjacency list, create a new
# vertex with source vertex as key and assign a list containing destination
# vertex as first adjacent vertex
elif destination_vertex in self.adj_list:
self.adj_list[source_vertex] = [destination_vertex]
# if both source vertex and destination vertex are not present in adjacency
# list, create a new vertex with source vertex as key and a list containing
# destination vertex as it's first adjacent vertex. Then create a new vertex
# with destination vertex as key, which has no adjacent vertex
else:
self.adj_list[source_vertex] = [destination_vertex]
self.adj_list[destination_vertex] = []
return self
def __repr__(self) -> str:
return pformat(self.adj_list)
| #!/usr/bin/env python3
# Author: OMKAR PATHAK, Nwachukwu Chidiebere
# Use a Python dictionary to construct the graph.
from __future__ import annotations
from pprint import pformat
from typing import Generic, TypeVar
T = TypeVar("T")
class GraphAdjacencyList(Generic[T]):
"""
Adjacency List type Graph Data Structure that accounts for directed and undirected
Graphs. Initialize graph object indicating whether it's directed or undirected.
Directed graph example:
>>> d_graph = GraphAdjacencyList()
>>> print(d_graph)
{}
>>> d_graph.add_edge(0, 1)
{0: [1], 1: []}
>>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5)
{0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []}
>>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7)
{0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}
>>> d_graph
{0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}
>>> print(repr(d_graph))
{0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}
Undirected graph example:
>>> u_graph = GraphAdjacencyList(directed=False)
>>> u_graph.add_edge(0, 1)
{0: [1], 1: [0]}
>>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5)
{0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]}
>>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7)
{0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]}
>>> u_graph.add_edge(4, 5)
{0: [1, 2],
1: [0, 2, 4, 5],
2: [1, 0, 6, 7],
4: [1, 5],
5: [1, 4],
6: [2],
7: [2]}
>>> print(u_graph)
{0: [1, 2],
1: [0, 2, 4, 5],
2: [1, 0, 6, 7],
4: [1, 5],
5: [1, 4],
6: [2],
7: [2]}
>>> print(repr(u_graph))
{0: [1, 2],
1: [0, 2, 4, 5],
2: [1, 0, 6, 7],
4: [1, 5],
5: [1, 4],
6: [2],
7: [2]}
>>> char_graph = GraphAdjacencyList(directed=False)
>>> char_graph.add_edge('a', 'b')
{'a': ['b'], 'b': ['a']}
>>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f')
{'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']}
>>> char_graph
{'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']}
"""
def __init__(self, directed: bool = True) -> None:
"""
Parameters:
directed: (bool) Indicates if graph is directed or undirected. Default is True.
"""
self.adj_list: dict[T, list[T]] = {} # dictionary of lists
self.directed = directed
def add_edge(
self, source_vertex: T, destination_vertex: T
) -> GraphAdjacencyList[T]:
"""
Connects vertices together. Creates and Edge from source vertex to destination
vertex.
Vertices will be created if not found in graph
"""
if not self.directed: # For undirected graphs
# if both source vertex and destination vertex are both present in the
# adjacency list, add destination vertex to source vertex list of adjacent
# vertices and add source vertex to destination vertex list of adjacent
# vertices.
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
self.adj_list[destination_vertex].append(source_vertex)
# if only source vertex is present in adjacency list, add destination vertex
# to source vertex list of adjacent vertices, then create a new vertex with
# destination vertex as key and assign a list containing the source vertex
# as it's first adjacent vertex.
elif source_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
self.adj_list[destination_vertex] = [source_vertex]
# if only destination vertex is present in adjacency list, add source vertex
# to destination vertex list of adjacent vertices, then create a new vertex
# with source vertex as key and assign a list containing the source vertex
# as it's first adjacent vertex.
elif destination_vertex in self.adj_list:
self.adj_list[destination_vertex].append(source_vertex)
self.adj_list[source_vertex] = [destination_vertex]
# if both source vertex and destination vertex are not present in adjacency
# list, create a new vertex with source vertex as key and assign a list
# containing the destination vertex as it's first adjacent vertex also
# create a new vertex with destination vertex as key and assign a list
# containing the source vertex as it's first adjacent vertex.
else:
self.adj_list[source_vertex] = [destination_vertex]
self.adj_list[destination_vertex] = [source_vertex]
else: # For directed graphs
# if both source vertex and destination vertex are present in adjacency
# list, add destination vertex to source vertex list of adjacent vertices.
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
# if only source vertex is present in adjacency list, add destination
# vertex to source vertex list of adjacent vertices and create a new vertex
# with destination vertex as key, which has no adjacent vertex
elif source_vertex in self.adj_list:
self.adj_list[source_vertex].append(destination_vertex)
self.adj_list[destination_vertex] = []
# if only destination vertex is present in adjacency list, create a new
# vertex with source vertex as key and assign a list containing destination
# vertex as first adjacent vertex
elif destination_vertex in self.adj_list:
self.adj_list[source_vertex] = [destination_vertex]
# if both source vertex and destination vertex are not present in adjacency
# list, create a new vertex with source vertex as key and a list containing
# destination vertex as it's first adjacent vertex. Then create a new vertex
# with destination vertex as key, which has no adjacent vertex
else:
self.adj_list[source_vertex] = [destination_vertex]
self.adj_list[destination_vertex] = []
return self
def __repr__(self) -> str:
return pformat(self.adj_list)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Author : Alexander Pantyukhin
Date : November 24, 2022
Task:
Given an m x n grid of characters board and a string word,
return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells,
where adjacent cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
Example:
Matrix:
---------
|A|B|C|E|
|S|F|C|S|
|A|D|E|E|
---------
Word:
"ABCCED"
Result:
True
Implementation notes: Use backtracking approach.
At each point, check all neighbors to try to find the next letter of the word.
leetcode: https://leetcode.com/problems/word-search/
"""
def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int:
"""
Returns the hash key of matrix indexes.
>>> get_point_key(10, 20, 1, 0)
200
"""
return len_board * len_board_column * row + column
def exits_word(
board: list[list[str]],
word: str,
row: int,
column: int,
word_index: int,
visited_points_set: set[int],
) -> bool:
"""
Return True if it's possible to search the word suffix
starting from the word_index.
>>> exits_word([["A"]], "B", 0, 0, 0, set())
False
"""
if board[row][column] != word[word_index]:
return False
if word_index == len(word) - 1:
return True
traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
len_board = len(board)
len_board_column = len(board[0])
for direction in traverts_directions:
next_i = row + direction[0]
next_j = column + direction[1]
if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
continue
key = get_point_key(len_board, len_board_column, next_i, next_j)
if key in visited_points_set:
continue
visited_points_set.add(key)
if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set):
return True
visited_points_set.remove(key)
return False
def word_exists(board: list[list[str]], word: str) -> bool:
"""
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED")
True
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE")
True
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB")
False
>>> word_exists([["A"]], "A")
True
>>> word_exists([["A","A","A","A","A","A"],
... ["A","A","A","A","A","A"],
... ["A","A","A","A","A","A"],
... ["A","A","A","A","A","A"],
... ["A","A","A","A","A","B"],
... ["A","A","A","A","B","A"]],
... "AAAAAAAAAAAAABB")
False
>>> word_exists([["A"]], 123)
Traceback (most recent call last):
...
ValueError: The word parameter should be a string of length greater than 0.
>>> word_exists([["A"]], "")
Traceback (most recent call last):
...
ValueError: The word parameter should be a string of length greater than 0.
>>> word_exists([[]], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
>>> word_exists([], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
>>> word_exists([["A"], [21]], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
"""
# Validate board
board_error_message = (
"The board should be a non empty matrix of single chars strings."
)
len_board = len(board)
if not isinstance(board, list) or len(board) == 0:
raise ValueError(board_error_message)
for row in board:
if not isinstance(row, list) or len(row) == 0:
raise ValueError(board_error_message)
for item in row:
if not isinstance(item, str) or len(item) != 1:
raise ValueError(board_error_message)
# Validate word
if not isinstance(word, str) or len(word) == 0:
raise ValueError(
"The word parameter should be a string of length greater than 0."
)
len_board_column = len(board[0])
for i in range(len_board):
for j in range(len_board_column):
if exits_word(
board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)}
):
return True
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Author : Alexander Pantyukhin
Date : November 24, 2022
Task:
Given an m x n grid of characters board and a string word,
return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells,
where adjacent cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
Example:
Matrix:
---------
|A|B|C|E|
|S|F|C|S|
|A|D|E|E|
---------
Word:
"ABCCED"
Result:
True
Implementation notes: Use backtracking approach.
At each point, check all neighbors to try to find the next letter of the word.
leetcode: https://leetcode.com/problems/word-search/
"""
def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int:
"""
Returns the hash key of matrix indexes.
>>> get_point_key(10, 20, 1, 0)
200
"""
return len_board * len_board_column * row + column
def exits_word(
board: list[list[str]],
word: str,
row: int,
column: int,
word_index: int,
visited_points_set: set[int],
) -> bool:
"""
Return True if it's possible to search the word suffix
starting from the word_index.
>>> exits_word([["A"]], "B", 0, 0, 0, set())
False
"""
if board[row][column] != word[word_index]:
return False
if word_index == len(word) - 1:
return True
traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
len_board = len(board)
len_board_column = len(board[0])
for direction in traverts_directions:
next_i = row + direction[0]
next_j = column + direction[1]
if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
continue
key = get_point_key(len_board, len_board_column, next_i, next_j)
if key in visited_points_set:
continue
visited_points_set.add(key)
if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set):
return True
visited_points_set.remove(key)
return False
def word_exists(board: list[list[str]], word: str) -> bool:
"""
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED")
True
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE")
True
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB")
False
>>> word_exists([["A"]], "A")
True
>>> word_exists([["A","A","A","A","A","A"],
... ["A","A","A","A","A","A"],
... ["A","A","A","A","A","A"],
... ["A","A","A","A","A","A"],
... ["A","A","A","A","A","B"],
... ["A","A","A","A","B","A"]],
... "AAAAAAAAAAAAABB")
False
>>> word_exists([["A"]], 123)
Traceback (most recent call last):
...
ValueError: The word parameter should be a string of length greater than 0.
>>> word_exists([["A"]], "")
Traceback (most recent call last):
...
ValueError: The word parameter should be a string of length greater than 0.
>>> word_exists([[]], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
>>> word_exists([], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
>>> word_exists([["A"], [21]], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
"""
# Validate board
board_error_message = (
"The board should be a non empty matrix of single chars strings."
)
len_board = len(board)
if not isinstance(board, list) or len(board) == 0:
raise ValueError(board_error_message)
for row in board:
if not isinstance(row, list) or len(row) == 0:
raise ValueError(board_error_message)
for item in row:
if not isinstance(item, str) or len(item) != 1:
raise ValueError(board_error_message)
# Validate word
if not isinstance(word, str) or len(word) == 0:
raise ValueError(
"The word parameter should be a string of length greater than 0."
)
len_board_column = len(board[0])
for i in range(len_board):
for j in range(len_board_column):
if exits_word(
board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)}
):
return True
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Each character on a computer is assigned a unique code and the preferred standard is
ASCII (American Standard Code for Information Interchange).
For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then
XOR each byte with a given value, taken from a secret key. The advantage with the
XOR function is that using the same encryption key on the cipher text, restores
the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and
the key is made up of random bytes. The user would keep the encrypted message and the
encryption key in different locations, and without both "halves", it is impossible to
decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is
to use a password as a key. If the password is shorter than the message, which is
likely, the key is repeated cyclically throughout the message. The balance for this
method is using a sufficiently long password key for security, but short enough to
be memorable.
Your task has been made easy, as the encryption key consists of three lower case
characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a
file containing the encrypted ASCII codes, and the knowledge that the plain text
must contain common English words, decrypt the message and find the sum of the ASCII
values in the original text.
"""
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
VALID_CHARS: str = (
string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase]
VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS}
COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None:
"""
Given an encrypted message and a possible 3-character key, decrypt the message.
If the decrypted message contains a invalid character, i.e. not an ASCII letter,
a digit, punctuation or whitespace, then we know the key is incorrect, so return
None.
>>> try_key([0, 17, 20, 4, 27], (104, 116, 120))
'hello'
>>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None
True
"""
decoded: str = ""
keychar: int
cipherchar: int
decodedchar: int
for keychar, cipherchar in zip(cycle(key), ciphertext):
decodedchar = cipherchar ^ keychar
if decodedchar not in VALID_INTS:
return None
decoded += chr(decodedchar)
return decoded
def filter_valid_chars(ciphertext: list[int]) -> list[str]:
"""
Given an encrypted message, test all 3-character strings to try and find the
key. Return a list of the possible decrypted messages.
>>> from itertools import cycle
>>> text = "The enemy's gate is down"
>>> key = "end"
>>> encoded = [ord(k) ^ ord(c) for k,c in zip(cycle(key), text)]
>>> text in filter_valid_chars(encoded)
True
"""
possibles: list[str] = []
for key in product(LOWERCASE_INTS, repeat=3):
encoded = try_key(ciphertext, key)
if encoded is not None:
possibles.append(encoded)
return possibles
def filter_common_word(possibles: list[str], common_word: str) -> list[str]:
"""
Given a list of possible decoded messages, narrow down the possibilities
for checking for the presence of a specified common word. Only decoded messages
containing common_word will be returned.
>>> filter_common_word(['asfla adf', 'I am here', ' !?! #a'], 'am')
['I am here']
>>> filter_common_word(['athla amf', 'I am here', ' !?! #a'], 'am')
['athla amf', 'I am here']
"""
return [possible for possible in possibles if common_word in possible.lower()]
def solution(filename: str = "p059_cipher.txt") -> int:
"""
Test the ciphertext against all possible 3-character keys, then narrow down the
possibilities by filtering using common words until there's only one possible
decoded message.
>>> solution("test_cipher.txt")
3000
"""
ciphertext: list[int]
possibles: list[str]
common_word: str
decoded_text: str
data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
ciphertext = [int(number) for number in data.strip().split(",")]
possibles = filter_valid_chars(ciphertext)
for common_word in COMMON_WORDS:
possibles = filter_common_word(possibles, common_word)
if len(possibles) == 1:
break
decoded_text = possibles[0]
return sum(ord(char) for char in decoded_text)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Each character on a computer is assigned a unique code and the preferred standard is
ASCII (American Standard Code for Information Interchange).
For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then
XOR each byte with a given value, taken from a secret key. The advantage with the
XOR function is that using the same encryption key on the cipher text, restores
the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and
the key is made up of random bytes. The user would keep the encrypted message and the
encryption key in different locations, and without both "halves", it is impossible to
decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is
to use a password as a key. If the password is shorter than the message, which is
likely, the key is repeated cyclically throughout the message. The balance for this
method is using a sufficiently long password key for security, but short enough to
be memorable.
Your task has been made easy, as the encryption key consists of three lower case
characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a
file containing the encrypted ASCII codes, and the knowledge that the plain text
must contain common English words, decrypt the message and find the sum of the ASCII
values in the original text.
"""
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
VALID_CHARS: str = (
string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase]
VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS}
COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None:
"""
Given an encrypted message and a possible 3-character key, decrypt the message.
If the decrypted message contains a invalid character, i.e. not an ASCII letter,
a digit, punctuation or whitespace, then we know the key is incorrect, so return
None.
>>> try_key([0, 17, 20, 4, 27], (104, 116, 120))
'hello'
>>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None
True
"""
decoded: str = ""
keychar: int
cipherchar: int
decodedchar: int
for keychar, cipherchar in zip(cycle(key), ciphertext):
decodedchar = cipherchar ^ keychar
if decodedchar not in VALID_INTS:
return None
decoded += chr(decodedchar)
return decoded
def filter_valid_chars(ciphertext: list[int]) -> list[str]:
"""
Given an encrypted message, test all 3-character strings to try and find the
key. Return a list of the possible decrypted messages.
>>> from itertools import cycle
>>> text = "The enemy's gate is down"
>>> key = "end"
>>> encoded = [ord(k) ^ ord(c) for k,c in zip(cycle(key), text)]
>>> text in filter_valid_chars(encoded)
True
"""
possibles: list[str] = []
for key in product(LOWERCASE_INTS, repeat=3):
encoded = try_key(ciphertext, key)
if encoded is not None:
possibles.append(encoded)
return possibles
def filter_common_word(possibles: list[str], common_word: str) -> list[str]:
"""
Given a list of possible decoded messages, narrow down the possibilities
for checking for the presence of a specified common word. Only decoded messages
containing common_word will be returned.
>>> filter_common_word(['asfla adf', 'I am here', ' !?! #a'], 'am')
['I am here']
>>> filter_common_word(['athla amf', 'I am here', ' !?! #a'], 'am')
['athla amf', 'I am here']
"""
return [possible for possible in possibles if common_word in possible.lower()]
def solution(filename: str = "p059_cipher.txt") -> int:
"""
Test the ciphertext against all possible 3-character keys, then narrow down the
possibilities by filtering using common words until there's only one possible
decoded message.
>>> solution("test_cipher.txt")
3000
"""
ciphertext: list[int]
possibles: list[str]
common_word: str
decoded_text: str
data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
ciphertext = [int(number) for number in data.strip().split(",")]
possibles = filter_valid_chars(ciphertext)
for common_word in COMMON_WORDS:
possibles = filter_common_word(possibles, common_word)
if len(possibles) == 1:
break
decoded_text = possibles[0]
return sum(ord(char) for char in decoded_text)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| 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 | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Problem 20: https://projecteuler.net/problem=20
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
from math import factorial
def solution(num: int = 100) -> int:
"""Returns the sum of the digits in the factorial of num
>>> solution(100)
648
>>> solution(50)
216
>>> solution(10)
27
>>> solution(5)
3
>>> solution(3)
6
>>> solution(2)
2
>>> solution(1)
1
"""
return sum(int(x) for x in str(factorial(num)))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip())))
| """
Problem 20: https://projecteuler.net/problem=20
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
from math import factorial
def solution(num: int = 100) -> int:
"""Returns the sum of the digits in the factorial of num
>>> solution(100)
648
>>> solution(50)
216
>>> solution(10)
27
>>> solution(5)
3
>>> solution(3)
6
>>> solution(2)
2
>>> solution(1)
1
"""
return sum(int(x) for x in str(factorial(num)))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip())))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # Primality Testing with the Rabin-Miller Algorithm
import random
def rabin_miller(num: int) -> bool:
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for _ in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v**2) % num
return True
def is_prime_low_num(num: int) -> bool:
if num < 2:
return False
low_primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in low_primes:
return True
for prime in low_primes:
if (num % prime) == 0:
return False
return rabin_miller(num)
def generate_large_prime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime_low_num(num):
return num
if __name__ == "__main__":
num = generate_large_prime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
| # Primality Testing with the Rabin-Miller Algorithm
import random
def rabin_miller(num: int) -> bool:
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for _ in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v**2) % num
return True
def is_prime_low_num(num: int) -> bool:
if num < 2:
return False
low_primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in low_primes:
return True
for prime in low_primes:
if (num % prime) == 0:
return False
return rabin_miller(num)
def generate_large_prime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime_low_num(num):
return num
if __name__ == "__main__":
num = generate_large_prime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Author : Alexander Pantyukhin
Date : November 1, 2022
Task:
Given a positive int number. Return True if this number is power of 2
or False otherwise.
Implementation notes: Use bit manipulation.
For example if the number is the power of two it's bits representation:
n = 0..100..00
n - 1 = 0..011..11
n & (n - 1) - no intersections = 0
"""
def is_power_of_two(number: int) -> bool:
"""
Return True if this number is power of 2 or False otherwise.
>>> is_power_of_two(0)
True
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(4)
True
>>> is_power_of_two(6)
False
>>> is_power_of_two(8)
True
>>> is_power_of_two(17)
False
>>> is_power_of_two(-1)
Traceback (most recent call last):
...
ValueError: number must not be negative
>>> is_power_of_two(1.2)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for &: 'float' and 'float'
# Test all powers of 2 from 0 to 10,000
>>> all(is_power_of_two(int(2 ** i)) for i in range(10000))
True
"""
if number < 0:
raise ValueError("number must not be negative")
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Author : Alexander Pantyukhin
Date : November 1, 2022
Task:
Given a positive int number. Return True if this number is power of 2
or False otherwise.
Implementation notes: Use bit manipulation.
For example if the number is the power of two it's bits representation:
n = 0..100..00
n - 1 = 0..011..11
n & (n - 1) - no intersections = 0
"""
def is_power_of_two(number: int) -> bool:
"""
Return True if this number is power of 2 or False otherwise.
>>> is_power_of_two(0)
True
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(4)
True
>>> is_power_of_two(6)
False
>>> is_power_of_two(8)
True
>>> is_power_of_two(17)
False
>>> is_power_of_two(-1)
Traceback (most recent call last):
...
ValueError: number must not be negative
>>> is_power_of_two(1.2)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for &: 'float' and 'float'
# Test all powers of 2 from 0 to 10,000
>>> all(is_power_of_two(int(2 ** i)) for i in range(10000))
True
"""
if number < 0:
raise ValueError("number must not be negative")
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from binascii import hexlify
from hashlib import sha256
from os import urandom
# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
primes = {
# 1536-bit
5: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 2048-bit
14: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AACAA68FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 3072-bit
15: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 4096-bit
16: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
"FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 6144-bit
17: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
"6DCC4024FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 8192-bit
18: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD"
"F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831"
"179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
"DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF"
"5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6"
"D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3"
"23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328"
"06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C"
"DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE"
"12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4"
"38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300"
"741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568"
"3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
"22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B"
"4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A"
"062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36"
"4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1"
"B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92"
"4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47"
"9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
"60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
}
class DiffieHellman:
"""
Class to represent the Diffie-Hellman key exchange protocol
>>> alice = DiffieHellman()
>>> bob = DiffieHellman()
>>> alice_private = alice.get_private_key()
>>> alice_public = alice.generate_public_key()
>>> bob_private = bob.get_private_key()
>>> bob_public = bob.generate_public_key()
>>> # generating shared key using the DH object
>>> alice_shared = alice.generate_shared_key(bob_public)
>>> bob_shared = bob.generate_shared_key(alice_public)
>>> assert alice_shared == bob_shared
>>> # generating shared key using static methods
>>> alice_shared = DiffieHellman.generate_shared_key_static(
... alice_private, bob_public
... )
>>> bob_shared = DiffieHellman.generate_shared_key_static(
... bob_private, alice_public
... )
>>> assert alice_shared == bob_shared
"""
# Current minimum recommendation is 2048 bit (group 14)
def __init__(self, group: int = 14) -> None:
if group not in primes:
raise ValueError("Unsupported Group")
self.prime = primes[group]["prime"]
self.generator = primes[group]["generator"]
self.__private_key = int(hexlify(urandom(32)), base=16)
def get_private_key(self) -> str:
return hex(self.__private_key)[2:]
def generate_public_key(self) -> str:
public_key = pow(self.generator, self.__private_key, self.prime)
return hex(public_key)[2:]
def is_valid_public_key(self, key: int) -> bool:
# check if the other public key is valid based on NIST SP800-56
return (
2 <= key <= self.prime - 2
and pow(key, (self.prime - 1) // 2, self.prime) == 1
)
def generate_shared_key(self, other_key_str: str) -> str:
other_key = int(other_key_str, base=16)
if not self.is_valid_public_key(other_key):
raise ValueError("Invalid public key")
shared_key = pow(other_key, self.__private_key, self.prime)
return sha256(str(shared_key).encode()).hexdigest()
@staticmethod
def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool:
# check if the other public key is valid based on NIST SP800-56
return (
2 <= remote_public_key_str <= prime - 2
and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1
)
@staticmethod
def generate_shared_key_static(
local_private_key_str: str, remote_public_key_str: str, group: int = 14
) -> str:
local_private_key = int(local_private_key_str, base=16)
remote_public_key = int(remote_public_key_str, base=16)
prime = primes[group]["prime"]
if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime):
raise ValueError("Invalid public key")
shared_key = pow(remote_public_key, local_private_key, prime)
return sha256(str(shared_key).encode()).hexdigest()
if __name__ == "__main__":
import doctest
doctest.testmod()
| from binascii import hexlify
from hashlib import sha256
from os import urandom
# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
primes = {
# 1536-bit
5: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 2048-bit
14: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AACAA68FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 3072-bit
15: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 4096-bit
16: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
"FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 6144-bit
17: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
"6DCC4024FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 8192-bit
18: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD"
"F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831"
"179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
"DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF"
"5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6"
"D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3"
"23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328"
"06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C"
"DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE"
"12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4"
"38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300"
"741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568"
"3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
"22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B"
"4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A"
"062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36"
"4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1"
"B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92"
"4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47"
"9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
"60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
}
class DiffieHellman:
"""
Class to represent the Diffie-Hellman key exchange protocol
>>> alice = DiffieHellman()
>>> bob = DiffieHellman()
>>> alice_private = alice.get_private_key()
>>> alice_public = alice.generate_public_key()
>>> bob_private = bob.get_private_key()
>>> bob_public = bob.generate_public_key()
>>> # generating shared key using the DH object
>>> alice_shared = alice.generate_shared_key(bob_public)
>>> bob_shared = bob.generate_shared_key(alice_public)
>>> assert alice_shared == bob_shared
>>> # generating shared key using static methods
>>> alice_shared = DiffieHellman.generate_shared_key_static(
... alice_private, bob_public
... )
>>> bob_shared = DiffieHellman.generate_shared_key_static(
... bob_private, alice_public
... )
>>> assert alice_shared == bob_shared
"""
# Current minimum recommendation is 2048 bit (group 14)
def __init__(self, group: int = 14) -> None:
if group not in primes:
raise ValueError("Unsupported Group")
self.prime = primes[group]["prime"]
self.generator = primes[group]["generator"]
self.__private_key = int(hexlify(urandom(32)), base=16)
def get_private_key(self) -> str:
return hex(self.__private_key)[2:]
def generate_public_key(self) -> str:
public_key = pow(self.generator, self.__private_key, self.prime)
return hex(public_key)[2:]
def is_valid_public_key(self, key: int) -> bool:
# check if the other public key is valid based on NIST SP800-56
return (
2 <= key <= self.prime - 2
and pow(key, (self.prime - 1) // 2, self.prime) == 1
)
def generate_shared_key(self, other_key_str: str) -> str:
other_key = int(other_key_str, base=16)
if not self.is_valid_public_key(other_key):
raise ValueError("Invalid public key")
shared_key = pow(other_key, self.__private_key, self.prime)
return sha256(str(shared_key).encode()).hexdigest()
@staticmethod
def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool:
# check if the other public key is valid based on NIST SP800-56
return (
2 <= remote_public_key_str <= prime - 2
and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1
)
@staticmethod
def generate_shared_key_static(
local_private_key_str: str, remote_public_key_str: str, group: int = 14
) -> str:
local_private_key = int(local_private_key_str, base=16)
remote_public_key = int(remote_public_key_str, base=16)
prime = primes[group]["prime"]
if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime):
raise ValueError("Invalid public key")
shared_key = pow(remote_public_key, local_private_key, prime)
return sha256(str(shared_key).encode()).hexdigest()
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
* Author: Manuel Di Lullo (https://github.com/manueldilullo)
* Description: Approximization algorithm for minimum vertex cover problem.
Greedy Approach. Uses graphs represented with an adjacency list
URL: https://mathworld.wolfram.com/MinimumVertexCover.html
URL: https://cs.stackexchange.com/questions/129017/greedy-algorithm-for-vertex-cover
"""
import heapq
def greedy_min_vertex_cover(graph: dict) -> set[int]:
"""
Greedy APX Algorithm for min Vertex Cover
@input: graph (graph stored in an adjacency list where each vertex
is represented with an integer)
@example:
>>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
>>> greedy_min_vertex_cover(graph)
{0, 1, 2, 4}
"""
# queue used to store nodes and their rank
queue: list[list] = []
# for each node and his adjacency list add them and the rank of the node to queue
# using heapq module the queue will be filled like a Priority Queue
# heapq works with a min priority queue, so I used -1*len(v) to build it
for key, value in graph.items():
# O(log(n))
heapq.heappush(queue, [-1 * len(value), (key, value)])
# chosen_vertices = set of chosen vertices
chosen_vertices = set()
# while queue isn't empty and there are still edges
# (queue[0][0] is the rank of the node with max rank)
while queue and queue[0][0] != 0:
# extract vertex with max rank from queue and add it to chosen_vertices
argmax = heapq.heappop(queue)[1][0]
chosen_vertices.add(argmax)
# Remove all arcs adjacent to argmax
for elem in queue:
# if v haven't adjacent node, skip
if elem[0] == 0:
continue
# if argmax is reachable from elem
# remove argmax from elem's adjacent list and update his rank
if argmax in elem[1][1]:
index = elem[1][1].index(argmax)
del elem[1][1][index]
elem[0] += 1
# re-order the queue
heapq.heapify(queue)
return chosen_vertices
if __name__ == "__main__":
import doctest
doctest.testmod()
graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
print(f"Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}")
| """
* Author: Manuel Di Lullo (https://github.com/manueldilullo)
* Description: Approximization algorithm for minimum vertex cover problem.
Greedy Approach. Uses graphs represented with an adjacency list
URL: https://mathworld.wolfram.com/MinimumVertexCover.html
URL: https://cs.stackexchange.com/questions/129017/greedy-algorithm-for-vertex-cover
"""
import heapq
def greedy_min_vertex_cover(graph: dict) -> set[int]:
"""
Greedy APX Algorithm for min Vertex Cover
@input: graph (graph stored in an adjacency list where each vertex
is represented with an integer)
@example:
>>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
>>> greedy_min_vertex_cover(graph)
{0, 1, 2, 4}
"""
# queue used to store nodes and their rank
queue: list[list] = []
# for each node and his adjacency list add them and the rank of the node to queue
# using heapq module the queue will be filled like a Priority Queue
# heapq works with a min priority queue, so I used -1*len(v) to build it
for key, value in graph.items():
# O(log(n))
heapq.heappush(queue, [-1 * len(value), (key, value)])
# chosen_vertices = set of chosen vertices
chosen_vertices = set()
# while queue isn't empty and there are still edges
# (queue[0][0] is the rank of the node with max rank)
while queue and queue[0][0] != 0:
# extract vertex with max rank from queue and add it to chosen_vertices
argmax = heapq.heappop(queue)[1][0]
chosen_vertices.add(argmax)
# Remove all arcs adjacent to argmax
for elem in queue:
# if v haven't adjacent node, skip
if elem[0] == 0:
continue
# if argmax is reachable from elem
# remove argmax from elem's adjacent list and update his rank
if argmax in elem[1][1]:
index = elem[1][1].index(argmax)
del elem[1][1][index]
elem[0] += 1
# re-order the queue
heapq.heapify(queue)
return chosen_vertices
if __name__ == "__main__":
import doctest
doctest.testmod()
graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
print(f"Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| def is_palindrome(head):
if not head:
return True
# split the list to two parts
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
second = slow.next
slow.next = None # Don't forget here! But forget still works!
# reverse the second part
node = None
while second:
nxt = second.next
second.next = node
node = second
second = nxt
# compare two parts
# second part has the same or one less node
while node:
if node.val != head.val:
return False
node = node.next
head = head.next
return True
def is_palindrome_stack(head):
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
return True
def is_palindrome_dict(head):
if not head or not head.next:
return True
d = {}
pos = 0
while head:
if head.val in d:
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
step = 0
for i in range(0, len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True
| def is_palindrome(head):
if not head:
return True
# split the list to two parts
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
second = slow.next
slow.next = None # Don't forget here! But forget still works!
# reverse the second part
node = None
while second:
nxt = second.next
second.next = node
node = second
second = nxt
# compare two parts
# second part has the same or one less node
while node:
if node.val != head.val:
return False
node = node.next
head = head.next
return True
def is_palindrome_stack(head):
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
return True
def is_palindrome_dict(head):
if not head or not head.next:
return True
d = {}
pos = 0
while head:
if head.val in d:
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
step = 0
for i in range(0, len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """Created by Nathan Damon, @bizzfitch on github
>>> test_miller_rabin()
"""
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
Uses numerical analysis results to return whether or not the passed number
is prime. If the passed number is above the upper limit, and
allow_probable is True, then a return value of True indicates that n is
probably prime. This test does not allow False negatives- a return value
of False is ALWAYS composite.
Parameters
----------
n : int
The integer to be tested. Since we usually care if a number is prime,
n < 2 returns False instead of raising a ValueError.
allow_probable: bool, default False
Whether or not to test n above the upper bound of the deterministic test.
Raises
------
ValueError
Reference
---------
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if n == 2:
return True
if not n % 2 or n < 2:
return False
if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit
return False
if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
raise ValueError(
"Warning: upper bound of deterministic test is exceeded. "
"Pass allow_probable=True to allow probabilistic test. "
"A return value of True indicates a probable prime."
)
# array bounds provided by analysis
bounds = [
2_047,
1_373_653,
25_326_001,
3_215_031_751,
2_152_302_898_747,
3_474_749_660_383,
341_550_071_728_321,
1,
3_825_123_056_546_413_051,
1,
1,
318_665_857_834_031_151_167_461,
3_317_044_064_679_887_385_961_981,
]
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
for idx, _p in enumerate(bounds, 1):
if n < _p:
# then we have our last prime to check
plist = primes[:idx]
break
d, s = n - 1, 0
# break up n -1 into a power of 2 (s) and
# remaining odd component
# essentially, solve for d * 2 ** s == n - 1
while d % 2 == 0:
d //= 2
s += 1
for prime in plist:
pr = False
for r in range(s):
m = pow(prime, d * 2**r, n)
# see article for analysis explanation for m
if (r == 0 and m == 1) or ((m + 1) % n == 0):
pr = True
# this loop will not determine compositeness
break
if pr:
continue
# if pr is False, then the above loop never evaluated to true,
# and the n MUST be composite
return False
return True
def test_miller_rabin() -> None:
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
and a prime in each range.
"""
assert not miller_rabin(561)
assert miller_rabin(563)
# 2047
assert not miller_rabin(838_201)
assert miller_rabin(838_207)
# 1_373_653
assert not miller_rabin(17_316_001)
assert miller_rabin(17_316_017)
# 25_326_001
assert not miller_rabin(3_078_386_641)
assert miller_rabin(3_078_386_653)
# 3_215_031_751
assert not miller_rabin(1_713_045_574_801)
assert miller_rabin(1_713_045_574_819)
# 2_152_302_898_747
assert not miller_rabin(2_779_799_728_307)
assert miller_rabin(2_779_799_728_327)
# 3_474_749_660_383
assert not miller_rabin(113_850_023_909_441)
assert miller_rabin(113_850_023_909_527)
# 341_550_071_728_321
assert not miller_rabin(1_275_041_018_848_804_351)
assert miller_rabin(1_275_041_018_848_804_391)
# 3_825_123_056_546_413_051
assert not miller_rabin(79_666_464_458_507_787_791_867)
assert miller_rabin(79_666_464_458_507_787_791_951)
# 318_665_857_834_031_151_167_461
assert not miller_rabin(552_840_677_446_647_897_660_333)
assert miller_rabin(552_840_677_446_647_897_660_359)
# 3_317_044_064_679_887_385_961_981
# upper limit for probabilistic test
if __name__ == "__main__":
test_miller_rabin()
| """Created by Nathan Damon, @bizzfitch on github
>>> test_miller_rabin()
"""
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
Uses numerical analysis results to return whether or not the passed number
is prime. If the passed number is above the upper limit, and
allow_probable is True, then a return value of True indicates that n is
probably prime. This test does not allow False negatives- a return value
of False is ALWAYS composite.
Parameters
----------
n : int
The integer to be tested. Since we usually care if a number is prime,
n < 2 returns False instead of raising a ValueError.
allow_probable: bool, default False
Whether or not to test n above the upper bound of the deterministic test.
Raises
------
ValueError
Reference
---------
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if n == 2:
return True
if not n % 2 or n < 2:
return False
if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit
return False
if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
raise ValueError(
"Warning: upper bound of deterministic test is exceeded. "
"Pass allow_probable=True to allow probabilistic test. "
"A return value of True indicates a probable prime."
)
# array bounds provided by analysis
bounds = [
2_047,
1_373_653,
25_326_001,
3_215_031_751,
2_152_302_898_747,
3_474_749_660_383,
341_550_071_728_321,
1,
3_825_123_056_546_413_051,
1,
1,
318_665_857_834_031_151_167_461,
3_317_044_064_679_887_385_961_981,
]
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
for idx, _p in enumerate(bounds, 1):
if n < _p:
# then we have our last prime to check
plist = primes[:idx]
break
d, s = n - 1, 0
# break up n -1 into a power of 2 (s) and
# remaining odd component
# essentially, solve for d * 2 ** s == n - 1
while d % 2 == 0:
d //= 2
s += 1
for prime in plist:
pr = False
for r in range(s):
m = pow(prime, d * 2**r, n)
# see article for analysis explanation for m
if (r == 0 and m == 1) or ((m + 1) % n == 0):
pr = True
# this loop will not determine compositeness
break
if pr:
continue
# if pr is False, then the above loop never evaluated to true,
# and the n MUST be composite
return False
return True
def test_miller_rabin() -> None:
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
and a prime in each range.
"""
assert not miller_rabin(561)
assert miller_rabin(563)
# 2047
assert not miller_rabin(838_201)
assert miller_rabin(838_207)
# 1_373_653
assert not miller_rabin(17_316_001)
assert miller_rabin(17_316_017)
# 25_326_001
assert not miller_rabin(3_078_386_641)
assert miller_rabin(3_078_386_653)
# 3_215_031_751
assert not miller_rabin(1_713_045_574_801)
assert miller_rabin(1_713_045_574_819)
# 2_152_302_898_747
assert not miller_rabin(2_779_799_728_307)
assert miller_rabin(2_779_799_728_327)
# 3_474_749_660_383
assert not miller_rabin(113_850_023_909_441)
assert miller_rabin(113_850_023_909_527)
# 341_550_071_728_321
assert not miller_rabin(1_275_041_018_848_804_351)
assert miller_rabin(1_275_041_018_848_804_391)
# 3_825_123_056_546_413_051
assert not miller_rabin(79_666_464_458_507_787_791_867)
assert miller_rabin(79_666_464_458_507_787_791_951)
# 318_665_857_834_031_151_167_461
assert not miller_rabin(552_840_677_446_647_897_660_333)
assert miller_rabin(552_840_677_446_647_897_660_359)
# 3_317_044_064_679_887_385_961_981
# upper limit for probabilistic test
if __name__ == "__main__":
test_miller_rabin()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from __future__ import annotations
from typing import Generic, TypeVar
T = TypeVar("T")
class StackOverflowError(BaseException):
pass
class StackUnderflowError(BaseException):
pass
class Stack(Generic[T]):
"""A stack is an abstract data type that serves as a collection of
elements with two principal operations: push() and pop(). push() adds an
element to the top of the stack, and pop() removes an element from the top
of a stack. The order in which elements come off of a stack are
Last In, First Out (LIFO).
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
"""
def __init__(self, limit: int = 10):
self.stack: list[T] = []
self.limit = limit
def __bool__(self) -> bool:
return bool(self.stack)
def __str__(self) -> str:
return str(self.stack)
def push(self, data: T) -> None:
"""Push an element to the top of the stack."""
if len(self.stack) >= self.limit:
raise StackOverflowError
self.stack.append(data)
def pop(self) -> T:
"""
Pop an element off of the top of the stack.
>>> Stack().pop()
Traceback (most recent call last):
...
data_structures.stacks.stack.StackUnderflowError
"""
if not self.stack:
raise StackUnderflowError
return self.stack.pop()
def peek(self) -> T:
"""
Peek at the top-most element of the stack.
>>> Stack().pop()
Traceback (most recent call last):
...
data_structures.stacks.stack.StackUnderflowError
"""
if not self.stack:
raise StackUnderflowError
return self.stack[-1]
def is_empty(self) -> bool:
"""Check if a stack is empty."""
return not bool(self.stack)
def is_full(self) -> bool:
return self.size() == self.limit
def size(self) -> int:
"""Return the size of the stack."""
return len(self.stack)
def __contains__(self, item: T) -> bool:
"""Check if item is in stack"""
return item in self.stack
def test_stack() -> None:
"""
>>> test_stack()
"""
stack: Stack[int] = Stack(10)
assert bool(stack) is False
assert stack.is_empty() is True
assert stack.is_full() is False
assert str(stack) == "[]"
try:
_ = stack.pop()
raise AssertionError # This should not happen
except StackUnderflowError:
assert True # This should happen
try:
_ = stack.peek()
raise AssertionError # This should not happen
except StackUnderflowError:
assert True # This should happen
for i in range(10):
assert stack.size() == i
stack.push(i)
assert bool(stack)
assert not stack.is_empty()
assert stack.is_full()
assert str(stack) == str(list(range(10)))
assert stack.pop() == 9
assert stack.peek() == 8
stack.push(100)
assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])
try:
stack.push(200)
raise AssertionError # This should not happen
except StackOverflowError:
assert True # This should happen
assert not stack.is_empty()
assert stack.size() == 10
assert 5 in stack
assert 55 not in stack
if __name__ == "__main__":
test_stack()
| from __future__ import annotations
from typing import Generic, TypeVar
T = TypeVar("T")
class StackOverflowError(BaseException):
pass
class StackUnderflowError(BaseException):
pass
class Stack(Generic[T]):
"""A stack is an abstract data type that serves as a collection of
elements with two principal operations: push() and pop(). push() adds an
element to the top of the stack, and pop() removes an element from the top
of a stack. The order in which elements come off of a stack are
Last In, First Out (LIFO).
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
"""
def __init__(self, limit: int = 10):
self.stack: list[T] = []
self.limit = limit
def __bool__(self) -> bool:
return bool(self.stack)
def __str__(self) -> str:
return str(self.stack)
def push(self, data: T) -> None:
"""Push an element to the top of the stack."""
if len(self.stack) >= self.limit:
raise StackOverflowError
self.stack.append(data)
def pop(self) -> T:
"""
Pop an element off of the top of the stack.
>>> Stack().pop()
Traceback (most recent call last):
...
data_structures.stacks.stack.StackUnderflowError
"""
if not self.stack:
raise StackUnderflowError
return self.stack.pop()
def peek(self) -> T:
"""
Peek at the top-most element of the stack.
>>> Stack().pop()
Traceback (most recent call last):
...
data_structures.stacks.stack.StackUnderflowError
"""
if not self.stack:
raise StackUnderflowError
return self.stack[-1]
def is_empty(self) -> bool:
"""Check if a stack is empty."""
return not bool(self.stack)
def is_full(self) -> bool:
return self.size() == self.limit
def size(self) -> int:
"""Return the size of the stack."""
return len(self.stack)
def __contains__(self, item: T) -> bool:
"""Check if item is in stack"""
return item in self.stack
def test_stack() -> None:
"""
>>> test_stack()
"""
stack: Stack[int] = Stack(10)
assert bool(stack) is False
assert stack.is_empty() is True
assert stack.is_full() is False
assert str(stack) == "[]"
try:
_ = stack.pop()
raise AssertionError # This should not happen
except StackUnderflowError:
assert True # This should happen
try:
_ = stack.peek()
raise AssertionError # This should not happen
except StackUnderflowError:
assert True # This should happen
for i in range(10):
assert stack.size() == i
stack.push(i)
assert bool(stack)
assert not stack.is_empty()
assert stack.is_full()
assert str(stack) == str(list(range(10)))
assert stack.pop() == 9
assert stack.peek() == 8
stack.push(100)
assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])
try:
stack.push(200)
raise AssertionError # This should not happen
except StackOverflowError:
assert True # This should happen
assert not stack.is_empty()
assert stack.size() == 10
assert 5 in stack
assert 55 not in stack
if __name__ == "__main__":
test_stack()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
This is a pure Python implementation of the heap sort algorithm.
For doctests run following command:
python -m doctest -v heap_sort.py
or
python3 -m doctest -v heap_sort.py
For manual testing run:
python heap_sort.py
"""
def heapify(unsorted, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
heapify(unsorted, largest, heap_size)
def heap_sort(unsorted):
"""
Pure implementation of the heap sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> heap_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> heap_sort([])
[]
>>> heap_sort([-2, -5, -45])
[-45, -5, -2]
"""
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(heap_sort(unsorted))
| """
This is a pure Python implementation of the heap sort algorithm.
For doctests run following command:
python -m doctest -v heap_sort.py
or
python3 -m doctest -v heap_sort.py
For manual testing run:
python heap_sort.py
"""
def heapify(unsorted, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
heapify(unsorted, largest, heap_size)
def heap_sort(unsorted):
"""
Pure implementation of the heap sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> heap_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> heap_sort([])
[]
>>> heap_sort([-2, -5, -45])
[-45, -5, -2]
"""
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(heap_sort(unsorted))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| class Graph:
"""
Data structure to store graphs (based on adjacency lists)
"""
def __init__(self):
self.num_vertices = 0
self.num_edges = 0
self.adjacency = {}
def add_vertex(self, vertex):
"""
Adds a vertex to the graph
"""
if vertex not in self.adjacency:
self.adjacency[vertex] = {}
self.num_vertices += 1
def add_edge(self, head, tail, weight):
"""
Adds an edge to the graph
"""
self.add_vertex(head)
self.add_vertex(tail)
if head == tail:
return
self.adjacency[head][tail] = weight
self.adjacency[tail][head] = weight
def distinct_weight(self):
"""
For Boruvks's algorithm the weights should be distinct
Converts the weights to be distinct
"""
edges = self.get_edges()
for edge in edges:
head, tail, weight = edge
edges.remove((tail, head, weight))
for i in range(len(edges)):
edges[i] = list(edges[i])
edges.sort(key=lambda e: e[2])
for i in range(len(edges) - 1):
if edges[i][2] >= edges[i + 1][2]:
edges[i + 1][2] = edges[i][2] + 1
for edge in edges:
head, tail, weight = edge
self.adjacency[head][tail] = weight
self.adjacency[tail][head] = weight
def __str__(self):
"""
Returns string representation of the graph
"""
string = ""
for tail in self.adjacency:
for head in self.adjacency[tail]:
weight = self.adjacency[head][tail]
string += f"{head} -> {tail} == {weight}\n"
return string.rstrip("\n")
def get_edges(self):
"""
Returna all edges in the graph
"""
output = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]))
return output
def get_vertices(self):
"""
Returns all vertices in the graph
"""
return self.adjacency.keys()
@staticmethod
def build(vertices=None, edges=None):
"""
Builds a graph from the given set of vertices and edges
"""
g = Graph()
if vertices is None:
vertices = []
if edges is None:
edge = []
for vertex in vertices:
g.add_vertex(vertex)
for edge in edges:
g.add_edge(*edge)
return g
class UnionFind:
"""
Disjoint set Union and Find for Boruvka's algorithm
"""
def __init__(self):
self.parent = {}
self.rank = {}
def __len__(self):
return len(self.parent)
def make_set(self, item):
if item in self.parent:
return self.find(item)
self.parent[item] = item
self.rank[item] = 0
return item
def find(self, item):
if item not in self.parent:
return self.make_set(item)
if item != self.parent[item]:
self.parent[item] = self.find(self.parent[item])
return self.parent[item]
def union(self, item1, item2):
root1 = self.find(item1)
root2 = self.find(item2)
if root1 == root2:
return root1
if self.rank[root1] > self.rank[root2]:
self.parent[root2] = root1
return root1
if self.rank[root1] < self.rank[root2]:
self.parent[root1] = root2
return root2
if self.rank[root1] == self.rank[root2]:
self.rank[root1] += 1
self.parent[root2] = root1
return root1
return None
@staticmethod
def boruvka_mst(graph):
"""
Implementation of Boruvka's algorithm
>>> g = Graph()
>>> g = Graph.build([0, 1, 2, 3], [[0, 1, 1], [0, 2, 1],[2, 3, 1]])
>>> g.distinct_weight()
>>> bg = Graph.boruvka_mst(g)
>>> print(bg)
1 -> 0 == 1
2 -> 0 == 2
0 -> 1 == 1
0 -> 2 == 2
3 -> 2 == 3
2 -> 3 == 3
"""
num_components = graph.num_vertices
union_find = Graph.UnionFind()
mst_edges = []
while num_components > 1:
cheap_edge = {}
for vertex in graph.get_vertices():
cheap_edge[vertex] = -1
edges = graph.get_edges()
for edge in edges:
head, tail, weight = edge
edges.remove((tail, head, weight))
for edge in edges:
head, tail, weight = edge
set1 = union_find.find(head)
set2 = union_find.find(tail)
if set1 != set2:
if cheap_edge[set1] == -1 or cheap_edge[set1][2] > weight:
cheap_edge[set1] = [head, tail, weight]
if cheap_edge[set2] == -1 or cheap_edge[set2][2] > weight:
cheap_edge[set2] = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
head, tail, weight = cheap_edge[vertex]
if union_find.find(head) != union_find.find(tail):
union_find.union(head, tail)
mst_edges.append(cheap_edge[vertex])
num_components = num_components - 1
mst = Graph.build(edges=mst_edges)
return mst
| class Graph:
"""
Data structure to store graphs (based on adjacency lists)
"""
def __init__(self):
self.num_vertices = 0
self.num_edges = 0
self.adjacency = {}
def add_vertex(self, vertex):
"""
Adds a vertex to the graph
"""
if vertex not in self.adjacency:
self.adjacency[vertex] = {}
self.num_vertices += 1
def add_edge(self, head, tail, weight):
"""
Adds an edge to the graph
"""
self.add_vertex(head)
self.add_vertex(tail)
if head == tail:
return
self.adjacency[head][tail] = weight
self.adjacency[tail][head] = weight
def distinct_weight(self):
"""
For Boruvks's algorithm the weights should be distinct
Converts the weights to be distinct
"""
edges = self.get_edges()
for edge in edges:
head, tail, weight = edge
edges.remove((tail, head, weight))
for i in range(len(edges)):
edges[i] = list(edges[i])
edges.sort(key=lambda e: e[2])
for i in range(len(edges) - 1):
if edges[i][2] >= edges[i + 1][2]:
edges[i + 1][2] = edges[i][2] + 1
for edge in edges:
head, tail, weight = edge
self.adjacency[head][tail] = weight
self.adjacency[tail][head] = weight
def __str__(self):
"""
Returns string representation of the graph
"""
string = ""
for tail in self.adjacency:
for head in self.adjacency[tail]:
weight = self.adjacency[head][tail]
string += f"{head} -> {tail} == {weight}\n"
return string.rstrip("\n")
def get_edges(self):
"""
Returna all edges in the graph
"""
output = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]))
return output
def get_vertices(self):
"""
Returns all vertices in the graph
"""
return self.adjacency.keys()
@staticmethod
def build(vertices=None, edges=None):
"""
Builds a graph from the given set of vertices and edges
"""
g = Graph()
if vertices is None:
vertices = []
if edges is None:
edge = []
for vertex in vertices:
g.add_vertex(vertex)
for edge in edges:
g.add_edge(*edge)
return g
class UnionFind:
"""
Disjoint set Union and Find for Boruvka's algorithm
"""
def __init__(self):
self.parent = {}
self.rank = {}
def __len__(self):
return len(self.parent)
def make_set(self, item):
if item in self.parent:
return self.find(item)
self.parent[item] = item
self.rank[item] = 0
return item
def find(self, item):
if item not in self.parent:
return self.make_set(item)
if item != self.parent[item]:
self.parent[item] = self.find(self.parent[item])
return self.parent[item]
def union(self, item1, item2):
root1 = self.find(item1)
root2 = self.find(item2)
if root1 == root2:
return root1
if self.rank[root1] > self.rank[root2]:
self.parent[root2] = root1
return root1
if self.rank[root1] < self.rank[root2]:
self.parent[root1] = root2
return root2
if self.rank[root1] == self.rank[root2]:
self.rank[root1] += 1
self.parent[root2] = root1
return root1
return None
@staticmethod
def boruvka_mst(graph):
"""
Implementation of Boruvka's algorithm
>>> g = Graph()
>>> g = Graph.build([0, 1, 2, 3], [[0, 1, 1], [0, 2, 1],[2, 3, 1]])
>>> g.distinct_weight()
>>> bg = Graph.boruvka_mst(g)
>>> print(bg)
1 -> 0 == 1
2 -> 0 == 2
0 -> 1 == 1
0 -> 2 == 2
3 -> 2 == 3
2 -> 3 == 3
"""
num_components = graph.num_vertices
union_find = Graph.UnionFind()
mst_edges = []
while num_components > 1:
cheap_edge = {}
for vertex in graph.get_vertices():
cheap_edge[vertex] = -1
edges = graph.get_edges()
for edge in edges:
head, tail, weight = edge
edges.remove((tail, head, weight))
for edge in edges:
head, tail, weight = edge
set1 = union_find.find(head)
set2 = union_find.find(tail)
if set1 != set2:
if cheap_edge[set1] == -1 or cheap_edge[set1][2] > weight:
cheap_edge[set1] = [head, tail, weight]
if cheap_edge[set2] == -1 or cheap_edge[set2][2] > weight:
cheap_edge[set2] = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
head, tail, weight = cheap_edge[vertex]
if union_find.find(head) != union_find.find(tail):
union_find.union(head, tail)
mst_edges.append(cheap_edge[vertex])
num_components = num_components - 1
mst = Graph.build(edges=mst_edges)
return mst
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| def kruskal(
num_nodes: int, edges: list[tuple[int, int, int]]
) -> list[tuple[int, int, int]]:
"""
>>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)])
[(2, 3, 1), (0, 1, 3), (1, 2, 5)]
>>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)])
[(2, 3, 1), (0, 2, 1), (0, 1, 3)]
>>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2),
... (2, 1, 1)])
[(2, 3, 1), (0, 2, 1), (2, 1, 1)]
"""
edges = sorted(edges, key=lambda edge: edge[2])
parent = list(range(num_nodes))
def find_parent(i):
if i != parent[i]:
parent[i] = find_parent(parent[i])
return parent[i]
minimum_spanning_tree_cost = 0
minimum_spanning_tree = []
for edge in edges:
parent_a = find_parent(edge[0])
parent_b = find_parent(edge[1])
if parent_a != parent_b:
minimum_spanning_tree_cost += edge[2]
minimum_spanning_tree.append(edge)
parent[parent_a] = parent_b
return minimum_spanning_tree
if __name__ == "__main__": # pragma: no cover
num_nodes, num_edges = list(map(int, input().strip().split()))
edges = []
for _ in range(num_edges):
node1, node2, cost = (int(x) for x in input().strip().split())
edges.append((node1, node2, cost))
kruskal(num_nodes, edges)
| def kruskal(
num_nodes: int, edges: list[tuple[int, int, int]]
) -> list[tuple[int, int, int]]:
"""
>>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)])
[(2, 3, 1), (0, 1, 3), (1, 2, 5)]
>>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)])
[(2, 3, 1), (0, 2, 1), (0, 1, 3)]
>>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2),
... (2, 1, 1)])
[(2, 3, 1), (0, 2, 1), (2, 1, 1)]
"""
edges = sorted(edges, key=lambda edge: edge[2])
parent = list(range(num_nodes))
def find_parent(i):
if i != parent[i]:
parent[i] = find_parent(parent[i])
return parent[i]
minimum_spanning_tree_cost = 0
minimum_spanning_tree = []
for edge in edges:
parent_a = find_parent(edge[0])
parent_b = find_parent(edge[1])
if parent_a != parent_b:
minimum_spanning_tree_cost += edge[2]
minimum_spanning_tree.append(edge)
parent[parent_a] = parent_b
return minimum_spanning_tree
if __name__ == "__main__": # pragma: no cover
num_nodes, num_edges = list(map(int, input().strip().split()))
edges = []
for _ in range(num_edges):
node1, node2, cost = (int(x) for x in input().strip().split())
edges.append((node1, node2, cost))
kruskal(num_nodes, edges)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import random
class Onepad:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
"""Function to encrypt text using pseudo-random numbers"""
plain = [ord(i) for i in text]
key = []
cipher = []
for i in plain:
k = random.randint(1, 300)
c = (i + k) * k
cipher.append(c)
key.append(k)
return cipher, key
@staticmethod
def decrypt(cipher: list[int], key: list[int]) -> str:
"""Function to decrypt text using pseudo-random numbers."""
plain = []
for i in range(len(key)):
p = int((cipher[i] - (key[i]) ** 2) / key[i])
plain.append(chr(p))
return "".join(plain)
if __name__ == "__main__":
c, k = Onepad().encrypt("Hello")
print(c, k)
print(Onepad().decrypt(c, k))
| import random
class Onepad:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
"""Function to encrypt text using pseudo-random numbers"""
plain = [ord(i) for i in text]
key = []
cipher = []
for i in plain:
k = random.randint(1, 300)
c = (i + k) * k
cipher.append(c)
key.append(k)
return cipher, key
@staticmethod
def decrypt(cipher: list[int], key: list[int]) -> str:
"""Function to decrypt text using pseudo-random numbers."""
plain = []
for i in range(len(key)):
p = int((cipher[i] - (key[i]) ** 2) / key[i])
plain.append(chr(p))
return "".join(plain)
if __name__ == "__main__":
c, k = Onepad().encrypt("Hello")
print(c, k)
print(Onepad().decrypt(c, k))
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
import os
def solution():
"""
Finds the maximum total in a triangle as described by the problem statement
above.
>>> solution()
1074
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle]
for i in range(1, len(a)):
for j in range(len(a[i])):
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number2 = a[i - 1][j - 1] if j > 0 else 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution())
| """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
import os
def solution():
"""
Finds the maximum total in a triangle as described by the problem statement
above.
>>> solution()
1074
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle]
for i in range(1, len(a)):
for j in range(len(a[i])):
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number2 = a[i - 1][j - 1] if j > 0 else 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Partition a set into two subsets such that the difference of subset sums is minimum
"""
def find_min(arr):
n = len(arr)
s = sum(arr)
dp = [[False for x in range(s + 1)] for y in range(n + 1)]
for i in range(1, n + 1):
dp[i][0] = True
for i in range(1, s + 1):
dp[0][i] = False
for i in range(1, n + 1):
for j in range(1, s + 1):
dp[i][j] = dp[i][j - 1]
if arr[i - 1] <= j:
dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]]
for j in range(int(s / 2), -1, -1):
if dp[n][j] is True:
diff = s - 2 * j
break
return diff
| """
Partition a set into two subsets such that the difference of subset sums is minimum
"""
def find_min(arr):
n = len(arr)
s = sum(arr)
dp = [[False for x in range(s + 1)] for y in range(n + 1)]
for i in range(1, n + 1):
dp[i][0] = True
for i in range(1, s + 1):
dp[0][i] = False
for i in range(1, n + 1):
for j in range(1, s + 1):
dp[i][j] = dp[i][j - 1]
if arr[i - 1] <= j:
dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]]
for j in range(int(s / 2), -1, -1):
if dp[n][j] is True:
diff = s - 2 * j
break
return diff
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| #!/usr/local/bin/python3
"""
Problem Description: Given two binary tree, return the merged tree.
The rule for merging is that if two nodes overlap, then put the value sum of
both nodes to the new value of the merged node. Otherwise, the NOT null node
will be used as the node of new tree.
"""
from __future__ import annotations
class Node:
"""
A binary node has value variable and pointers to its left and right node.
"""
def __init__(self, value: int = 0) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None:
"""
Returns root node of the merged tree.
>>> tree1 = Node(5)
>>> tree1.left = Node(6)
>>> tree1.right = Node(7)
>>> tree1.left.left = Node(2)
>>> tree2 = Node(4)
>>> tree2.left = Node(5)
>>> tree2.right = Node(8)
>>> tree2.left.right = Node(1)
>>> tree2.right.right = Node(4)
>>> merged_tree = merge_two_binary_trees(tree1, tree2)
>>> print_preorder(merged_tree)
9
11
2
1
15
4
"""
if tree1 is None:
return tree2
if tree2 is None:
return tree1
tree1.value = tree1.value + tree2.value
tree1.left = merge_two_binary_trees(tree1.left, tree2.left)
tree1.right = merge_two_binary_trees(tree1.right, tree2.right)
return tree1
def print_preorder(root: Node | None) -> None:
"""
Print pre-order traversal of the tree.
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> print_preorder(root)
1
2
3
>>> print_preorder(root.right)
3
"""
if root:
print(root.value)
print_preorder(root.left)
print_preorder(root.right)
if __name__ == "__main__":
tree1 = Node(1)
tree1.left = Node(2)
tree1.right = Node(3)
tree1.left.left = Node(4)
tree2 = Node(2)
tree2.left = Node(4)
tree2.right = Node(6)
tree2.left.right = Node(9)
tree2.right.right = Node(5)
print("Tree1 is: ")
print_preorder(tree1)
print("Tree2 is: ")
print_preorder(tree2)
merged_tree = merge_two_binary_trees(tree1, tree2)
print("Merged Tree is: ")
print_preorder(merged_tree)
| #!/usr/local/bin/python3
"""
Problem Description: Given two binary tree, return the merged tree.
The rule for merging is that if two nodes overlap, then put the value sum of
both nodes to the new value of the merged node. Otherwise, the NOT null node
will be used as the node of new tree.
"""
from __future__ import annotations
class Node:
"""
A binary node has value variable and pointers to its left and right node.
"""
def __init__(self, value: int = 0) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None:
"""
Returns root node of the merged tree.
>>> tree1 = Node(5)
>>> tree1.left = Node(6)
>>> tree1.right = Node(7)
>>> tree1.left.left = Node(2)
>>> tree2 = Node(4)
>>> tree2.left = Node(5)
>>> tree2.right = Node(8)
>>> tree2.left.right = Node(1)
>>> tree2.right.right = Node(4)
>>> merged_tree = merge_two_binary_trees(tree1, tree2)
>>> print_preorder(merged_tree)
9
11
2
1
15
4
"""
if tree1 is None:
return tree2
if tree2 is None:
return tree1
tree1.value = tree1.value + tree2.value
tree1.left = merge_two_binary_trees(tree1.left, tree2.left)
tree1.right = merge_two_binary_trees(tree1.right, tree2.right)
return tree1
def print_preorder(root: Node | None) -> None:
"""
Print pre-order traversal of the tree.
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> print_preorder(root)
1
2
3
>>> print_preorder(root.right)
3
"""
if root:
print(root.value)
print_preorder(root.left)
print_preorder(root.right)
if __name__ == "__main__":
tree1 = Node(1)
tree1.left = Node(2)
tree1.right = Node(3)
tree1.left.left = Node(4)
tree2 = Node(2)
tree2.left = Node(4)
tree2.right = Node(6)
tree2.left.right = Node(9)
tree2.right.right = Node(5)
print("Tree1 is: ")
print_preorder(tree1)
print("Tree2 is: ")
print_preorder(tree2)
merged_tree = merge_two_binary_trees(tree1, tree2)
print("Merged Tree is: ")
print_preorder(merged_tree)
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| import math
from collections.abc import Generator
def slow_primes(max_n: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(slow_primes(0))
[]
>>> list(slow_primes(-1))
[]
>>> list(slow_primes(-10))
[]
>>> list(slow_primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(slow_primes(11))
[2, 3, 5, 7, 11]
>>> list(slow_primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(slow_primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max_n + 1)))
for i in (n for n in numbers if n > 1):
for j in range(2, i):
if (i % j) == 0:
break
else:
yield i
def primes(max_n: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(primes(0))
[]
>>> list(primes(-1))
[]
>>> list(primes(-10))
[]
>>> list(primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(primes(11))
[2, 3, 5, 7, 11]
>>> list(primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max_n + 1)))
for i in (n for n in numbers if n > 1):
# only need to check for factors up to sqrt(i)
bound = int(math.sqrt(i)) + 1
for j in range(2, bound):
if (i % j) == 0:
break
else:
yield i
def fast_primes(max_n: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(fast_primes(0))
[]
>>> list(fast_primes(-1))
[]
>>> list(fast_primes(-10))
[]
>>> list(fast_primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(fast_primes(11))
[2, 3, 5, 7, 11]
>>> list(fast_primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(fast_primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max_n + 1), 2))
# It's useless to test even numbers as they will not be prime
if max_n > 2:
yield 2 # Because 2 will not be tested, it's necessary to yield it now
for i in (n for n in numbers if n > 1):
bound = int(math.sqrt(i)) + 1
for j in range(3, bound, 2):
# As we removed the even numbers, we don't need them now
if (i % j) == 0:
break
else:
yield i
def benchmark():
"""
Let's benchmark our functions side-by-side...
"""
from timeit import timeit
setup = "from __main__ import slow_primes, primes, fast_primes"
print(timeit("slow_primes(1_000_000_000_000)", setup=setup, number=1_000_000))
print(timeit("primes(1_000_000_000_000)", setup=setup, number=1_000_000))
print(timeit("fast_primes(1_000_000_000_000)", setup=setup, number=1_000_000))
if __name__ == "__main__":
number = int(input("Calculate primes up to:\n>> ").strip())
for ret in primes(number):
print(ret)
benchmark()
| import math
from collections.abc import Generator
def slow_primes(max_n: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(slow_primes(0))
[]
>>> list(slow_primes(-1))
[]
>>> list(slow_primes(-10))
[]
>>> list(slow_primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(slow_primes(11))
[2, 3, 5, 7, 11]
>>> list(slow_primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(slow_primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max_n + 1)))
for i in (n for n in numbers if n > 1):
for j in range(2, i):
if (i % j) == 0:
break
else:
yield i
def primes(max_n: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(primes(0))
[]
>>> list(primes(-1))
[]
>>> list(primes(-10))
[]
>>> list(primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(primes(11))
[2, 3, 5, 7, 11]
>>> list(primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max_n + 1)))
for i in (n for n in numbers if n > 1):
# only need to check for factors up to sqrt(i)
bound = int(math.sqrt(i)) + 1
for j in range(2, bound):
if (i % j) == 0:
break
else:
yield i
def fast_primes(max_n: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(fast_primes(0))
[]
>>> list(fast_primes(-1))
[]
>>> list(fast_primes(-10))
[]
>>> list(fast_primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(fast_primes(11))
[2, 3, 5, 7, 11]
>>> list(fast_primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(fast_primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max_n + 1), 2))
# It's useless to test even numbers as they will not be prime
if max_n > 2:
yield 2 # Because 2 will not be tested, it's necessary to yield it now
for i in (n for n in numbers if n > 1):
bound = int(math.sqrt(i)) + 1
for j in range(3, bound, 2):
# As we removed the even numbers, we don't need them now
if (i % j) == 0:
break
else:
yield i
def benchmark():
"""
Let's benchmark our functions side-by-side...
"""
from timeit import timeit
setup = "from __main__ import slow_primes, primes, fast_primes"
print(timeit("slow_primes(1_000_000_000_000)", setup=setup, number=1_000_000))
print(timeit("primes(1_000_000_000_000)", setup=setup, number=1_000_000))
print(timeit("fast_primes(1_000_000_000_000)", setup=setup, number=1_000_000))
if __name__ == "__main__":
number = int(input("Calculate primes up to:\n>> ").strip())
for ret in primes(number):
print(ret)
benchmark()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| #!/usr/bin/env python3
"""
Build a simple bare-minimum quantum circuit that starts with a single
qubit (by default, in state 0) and inverts it. Run the experiment 1000
times and print the total count of the states finally observed.
Qiskit Docs: https://qiskit.org/documentation/getting_started.html
"""
import qiskit
def single_qubit_measure(
qubits: int, classical_bits: int
) -> qiskit.result.counts.Counts:
"""
>>> single_qubit_measure(2, 2)
{'11': 1000}
>>> single_qubit_measure(4, 4)
{'0011': 1000}
"""
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
# Create a Quantum Circuit acting on the q register
circuit = qiskit.QuantumCircuit(qubits, classical_bits)
# Apply X (NOT) Gate to Qubits 0 & 1
circuit.x(0)
circuit.x(1)
# Map the quantum measurement to the classical bits
circuit.measure([0, 1], [0, 1])
# Execute the circuit on the qasm simulator
job = qiskit.execute(circuit, simulator, shots=1000)
# Return the histogram data of the results of the experiment.
return job.result().get_counts(circuit)
if __name__ == "__main__":
counts = single_qubit_measure(2, 2)
print(f"Total count for various states are: {counts}")
| #!/usr/bin/env python3
"""
Build a simple bare-minimum quantum circuit that starts with a single
qubit (by default, in state 0) and inverts it. Run the experiment 1000
times and print the total count of the states finally observed.
Qiskit Docs: https://qiskit.org/documentation/getting_started.html
"""
import qiskit
def single_qubit_measure(
qubits: int, classical_bits: int
) -> qiskit.result.counts.Counts:
"""
>>> single_qubit_measure(2, 2)
{'11': 1000}
>>> single_qubit_measure(4, 4)
{'0011': 1000}
"""
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
# Create a Quantum Circuit acting on the q register
circuit = qiskit.QuantumCircuit(qubits, classical_bits)
# Apply X (NOT) Gate to Qubits 0 & 1
circuit.x(0)
circuit.x(1)
# Map the quantum measurement to the classical bits
circuit.measure([0, 1], [0, 1])
# Execute the circuit on the qasm simulator
job = qiskit.execute(circuit, simulator, shots=1000)
# Return the histogram data of the results of the experiment.
return job.result().get_counts(circuit)
if __name__ == "__main__":
counts = single_qubit_measure(2, 2)
print(f"Total count for various states are: {counts}")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
This script demonstrates an implementation of the Gaussian Error Linear Unit function.
* https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions
The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x).
Gaussian Error Linear Unit (GELU) is a high-performing neural network activation
function.
This script is inspired by a corresponding research paper.
* https://arxiv.org/abs/1606.08415
"""
import numpy as np
def sigmoid(vector: np.array) -> np.array:
"""
Mathematical function sigmoid takes a vector x of K real numbers as input and
returns 1/ (1 + e^-x).
https://en.wikipedia.org/wiki/Sigmoid_function
>>> sigmoid(np.array([-1.0, 1.0, 2.0]))
array([0.26894142, 0.73105858, 0.88079708])
"""
return 1 / (1 + np.exp(-vector))
def gaussian_error_linear_unit(vector: np.array) -> np.array:
"""
Implements the Gaussian Error Linear Unit (GELU) function
Parameters:
vector (np.array): A numpy array of shape (1,n)
consisting of real values
Returns:
gelu_vec (np.array): The input numpy array, after applying
gelu.
Examples:
>>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0]))
array([-0.15420423, 0.84579577, 1.93565862])
>>> gaussian_error_linear_unit(np.array([-3]))
array([-0.01807131])
"""
return vector * sigmoid(1.702 * vector)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
This script demonstrates an implementation of the Gaussian Error Linear Unit function.
* https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions
The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x).
Gaussian Error Linear Unit (GELU) is a high-performing neural network activation
function.
This script is inspired by a corresponding research paper.
* https://arxiv.org/abs/1606.08415
"""
import numpy as np
def sigmoid(vector: np.array) -> np.array:
"""
Mathematical function sigmoid takes a vector x of K real numbers as input and
returns 1/ (1 + e^-x).
https://en.wikipedia.org/wiki/Sigmoid_function
>>> sigmoid(np.array([-1.0, 1.0, 2.0]))
array([0.26894142, 0.73105858, 0.88079708])
"""
return 1 / (1 + np.exp(-vector))
def gaussian_error_linear_unit(vector: np.array) -> np.array:
"""
Implements the Gaussian Error Linear Unit (GELU) function
Parameters:
vector (np.array): A numpy array of shape (1,n)
consisting of real values
Returns:
gelu_vec (np.array): The input numpy array, after applying
gelu.
Examples:
>>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0]))
array([-0.15420423, 0.84579577, 1.93565862])
>>> gaussian_error_linear_unit(np.array([-3]))
array([-0.01807131])
"""
return vector * sigmoid(1.702 * vector)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| from __future__ import annotations
from collections import Counter
from random import random
class MarkovChainGraphUndirectedUnweighted:
"""
Undirected Unweighted Graph for running Markov Chain Algorithm
"""
def __init__(self):
self.connections = {}
def add_node(self, node: str) -> None:
self.connections[node] = {}
def add_transition_probability(
self, node1: str, node2: str, probability: float
) -> None:
if node1 not in self.connections:
self.add_node(node1)
if node2 not in self.connections:
self.add_node(node2)
self.connections[node1][node2] = probability
def get_nodes(self) -> list[str]:
return list(self.connections)
def transition(self, node: str) -> str:
current_probability = 0
random_value = random()
for dest in self.connections[node]:
current_probability += self.connections[node][dest]
if current_probability > random_value:
return dest
return ""
def get_transitions(
start: str, transitions: list[tuple[str, str, float]], steps: int
) -> dict[str, int]:
"""
Running Markov Chain algorithm and calculating the number of times each node is
visited
>>> transitions = [
... ('a', 'a', 0.9),
... ('a', 'b', 0.075),
... ('a', 'c', 0.025),
... ('b', 'a', 0.15),
... ('b', 'b', 0.8),
... ('b', 'c', 0.05),
... ('c', 'a', 0.25),
... ('c', 'b', 0.25),
... ('c', 'c', 0.5)
... ]
>>> result = get_transitions('a', transitions, 5000)
>>> result['a'] > result['b'] > result['c']
True
"""
graph = MarkovChainGraphUndirectedUnweighted()
for node1, node2, probability in transitions:
graph.add_transition_probability(node1, node2, probability)
visited = Counter(graph.get_nodes())
node = start
for _ in range(steps):
node = graph.transition(node)
visited[node] += 1
return visited
if __name__ == "__main__":
import doctest
doctest.testmod()
| from __future__ import annotations
from collections import Counter
from random import random
class MarkovChainGraphUndirectedUnweighted:
"""
Undirected Unweighted Graph for running Markov Chain Algorithm
"""
def __init__(self):
self.connections = {}
def add_node(self, node: str) -> None:
self.connections[node] = {}
def add_transition_probability(
self, node1: str, node2: str, probability: float
) -> None:
if node1 not in self.connections:
self.add_node(node1)
if node2 not in self.connections:
self.add_node(node2)
self.connections[node1][node2] = probability
def get_nodes(self) -> list[str]:
return list(self.connections)
def transition(self, node: str) -> str:
current_probability = 0
random_value = random()
for dest in self.connections[node]:
current_probability += self.connections[node][dest]
if current_probability > random_value:
return dest
return ""
def get_transitions(
start: str, transitions: list[tuple[str, str, float]], steps: int
) -> dict[str, int]:
"""
Running Markov Chain algorithm and calculating the number of times each node is
visited
>>> transitions = [
... ('a', 'a', 0.9),
... ('a', 'b', 0.075),
... ('a', 'c', 0.025),
... ('b', 'a', 0.15),
... ('b', 'b', 0.8),
... ('b', 'c', 0.05),
... ('c', 'a', 0.25),
... ('c', 'b', 0.25),
... ('c', 'c', 0.5)
... ]
>>> result = get_transitions('a', transitions, 5000)
>>> result['a'] > result['b'] > result['c']
True
"""
graph = MarkovChainGraphUndirectedUnweighted()
for node1, node2, probability in transitions:
graph.add_transition_probability(node1, node2, probability)
visited = Counter(graph.get_nodes())
node = start
for _ in range(steps):
node = graph.transition(node)
visited[node] += 1
return visited
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # Implementation of Circular Queue using linked lists
# https://en.wikipedia.org/wiki/Circular_buffer
from __future__ import annotations
from typing import Any
class CircularQueueLinkedList:
"""
Circular FIFO list with the given capacity (default queue length : 6)
>>> cq = CircularQueueLinkedList(2)
>>> cq.enqueue('a')
>>> cq.enqueue('b')
>>> cq.enqueue('c')
Traceback (most recent call last):
...
Exception: Full Queue
"""
def __init__(self, initial_capacity: int = 6) -> None:
self.front: Node | None = None
self.rear: Node | None = None
self.create_linked_list(initial_capacity)
def create_linked_list(self, initial_capacity: int) -> None:
current_node = Node()
self.front = current_node
self.rear = current_node
previous_node = current_node
for _ in range(1, initial_capacity):
current_node = Node()
previous_node.next = current_node
current_node.prev = previous_node
previous_node = current_node
previous_node.next = self.front
self.front.prev = previous_node
def is_empty(self) -> bool:
"""
Checks where the queue is empty or not
>>> cq = CircularQueueLinkedList()
>>> cq.is_empty()
True
>>> cq.enqueue('a')
>>> cq.is_empty()
False
>>> cq.dequeue()
'a'
>>> cq.is_empty()
True
"""
return (
self.front == self.rear
and self.front is not None
and self.front.data is None
)
def first(self) -> Any | None:
"""
Returns the first element of the queue
>>> cq = CircularQueueLinkedList()
>>> cq.first()
Traceback (most recent call last):
...
Exception: Empty Queue
>>> cq.enqueue('a')
>>> cq.first()
'a'
>>> cq.dequeue()
'a'
>>> cq.first()
Traceback (most recent call last):
...
Exception: Empty Queue
>>> cq.enqueue('b')
>>> cq.enqueue('c')
>>> cq.first()
'b'
"""
self.check_can_perform_operation()
return self.front.data if self.front else None
def enqueue(self, data: Any) -> None:
"""
Saves data at the end of the queue
>>> cq = CircularQueueLinkedList()
>>> cq.enqueue('a')
>>> cq.enqueue('b')
>>> cq.dequeue()
'a'
>>> cq.dequeue()
'b'
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: Empty Queue
"""
if self.rear is None:
return
self.check_is_full()
if not self.is_empty():
self.rear = self.rear.next
if self.rear:
self.rear.data = data
def dequeue(self) -> Any:
"""
Removes and retrieves the first element of the queue
>>> cq = CircularQueueLinkedList()
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: Empty Queue
>>> cq.enqueue('a')
>>> cq.dequeue()
'a'
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: Empty Queue
"""
self.check_can_perform_operation()
if self.rear is None or self.front is None:
return None
if self.front == self.rear:
data = self.front.data
self.front.data = None
return data
old_front = self.front
self.front = old_front.next
data = old_front.data
old_front.data = None
return data
def check_can_perform_operation(self) -> None:
if self.is_empty():
raise Exception("Empty Queue")
def check_is_full(self) -> None:
if self.rear and self.rear.next == self.front:
raise Exception("Full Queue")
class Node:
def __init__(self) -> None:
self.data: Any | None = None
self.next: Node | None = None
self.prev: Node | None = None
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Implementation of Circular Queue using linked lists
# https://en.wikipedia.org/wiki/Circular_buffer
from __future__ import annotations
from typing import Any
class CircularQueueLinkedList:
"""
Circular FIFO list with the given capacity (default queue length : 6)
>>> cq = CircularQueueLinkedList(2)
>>> cq.enqueue('a')
>>> cq.enqueue('b')
>>> cq.enqueue('c')
Traceback (most recent call last):
...
Exception: Full Queue
"""
def __init__(self, initial_capacity: int = 6) -> None:
self.front: Node | None = None
self.rear: Node | None = None
self.create_linked_list(initial_capacity)
def create_linked_list(self, initial_capacity: int) -> None:
current_node = Node()
self.front = current_node
self.rear = current_node
previous_node = current_node
for _ in range(1, initial_capacity):
current_node = Node()
previous_node.next = current_node
current_node.prev = previous_node
previous_node = current_node
previous_node.next = self.front
self.front.prev = previous_node
def is_empty(self) -> bool:
"""
Checks where the queue is empty or not
>>> cq = CircularQueueLinkedList()
>>> cq.is_empty()
True
>>> cq.enqueue('a')
>>> cq.is_empty()
False
>>> cq.dequeue()
'a'
>>> cq.is_empty()
True
"""
return (
self.front == self.rear
and self.front is not None
and self.front.data is None
)
def first(self) -> Any | None:
"""
Returns the first element of the queue
>>> cq = CircularQueueLinkedList()
>>> cq.first()
Traceback (most recent call last):
...
Exception: Empty Queue
>>> cq.enqueue('a')
>>> cq.first()
'a'
>>> cq.dequeue()
'a'
>>> cq.first()
Traceback (most recent call last):
...
Exception: Empty Queue
>>> cq.enqueue('b')
>>> cq.enqueue('c')
>>> cq.first()
'b'
"""
self.check_can_perform_operation()
return self.front.data if self.front else None
def enqueue(self, data: Any) -> None:
"""
Saves data at the end of the queue
>>> cq = CircularQueueLinkedList()
>>> cq.enqueue('a')
>>> cq.enqueue('b')
>>> cq.dequeue()
'a'
>>> cq.dequeue()
'b'
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: Empty Queue
"""
if self.rear is None:
return
self.check_is_full()
if not self.is_empty():
self.rear = self.rear.next
if self.rear:
self.rear.data = data
def dequeue(self) -> Any:
"""
Removes and retrieves the first element of the queue
>>> cq = CircularQueueLinkedList()
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: Empty Queue
>>> cq.enqueue('a')
>>> cq.dequeue()
'a'
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: Empty Queue
"""
self.check_can_perform_operation()
if self.rear is None or self.front is None:
return None
if self.front == self.rear:
data = self.front.data
self.front.data = None
return data
old_front = self.front
self.front = old_front.next
data = old_front.data
old_front.data = None
return data
def check_can_perform_operation(self) -> None:
if self.is_empty():
raise Exception("Empty Queue")
def check_is_full(self) -> None:
if self.rear and self.rear.next == self.front:
raise Exception("Full Queue")
class Node:
def __init__(self) -> None:
self.data: Any | None = None
self.next: Node | None = None
self.prev: Node | None = None
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| # Author: M. Yathurshan
# Black Formatter: True
"""
Implementation of SHA256 Hash function in a Python class and provides utilities
to find hash of string or hash of text from a file.
Usage: python sha256.py --string "Hello World!!"
python sha256.py --file "hello_world.txt"
When run without any arguments,
it prints the hash of the string "Hello World!! Welcome to Cryptography"
References:
https://qvault.io/cryptography/how-sha-2-works-step-by-step-sha-256/
https://en.wikipedia.org/wiki/SHA-2
"""
import argparse
import struct
import unittest
class SHA256:
"""
Class to contain the entire pipeline for SHA1 Hashing Algorithm
>>> SHA256(b'Python').hash
'18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db'
>>> SHA256(b'hello world').hash
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
"""
def __init__(self, data: bytes) -> None:
self.data = data
# Initialize hash values
self.hashes = [
0x6A09E667,
0xBB67AE85,
0x3C6EF372,
0xA54FF53A,
0x510E527F,
0x9B05688C,
0x1F83D9AB,
0x5BE0CD19,
]
# Initialize round constants
self.round_constants = [
0x428A2F98,
0x71374491,
0xB5C0FBCF,
0xE9B5DBA5,
0x3956C25B,
0x59F111F1,
0x923F82A4,
0xAB1C5ED5,
0xD807AA98,
0x12835B01,
0x243185BE,
0x550C7DC3,
0x72BE5D74,
0x80DEB1FE,
0x9BDC06A7,
0xC19BF174,
0xE49B69C1,
0xEFBE4786,
0x0FC19DC6,
0x240CA1CC,
0x2DE92C6F,
0x4A7484AA,
0x5CB0A9DC,
0x76F988DA,
0x983E5152,
0xA831C66D,
0xB00327C8,
0xBF597FC7,
0xC6E00BF3,
0xD5A79147,
0x06CA6351,
0x14292967,
0x27B70A85,
0x2E1B2138,
0x4D2C6DFC,
0x53380D13,
0x650A7354,
0x766A0ABB,
0x81C2C92E,
0x92722C85,
0xA2BFE8A1,
0xA81A664B,
0xC24B8B70,
0xC76C51A3,
0xD192E819,
0xD6990624,
0xF40E3585,
0x106AA070,
0x19A4C116,
0x1E376C08,
0x2748774C,
0x34B0BCB5,
0x391C0CB3,
0x4ED8AA4A,
0x5B9CCA4F,
0x682E6FF3,
0x748F82EE,
0x78A5636F,
0x84C87814,
0x8CC70208,
0x90BEFFFA,
0xA4506CEB,
0xBEF9A3F7,
0xC67178F2,
]
self.preprocessed_data = self.preprocessing(self.data)
self.final_hash()
@staticmethod
def preprocessing(data: bytes) -> bytes:
padding = b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64))
big_endian_integer = struct.pack(">Q", (len(data) * 8))
return data + padding + big_endian_integer
def final_hash(self) -> None:
# Convert into blocks of 64 bytes
self.blocks = [
self.preprocessed_data[x : x + 64]
for x in range(0, len(self.preprocessed_data), 64)
]
for block in self.blocks:
# Convert the given block into a list of 4 byte integers
words = list(struct.unpack(">16L", block))
# add 48 0-ed integers
words += [0] * 48
a, b, c, d, e, f, g, h = self.hashes
for index in range(0, 64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
self.ror(words[index - 15], 7)
^ self.ror(words[index - 15], 18)
^ (words[index - 15] >> 3)
)
s1 = (
self.ror(words[index - 2], 17)
^ self.ror(words[index - 2], 19)
^ (words[index - 2] >> 10)
)
words[index] = (
words[index - 16] + s0 + words[index - 7] + s1
) % 0x100000000
# Compression
s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25)
ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g)
temp1 = (
h + s1 + ch + self.round_constants[index] + words[index]
) % 0x100000000
s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22)
maj = (a & b) ^ (a & c) ^ (b & c)
temp2 = (s0 + maj) % 0x100000000
h, g, f, e, d, c, b, a = (
g,
f,
e,
((d + temp1) % 0x100000000),
c,
b,
a,
((temp1 + temp2) % 0x100000000),
)
mutated_hash_values = [a, b, c, d, e, f, g, h]
# Modify final values
self.hashes = [
((element + mutated_hash_values[index]) % 0x100000000)
for index, element in enumerate(self.hashes)
]
self.hash = "".join([hex(value)[2:].zfill(8) for value in self.hashes])
def ror(self, value: int, rotations: int) -> int:
"""
Right rotate a given unsigned number by a certain amount of rotations
"""
return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations)
class SHA256HashTest(unittest.TestCase):
"""
Test class for the SHA256 class. Inherits the TestCase class from unittest
"""
def test_match_hashes(self) -> None:
import hashlib
msg = bytes("Test String", "utf-8")
self.assertEqual(SHA256(msg).hash, hashlib.sha256(msg).hexdigest())
def main() -> None:
"""
Provides option 'string' or 'file' to take input
and prints the calculated SHA-256 hash
"""
# unittest.main()
import doctest
doctest.testmod()
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--string",
dest="input_string",
default="Hello World!! Welcome to Cryptography",
help="Hash the string",
)
parser.add_argument(
"-f", "--file", dest="input_file", help="Hash contents of a file"
)
args = parser.parse_args()
input_string = args.input_string
# hash input should be a bytestring
if args.input_file:
with open(args.input_file, "rb") as f:
hash_input = f.read()
else:
hash_input = bytes(input_string, "utf-8")
print(SHA256(hash_input).hash)
if __name__ == "__main__":
main()
| # Author: M. Yathurshan
# Black Formatter: True
"""
Implementation of SHA256 Hash function in a Python class and provides utilities
to find hash of string or hash of text from a file.
Usage: python sha256.py --string "Hello World!!"
python sha256.py --file "hello_world.txt"
When run without any arguments,
it prints the hash of the string "Hello World!! Welcome to Cryptography"
References:
https://qvault.io/cryptography/how-sha-2-works-step-by-step-sha-256/
https://en.wikipedia.org/wiki/SHA-2
"""
import argparse
import struct
import unittest
class SHA256:
"""
Class to contain the entire pipeline for SHA1 Hashing Algorithm
>>> SHA256(b'Python').hash
'18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db'
>>> SHA256(b'hello world').hash
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
"""
def __init__(self, data: bytes) -> None:
self.data = data
# Initialize hash values
self.hashes = [
0x6A09E667,
0xBB67AE85,
0x3C6EF372,
0xA54FF53A,
0x510E527F,
0x9B05688C,
0x1F83D9AB,
0x5BE0CD19,
]
# Initialize round constants
self.round_constants = [
0x428A2F98,
0x71374491,
0xB5C0FBCF,
0xE9B5DBA5,
0x3956C25B,
0x59F111F1,
0x923F82A4,
0xAB1C5ED5,
0xD807AA98,
0x12835B01,
0x243185BE,
0x550C7DC3,
0x72BE5D74,
0x80DEB1FE,
0x9BDC06A7,
0xC19BF174,
0xE49B69C1,
0xEFBE4786,
0x0FC19DC6,
0x240CA1CC,
0x2DE92C6F,
0x4A7484AA,
0x5CB0A9DC,
0x76F988DA,
0x983E5152,
0xA831C66D,
0xB00327C8,
0xBF597FC7,
0xC6E00BF3,
0xD5A79147,
0x06CA6351,
0x14292967,
0x27B70A85,
0x2E1B2138,
0x4D2C6DFC,
0x53380D13,
0x650A7354,
0x766A0ABB,
0x81C2C92E,
0x92722C85,
0xA2BFE8A1,
0xA81A664B,
0xC24B8B70,
0xC76C51A3,
0xD192E819,
0xD6990624,
0xF40E3585,
0x106AA070,
0x19A4C116,
0x1E376C08,
0x2748774C,
0x34B0BCB5,
0x391C0CB3,
0x4ED8AA4A,
0x5B9CCA4F,
0x682E6FF3,
0x748F82EE,
0x78A5636F,
0x84C87814,
0x8CC70208,
0x90BEFFFA,
0xA4506CEB,
0xBEF9A3F7,
0xC67178F2,
]
self.preprocessed_data = self.preprocessing(self.data)
self.final_hash()
@staticmethod
def preprocessing(data: bytes) -> bytes:
padding = b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64))
big_endian_integer = struct.pack(">Q", (len(data) * 8))
return data + padding + big_endian_integer
def final_hash(self) -> None:
# Convert into blocks of 64 bytes
self.blocks = [
self.preprocessed_data[x : x + 64]
for x in range(0, len(self.preprocessed_data), 64)
]
for block in self.blocks:
# Convert the given block into a list of 4 byte integers
words = list(struct.unpack(">16L", block))
# add 48 0-ed integers
words += [0] * 48
a, b, c, d, e, f, g, h = self.hashes
for index in range(0, 64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
self.ror(words[index - 15], 7)
^ self.ror(words[index - 15], 18)
^ (words[index - 15] >> 3)
)
s1 = (
self.ror(words[index - 2], 17)
^ self.ror(words[index - 2], 19)
^ (words[index - 2] >> 10)
)
words[index] = (
words[index - 16] + s0 + words[index - 7] + s1
) % 0x100000000
# Compression
s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25)
ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g)
temp1 = (
h + s1 + ch + self.round_constants[index] + words[index]
) % 0x100000000
s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22)
maj = (a & b) ^ (a & c) ^ (b & c)
temp2 = (s0 + maj) % 0x100000000
h, g, f, e, d, c, b, a = (
g,
f,
e,
((d + temp1) % 0x100000000),
c,
b,
a,
((temp1 + temp2) % 0x100000000),
)
mutated_hash_values = [a, b, c, d, e, f, g, h]
# Modify final values
self.hashes = [
((element + mutated_hash_values[index]) % 0x100000000)
for index, element in enumerate(self.hashes)
]
self.hash = "".join([hex(value)[2:].zfill(8) for value in self.hashes])
def ror(self, value: int, rotations: int) -> int:
"""
Right rotate a given unsigned number by a certain amount of rotations
"""
return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations)
class SHA256HashTest(unittest.TestCase):
"""
Test class for the SHA256 class. Inherits the TestCase class from unittest
"""
def test_match_hashes(self) -> None:
import hashlib
msg = bytes("Test String", "utf-8")
self.assertEqual(SHA256(msg).hash, hashlib.sha256(msg).hexdigest())
def main() -> None:
"""
Provides option 'string' or 'file' to take input
and prints the calculated SHA-256 hash
"""
# unittest.main()
import doctest
doctest.testmod()
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--string",
dest="input_string",
default="Hello World!! Welcome to Cryptography",
help="Hash the string",
)
parser.add_argument(
"-f", "--file", dest="input_file", help="Hash contents of a file"
)
args = parser.parse_args()
input_string = args.input_string
# hash input should be a bytestring
if args.input_file:
with open(args.input_file, "rb") as f:
hash_input = f.read()
else:
hash_input = bytes(input_string, "utf-8")
print(SHA256(hash_input).hash)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| -1 |
||
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| """
Given an array of integer elements and an integer 'k', we are required to find the
maximum sum of 'k' consecutive elements in the array.
Instead of using a nested for loop, in a Brute force approach we will use a technique
called 'Window sliding technique' where the nested loops can be converted to a single
loop to reduce time complexity.
"""
from __future__ import annotations
def max_sum_in_array(array: list[int], k: int) -> int:
"""
Returns the maximum sum of k consecutive elements
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
>>> k = 4
>>> max_sum_in_array(arr, k)
24
>>> k = 10
>>> max_sum_in_array(arr,k)
Traceback (most recent call last):
...
ValueError: Invalid Input
>>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]
>>> k = 4
>>> max_sum_in_array(arr, k)
27
"""
if len(array) < k or k < 0:
raise ValueError("Invalid Input")
max_sum = current_sum = sum(array[:k])
for i in range(len(array) - k):
current_sum = current_sum - array[i] + array[i + k]
max_sum = max(max_sum, current_sum)
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
| """
Given an array of integer elements and an integer 'k', we are required to find the
maximum sum of 'k' consecutive elements in the array.
Instead of using a nested for loop, in a Brute force approach we will use a technique
called 'Window sliding technique' where the nested loops can be converted to a single
loop to reduce time complexity.
"""
from __future__ import annotations
def max_sum_in_array(array: list[int], k: int) -> int:
"""
Returns the maximum sum of k consecutive elements
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
>>> k = 4
>>> max_sum_in_array(arr, k)
24
>>> k = 10
>>> max_sum_in_array(arr,k)
Traceback (most recent call last):
...
ValueError: Invalid Input
>>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]
>>> k = 4
>>> max_sum_in_array(arr, k)
27
"""
if len(array) < k or k < 0:
raise ValueError("Invalid Input")
max_sum = current_sum = sum(array[:k])
for i in range(len(array) - k):
current_sum = current_sum - array[i] + array[i + k]
max_sum = max(max_sum, current_sum)
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
| -1 |
TheAlgorithms/Python | 8,936 | Fix ruff errors | ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| tianyizheng02 | "2023-08-09T07:13:45Z" | "2023-08-09T07:55:31Z" | 842d03fb2ab7d83e4d4081c248d71e89bb520809 | ae0fc85401efd9816193a06e554a66600cc09a97 | Fix ruff errors. ### Describe your change:
Fixes #8935
Fixing ruff errors again due to the recent version update
Notably, I didn't fix the ruff error in [neural_network/input_data.py](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/input_data.py) because it appears that the file was taken directly from TensorFlow's codebase, so I don't want to modify it _just_ yet. Instead, I renamed it to neural_network/input_data.py_tf because it should be left out of the directory for the following reasons:
1. Its sole purpose is to be used by [neural_network/gan.py_tf](https://github.com/TheAlgorithms/Python/blob/842d03fb2ab7d83e4d4081c248d71e89bb520809/neural_network/gan.py_tf), which is itself left out of the directory because of issues with TensorFlow.
2. All of it's actually deprecated—TensorFlow explicitly says so in the code and recommends getting the necessary input data using a different function. If/when neural_network/gan.py_tf is eventually added back to the directory, its implementation should be changed to not use neural_network/input_data.py anyway.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] 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.
* [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
| 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 |
Subsets and Splits