repo_name
stringclasses 1
value | pr_number
int64 4.12k
11.2k
| pr_title
stringlengths 9
107
| pr_description
stringlengths 107
5.48k
| author
stringlengths 4
18
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 118
5.52k
| before_content
stringlengths 0
7.93M
| after_content
stringlengths 0
7.93M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/python
"""Author Anurag Kumar | [email protected] | git/anuragkumarak95
Simple example of Fractal generation using recursive function.
What is Sierpinski Triangle?
>>The Sierpinski triangle (also with the original orthography Sierpinski), also called
the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set
with the overall shape of an equilateral triangle, subdivided recursively into smaller
equilateral triangles. Originally constructed as a curve, this is one of the basic
examples of self-similar sets, i.e., it is a mathematically generated pattern that can
be reproducible at any magnification or reduction. It is named after the Polish
mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries
prior to the work of Sierpinski.
Requirements(pip):
- turtle
Python:
- 2.6
Usage:
- $python sierpinski_triangle.py <int:depth_for_fractal>
Credits: This code was written by editing the code from
http://www.riannetrujillo.com/blog/python-fractal/
"""
import sys
import turtle
PROGNAME = "Sierpinski Triangle"
points = [[-175, -125], [0, 175], [175, -125]] # size of triangle
def getMid(p1, p2):
return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) # find midpoint
def triangle(points, depth):
myPen.up()
myPen.goto(points[0][0], points[0][1])
myPen.down()
myPen.goto(points[1][0], points[1][1])
myPen.goto(points[2][0], points[2][1])
myPen.goto(points[0][0], points[0][1])
if depth > 0:
triangle(
[points[0], getMid(points[0], points[1]), getMid(points[0], points[2])],
depth - 1,
)
triangle(
[points[1], getMid(points[0], points[1]), getMid(points[1], points[2])],
depth - 1,
)
triangle(
[points[2], getMid(points[2], points[1]), getMid(points[0], points[2])],
depth - 1,
)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError(
"right format for using this script: "
"$python fractals.py <int:depth_for_fractal>"
)
myPen = turtle.Turtle()
myPen.ht()
myPen.speed(5)
myPen.pencolor("red")
triangle(points, int(sys.argv[1]))
| #!/usr/bin/python
"""Author Anurag Kumar | [email protected] | git/anuragkumarak95
Simple example of Fractal generation using recursive function.
What is Sierpinski Triangle?
>>The Sierpinski triangle (also with the original orthography Sierpinski), also called
the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set
with the overall shape of an equilateral triangle, subdivided recursively into smaller
equilateral triangles. Originally constructed as a curve, this is one of the basic
examples of self-similar sets, i.e., it is a mathematically generated pattern that can
be reproducible at any magnification or reduction. It is named after the Polish
mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries
prior to the work of Sierpinski.
Requirements(pip):
- turtle
Python:
- 2.6
Usage:
- $python sierpinski_triangle.py <int:depth_for_fractal>
Credits: This code was written by editing the code from
http://www.riannetrujillo.com/blog/python-fractal/
"""
import sys
import turtle
PROGNAME = "Sierpinski Triangle"
points = [[-175, -125], [0, 175], [175, -125]] # size of triangle
def getMid(p1, p2):
return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) # find midpoint
def triangle(points, depth):
myPen.up()
myPen.goto(points[0][0], points[0][1])
myPen.down()
myPen.goto(points[1][0], points[1][1])
myPen.goto(points[2][0], points[2][1])
myPen.goto(points[0][0], points[0][1])
if depth > 0:
triangle(
[points[0], getMid(points[0], points[1]), getMid(points[0], points[2])],
depth - 1,
)
triangle(
[points[1], getMid(points[0], points[1]), getMid(points[1], points[2])],
depth - 1,
)
triangle(
[points[2], getMid(points[2], points[1]), getMid(points[0], points[2])],
depth - 1,
)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError(
"right format for using this script: "
"$python fractals.py <int:depth_for_fractal>"
)
myPen = turtle.Turtle()
myPen.ht()
myPen.speed(5)
myPen.pencolor("red")
triangle(points, int(sys.argv[1]))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
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, target, learning_rate=0.01, epoch_number=1000, bias=-1):
"""
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 = []
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 i 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) -> 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],
]
exit = [
-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=exit, 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 = []
for i in range(len(samples[0])):
observation = input("value: ").strip()
if observation == "q":
break
observation = float(observation)
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, target, learning_rate=0.01, epoch_number=1000, bias=-1):
"""
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 = []
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 i 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) -> 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],
]
exit = [
-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=exit, 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 = []
for i in range(len(samples[0])):
observation = input("value: ").strip()
if observation == "q":
break
observation = float(observation)
sample.insert(i, observation)
network.sort(sample)
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler 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(list(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(list(str(num ** 3))))
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #
| #
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The function below will convert any binary string to the octal equivalent.
>>> bin_to_octal("1111")
'17'
>>> bin_to_octal("101010101010011")
'52523'
>>> bin_to_octal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> bin_to_octal("a-1")
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
"""
def bin_to_octal(bin_string: str) -> str:
if not all(char in "01" for char in bin_string):
raise ValueError("Non-binary value was passed to the function")
if not bin_string:
raise ValueError("Empty string was passed to the function")
oct_string = ""
while len(bin_string) % 3 != 0:
bin_string = "0" + bin_string
bin_string_in_3_list = [
bin_string[index : index + 3]
for index, value in enumerate(bin_string)
if index % 3 == 0
]
for bin_group in bin_string_in_3_list:
oct_val = 0
for index, val in enumerate(bin_group):
oct_val += int(2 ** (2 - index) * int(val))
oct_string += str(oct_val)
return oct_string
if __name__ == "__main__":
from doctest import testmod
testmod()
| """
The function below will convert any binary string to the octal equivalent.
>>> bin_to_octal("1111")
'17'
>>> bin_to_octal("101010101010011")
'52523'
>>> bin_to_octal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> bin_to_octal("a-1")
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
"""
def bin_to_octal(bin_string: str) -> str:
if not all(char in "01" for char in bin_string):
raise ValueError("Non-binary value was passed to the function")
if not bin_string:
raise ValueError("Empty string was passed to the function")
oct_string = ""
while len(bin_string) % 3 != 0:
bin_string = "0" + bin_string
bin_string_in_3_list = [
bin_string[index : index + 3]
for index, value in enumerate(bin_string)
if index % 3 == 0
]
for bin_group in bin_string_in_3_list:
oct_val = 0
for index, val in enumerate(bin_group):
oct_val += int(2 ** (2 - index) * int(val))
oct_string += str(oct_val)
return oct_string
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Author: https://github.com/bhushan-borole
"""
"""
The input graph for the algorithm is:
A B C
A 0 1 1
B 0 0 1
C 1 0 0
"""
graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]]
class Node:
def __init__(self, name):
self.name = name
self.inbound = []
self.outbound = []
def add_inbound(self, node):
self.inbound.append(node)
def add_outbound(self, node):
self.outbound.append(node)
def __repr__(self):
return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}"
def page_rank(nodes, limit=3, d=0.85):
ranks = {}
for node in nodes:
ranks[node.name] = 1
outbounds = {}
for node in nodes:
outbounds[node.name] = len(node.outbound)
for i in range(limit):
print(f"======= Iteration {i + 1} =======")
for j, node in enumerate(nodes):
ranks[node.name] = (1 - d) + d * sum(
[ranks[ib] / outbounds[ib] for ib in node.inbound]
)
print(ranks)
def main():
names = list(input("Enter Names of the Nodes: ").split())
nodes = [Node(name) for name in names]
for ri, row in enumerate(graph):
for ci, col in enumerate(row):
if col == 1:
nodes[ci].add_inbound(names[ri])
nodes[ri].add_outbound(names[ci])
print("======= Nodes =======")
for node in nodes:
print(node)
page_rank(nodes)
if __name__ == "__main__":
main()
| """
Author: https://github.com/bhushan-borole
"""
"""
The input graph for the algorithm is:
A B C
A 0 1 1
B 0 0 1
C 1 0 0
"""
graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]]
class Node:
def __init__(self, name):
self.name = name
self.inbound = []
self.outbound = []
def add_inbound(self, node):
self.inbound.append(node)
def add_outbound(self, node):
self.outbound.append(node)
def __repr__(self):
return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}"
def page_rank(nodes, limit=3, d=0.85):
ranks = {}
for node in nodes:
ranks[node.name] = 1
outbounds = {}
for node in nodes:
outbounds[node.name] = len(node.outbound)
for i in range(limit):
print(f"======= Iteration {i + 1} =======")
for j, node in enumerate(nodes):
ranks[node.name] = (1 - d) + d * sum(
[ranks[ib] / outbounds[ib] for ib in node.inbound]
)
print(ranks)
def main():
names = list(input("Enter Names of the Nodes: ").split())
nodes = [Node(name) for name in names]
for ri, row in enumerate(graph):
for ci, col in enumerate(row):
if col == 1:
nodes[ci].add_inbound(names[ri])
nodes[ri].add_outbound(names[ci])
print("======= Nodes =======")
for node in nodes:
print(node)
page_rank(nodes)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Champernowne's constant
Problem 40
An irrational decimal fraction is created by concatenating the positive
integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the
following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
"""
def solution():
"""Returns
>>> solution()
210
"""
constant = []
i = 1
while len(constant) < 1e6:
constant.append(str(i))
i += 1
constant = "".join(constant)
return (
int(constant[0])
* int(constant[9])
* int(constant[99])
* int(constant[999])
* int(constant[9999])
* int(constant[99999])
* int(constant[999999])
)
if __name__ == "__main__":
print(solution())
| """
Champernowne's constant
Problem 40
An irrational decimal fraction is created by concatenating the positive
integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the
following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
"""
def solution():
"""Returns
>>> solution()
210
"""
constant = []
i = 1
while len(constant) < 1e6:
constant.append(str(i))
i += 1
constant = "".join(constant)
return (
int(constant[0])
* int(constant[9])
* int(constant[99])
* int(constant[999])
* int(constant[9999])
* int(constant[99999])
* int(constant[999999])
)
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Prize Strings
Problem 191
A particular school offers cash rewards to children with good attendance and
punctuality. If they are absent for three consecutive days or late on more
than one occasion then they forfeit their prize.
During an n-day period a trinary string is formed for each child consisting
of L's (late), O's (on time), and A's (absent).
Although there are eighty-one trinary strings for a 4-day period that can be
formed, exactly forty-three strings would lead to a prize:
OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA
OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO
AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL
AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA
LAOO LAOA LAAO
How many "prize" strings exist over a 30-day period?
References:
- The original Project Euler project page:
https://projecteuler.net/problem=191
"""
cache = {}
def _calculate(days: int, absent: int, late: int) -> int:
"""
A small helper function for the recursion, mainly to have
a clean interface for the solution() function below.
It should get called with the number of days (corresponding
to the desired length of the 'prize strings'), and the
initial values for the number of consecutive absent days and
number of total late days.
>>> _calculate(days=4, absent=0, late=0)
43
>>> _calculate(days=30, absent=2, late=0)
0
>>> _calculate(days=30, absent=1, late=0)
98950096
"""
# if we are absent twice, or late 3 consecutive days,
# no further prize strings are possible
if late == 3 or absent == 2:
return 0
# if we have no days left, and have not failed any other rules,
# we have a prize string
if days == 0:
return 1
# No easy solution, so now we need to do the recursive calculation
# First, check if the combination is already in the cache, and
# if yes, return the stored value from there since we already
# know the number of possible prize strings from this point on
key = (days, absent, late)
if key in cache:
return cache[key]
# now we calculate the three possible ways that can unfold from
# this point on, depending on our attendance today
# 1) if we are late (but not absent), the "absent" counter stays as
# it is, but the "late" counter increases by one
state_late = _calculate(days - 1, absent, late + 1)
# 2) if we are absent, the "absent" counter increases by 1, and the
# "late" counter resets to 0
state_absent = _calculate(days - 1, absent + 1, 0)
# 3) if we are on time, this resets the "late" counter and keeps the
# absent counter
state_ontime = _calculate(days - 1, absent, 0)
prizestrings = state_late + state_absent + state_ontime
cache[key] = prizestrings
return prizestrings
def solution(days: int = 30) -> int:
"""
Returns the number of possible prize strings for a particular number
of days, using a simple recursive function with caching to speed it up.
>>> solution()
1918080160
>>> solution(4)
43
"""
return _calculate(days, absent=0, late=0)
if __name__ == "__main__":
print(solution())
| """
Prize Strings
Problem 191
A particular school offers cash rewards to children with good attendance and
punctuality. If they are absent for three consecutive days or late on more
than one occasion then they forfeit their prize.
During an n-day period a trinary string is formed for each child consisting
of L's (late), O's (on time), and A's (absent).
Although there are eighty-one trinary strings for a 4-day period that can be
formed, exactly forty-three strings would lead to a prize:
OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA
OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO
AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL
AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA
LAOO LAOA LAAO
How many "prize" strings exist over a 30-day period?
References:
- The original Project Euler project page:
https://projecteuler.net/problem=191
"""
cache = {}
def _calculate(days: int, absent: int, late: int) -> int:
"""
A small helper function for the recursion, mainly to have
a clean interface for the solution() function below.
It should get called with the number of days (corresponding
to the desired length of the 'prize strings'), and the
initial values for the number of consecutive absent days and
number of total late days.
>>> _calculate(days=4, absent=0, late=0)
43
>>> _calculate(days=30, absent=2, late=0)
0
>>> _calculate(days=30, absent=1, late=0)
98950096
"""
# if we are absent twice, or late 3 consecutive days,
# no further prize strings are possible
if late == 3 or absent == 2:
return 0
# if we have no days left, and have not failed any other rules,
# we have a prize string
if days == 0:
return 1
# No easy solution, so now we need to do the recursive calculation
# First, check if the combination is already in the cache, and
# if yes, return the stored value from there since we already
# know the number of possible prize strings from this point on
key = (days, absent, late)
if key in cache:
return cache[key]
# now we calculate the three possible ways that can unfold from
# this point on, depending on our attendance today
# 1) if we are late (but not absent), the "absent" counter stays as
# it is, but the "late" counter increases by one
state_late = _calculate(days - 1, absent, late + 1)
# 2) if we are absent, the "absent" counter increases by 1, and the
# "late" counter resets to 0
state_absent = _calculate(days - 1, absent + 1, 0)
# 3) if we are on time, this resets the "late" counter and keeps the
# absent counter
state_ontime = _calculate(days - 1, absent, 0)
prizestrings = state_late + state_absent + state_ontime
cache[key] = prizestrings
return prizestrings
def solution(days: int = 30) -> int:
"""
Returns the number of possible prize strings for a particular number
of days, using a simple recursive function with caching to speed it up.
>>> solution()
1918080160
>>> solution(4)
43
"""
return _calculate(days, absent=0, late=0)
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is pure Python implementation of comb sort algorithm.
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz
Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991.
Comb sort improves on bubble sort algorithm.
In bubble sort, distance (or gap) between two compared elements is always one.
Comb sort improvement is that gap can be much more than 1, in order to prevent slowing
down by small values
at the end of a list.
More info on: https://en.wikipedia.org/wiki/Comb_sort
For doctests run following command:
python -m doctest -v comb_sort.py
or
python3 -m doctest -v comb_sort.py
For manual testing run:
python comb_sort.py
"""
def comb_sort(data: list) -> list:
"""Pure implementation of comb sort algorithm in Python
:param data: mutable collection with comparable items
:return: the same collection in ascending order
Examples:
>>> comb_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> comb_sort([])
[]
>>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
[-15, -7, 0, 2, 3, 8, 45, 99]
"""
shrink_factor = 1.3
gap = len(data)
completed = False
while not completed:
# Update the gap value for a next comb
gap = int(gap / shrink_factor)
if gap <= 1:
completed = True
index = 0
while index + gap < len(data):
if data[index] > data[index + gap]:
# Swap values
data[index], data[index + gap] = data[index + gap], data[index]
completed = False
index += 1
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(comb_sort(unsorted))
| """
This is pure Python implementation of comb sort algorithm.
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz
Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991.
Comb sort improves on bubble sort algorithm.
In bubble sort, distance (or gap) between two compared elements is always one.
Comb sort improvement is that gap can be much more than 1, in order to prevent slowing
down by small values
at the end of a list.
More info on: https://en.wikipedia.org/wiki/Comb_sort
For doctests run following command:
python -m doctest -v comb_sort.py
or
python3 -m doctest -v comb_sort.py
For manual testing run:
python comb_sort.py
"""
def comb_sort(data: list) -> list:
"""Pure implementation of comb sort algorithm in Python
:param data: mutable collection with comparable items
:return: the same collection in ascending order
Examples:
>>> comb_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> comb_sort([])
[]
>>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
[-15, -7, 0, 2, 3, 8, 45, 99]
"""
shrink_factor = 1.3
gap = len(data)
completed = False
while not completed:
# Update the gap value for a next comb
gap = int(gap / shrink_factor)
if gap <= 1:
completed = True
index = 0
while index + gap < len(data):
if data[index] > data[index + gap]:
# Swap values
data[index], data[index + gap] = data[index + gap], data[index]
completed = False
index += 1
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(comb_sort(unsorted))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 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
"""
i = 1
j = 2
total = 0
while j <= n:
if j % 2 == 0:
total += j
i, j = j, i + j
return total
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 2: https://projecteuler.net/problem=2
Even Fibonacci Numbers
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
References:
- https://en.wikipedia.org/wiki/Fibonacci_number
"""
def solution(n: int = 4000000) -> int:
"""
Returns the sum of all even fibonacci sequence elements that are lower
or equal to n.
>>> solution(10)
10
>>> solution(15)
10
>>> solution(2)
2
>>> solution(1)
0
>>> solution(34)
44
"""
i = 1
j = 2
total = 0
while j <= n:
if j % 2 == 0:
total += j
i, j = j, i + j
return total
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://cp-algorithms.com/string/z-function.html
Z-function or Z algorithm
Efficient algorithm for pattern occurrence in a string
Time Complexity: O(n) - where n is the length of the string
"""
def z_function(input_str: str) -> list:
"""
For the given string this function computes value for each index,
which represents the maximal length substring starting from the index
and is the same as the prefix of the same size
e.x. for string 'abab' for second index value would be 2
For the value of the first element the algorithm always returns 0
>>> z_function("abracadabra")
[0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]
>>> z_function("aaaa")
[0, 3, 2, 1]
>>> z_function("zxxzxxz")
[0, 0, 0, 4, 0, 0, 1]
"""
z_result = [0] * len(input_str)
# initialize interval's left pointer and right pointer
left_pointer, right_pointer = 0, 0
for i in range(1, len(input_str)):
# case when current index is inside the interval
if i <= right_pointer:
min_edge = min(right_pointer - i + 1, z_result[i - left_pointer])
z_result[i] = min_edge
while go_next(i, z_result, input_str):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
left_pointer, right_pointer = i, i + z_result[i] - 1
return z_result
def go_next(i, z_result, s):
"""
Check if we have to move forward to the next characters or not
"""
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
def find_pattern(pattern: str, input_str: str) -> int:
"""
Example of using z-function for pattern occurrence
Given function returns the number of times 'pattern'
appears in 'input_str' as a substring
>>> find_pattern("abr", "abracadabra")
2
>>> find_pattern("a", "aaaa")
4
>>> find_pattern("xz", "zxxzxxz")
2
"""
answer = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
z_result = z_function(pattern + input_str)
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(pattern):
answer += 1
return answer
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
https://cp-algorithms.com/string/z-function.html
Z-function or Z algorithm
Efficient algorithm for pattern occurrence in a string
Time Complexity: O(n) - where n is the length of the string
"""
def z_function(input_str: str) -> list:
"""
For the given string this function computes value for each index,
which represents the maximal length substring starting from the index
and is the same as the prefix of the same size
e.x. for string 'abab' for second index value would be 2
For the value of the first element the algorithm always returns 0
>>> z_function("abracadabra")
[0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]
>>> z_function("aaaa")
[0, 3, 2, 1]
>>> z_function("zxxzxxz")
[0, 0, 0, 4, 0, 0, 1]
"""
z_result = [0] * len(input_str)
# initialize interval's left pointer and right pointer
left_pointer, right_pointer = 0, 0
for i in range(1, len(input_str)):
# case when current index is inside the interval
if i <= right_pointer:
min_edge = min(right_pointer - i + 1, z_result[i - left_pointer])
z_result[i] = min_edge
while go_next(i, z_result, input_str):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
left_pointer, right_pointer = i, i + z_result[i] - 1
return z_result
def go_next(i, z_result, s):
"""
Check if we have to move forward to the next characters or not
"""
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
def find_pattern(pattern: str, input_str: str) -> int:
"""
Example of using z-function for pattern occurrence
Given function returns the number of times 'pattern'
appears in 'input_str' as a substring
>>> find_pattern("abr", "abracadabra")
2
>>> find_pattern("a", "aaaa")
4
>>> find_pattern("xz", "zxxzxxz")
2
"""
answer = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
z_result = z_function(pattern + input_str)
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(pattern):
answer += 1
return answer
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 46: https://projecteuler.net/problem=46
It was proposed by Christian Goldbach that every odd composite number can be
written as the sum of a prime and twice a square.
9 = 7 + 2 × 12
15 = 7 + 2 × 22
21 = 3 + 2 × 32
25 = 7 + 2 × 32
27 = 19 + 2 × 22
33 = 31 + 2 × 12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a
prime and twice a square?
"""
from __future__ import annotations
seive = [True] * 100001
i = 2
while i * i <= 100000:
if seive[i]:
for j in range(i * i, 100001, i):
seive[j] = False
i += 1
def is_prime(n: int) -> bool:
"""
Returns True if n is prime,
False otherwise, for 2 <= n <= 100000
>>> is_prime(87)
False
>>> is_prime(23)
True
>>> is_prime(25363)
False
"""
return seive[n]
odd_composites = [num for num in range(3, len(seive), 2) if not is_prime(num)]
def compute_nums(n: int) -> list[int]:
"""
Returns a list of first n odd composite numbers which do
not follow the conjecture.
>>> compute_nums(1)
[5777]
>>> compute_nums(2)
[5777, 5993]
>>> compute_nums(0)
Traceback (most recent call last):
...
ValueError: n must be >= 0
>>> compute_nums("a")
Traceback (most recent call last):
...
ValueError: n must be an integer
>>> compute_nums(1.1)
Traceback (most recent call last):
...
ValueError: n must be an integer
"""
if not isinstance(n, int):
raise ValueError("n must be an integer")
if n <= 0:
raise ValueError("n must be >= 0")
list_nums = []
for num in range(len(odd_composites)):
i = 0
while 2 * i * i <= odd_composites[num]:
rem = odd_composites[num] - 2 * i * i
if is_prime(rem):
break
i += 1
else:
list_nums.append(odd_composites[num])
if len(list_nums) == n:
return list_nums
def solution() -> int:
"""Return the solution to the problem"""
return compute_nums(1)[0]
if __name__ == "__main__":
print(f"{solution() = }")
| """
Problem 46: https://projecteuler.net/problem=46
It was proposed by Christian Goldbach that every odd composite number can be
written as the sum of a prime and twice a square.
9 = 7 + 2 × 12
15 = 7 + 2 × 22
21 = 3 + 2 × 32
25 = 7 + 2 × 32
27 = 19 + 2 × 22
33 = 31 + 2 × 12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a
prime and twice a square?
"""
from __future__ import annotations
seive = [True] * 100001
i = 2
while i * i <= 100000:
if seive[i]:
for j in range(i * i, 100001, i):
seive[j] = False
i += 1
def is_prime(n: int) -> bool:
"""
Returns True if n is prime,
False otherwise, for 2 <= n <= 100000
>>> is_prime(87)
False
>>> is_prime(23)
True
>>> is_prime(25363)
False
"""
return seive[n]
odd_composites = [num for num in range(3, len(seive), 2) if not is_prime(num)]
def compute_nums(n: int) -> list[int]:
"""
Returns a list of first n odd composite numbers which do
not follow the conjecture.
>>> compute_nums(1)
[5777]
>>> compute_nums(2)
[5777, 5993]
>>> compute_nums(0)
Traceback (most recent call last):
...
ValueError: n must be >= 0
>>> compute_nums("a")
Traceback (most recent call last):
...
ValueError: n must be an integer
>>> compute_nums(1.1)
Traceback (most recent call last):
...
ValueError: n must be an integer
"""
if not isinstance(n, int):
raise ValueError("n must be an integer")
if n <= 0:
raise ValueError("n must be >= 0")
list_nums = []
for num in range(len(odd_composites)):
i = 0
while 2 * i * i <= odd_composites[num]:
rem = odd_composites[num] - 2 * i * i
if is_prime(rem):
break
i += 1
else:
list_nums.append(odd_composites[num])
if len(list_nums) == n:
return list_nums
def solution() -> int:
"""Return the solution to the problem"""
return compute_nums(1)[0]
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """README, Author - Anurag Kumar(mailto:[email protected])
Requirements:
- sklearn
- numpy
- matplotlib
Python:
- 3.5
Inputs:
- X , a 2D numpy array of features.
- k , number of clusters to create.
- initial_centroids , initial centroid values generated by utility function(mentioned
in usage).
- maxiter , maximum number of iterations to process.
- heterogeneity , empty list that will be filled with hetrogeneity values if passed
to kmeans func.
Usage:
1. define 'k' value, 'X' features array and 'hetrogeneity' empty list
2. create initial_centroids,
initial_centroids = get_initial_centroids(
X,
k,
seed=0 # seed value for initial centroid generation,
# None for randomness(default=None)
)
3. find centroids and clusters using kmeans function.
centroids, cluster_assignment = kmeans(
X,
k,
initial_centroids,
maxiter=400,
record_heterogeneity=heterogeneity,
verbose=True # whether to print logs in console or not.(default=False)
)
4. Plot the loss function, hetrogeneity values for every iteration saved in
hetrogeneity list.
plot_heterogeneity(
heterogeneity,
k
)
5. Transfers Dataframe into excel format it must have feature called
'Clust' with k means clustering numbers in it.
"""
import warnings
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import pairwise_distances
warnings.filterwarnings("ignore")
TAG = "K-MEANS-CLUST/ "
def get_initial_centroids(data, k, seed=None):
"""Randomly choose k data points as initial centroids"""
if seed is not None: # useful for obtaining consistent results
np.random.seed(seed)
n = data.shape[0] # number of data points
# Pick K indices from range [0, N).
rand_indices = np.random.randint(0, n, k)
# Keep centroids as dense format, as many entries will be nonzero due to averaging.
# As long as at least one document in a cluster contains a word,
# it will carry a nonzero weight in the TF-IDF vector of the centroid.
centroids = data[rand_indices, :]
return centroids
def centroid_pairwise_dist(X, centroids):
return pairwise_distances(X, centroids, metric="euclidean")
def assign_clusters(data, centroids):
# Compute distances between each data point and the set of centroids:
# Fill in the blank (RHS only)
distances_from_centroids = centroid_pairwise_dist(data, centroids)
# Compute cluster assignments for each data point:
# Fill in the blank (RHS only)
cluster_assignment = np.argmin(distances_from_centroids, axis=1)
return cluster_assignment
def revise_centroids(data, k, cluster_assignment):
new_centroids = []
for i in range(k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = data[cluster_assignment == i]
# Compute the mean of the data points. Fill in the blank (RHS only)
centroid = member_data_points.mean(axis=0)
new_centroids.append(centroid)
new_centroids = np.array(new_centroids)
return new_centroids
def compute_heterogeneity(data, k, centroids, cluster_assignment):
heterogeneity = 0.0
for i in range(k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = data[cluster_assignment == i, :]
if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty
# Compute distances from centroid to data points (RHS only)
distances = pairwise_distances(
member_data_points, [centroids[i]], metric="euclidean"
)
squared_distances = distances ** 2
heterogeneity += np.sum(squared_distances)
return heterogeneity
def plot_heterogeneity(heterogeneity, k):
plt.figure(figsize=(7, 4))
plt.plot(heterogeneity, linewidth=4)
plt.xlabel("# Iterations")
plt.ylabel("Heterogeneity")
plt.title(f"Heterogeneity of clustering over time, K={k:d}")
plt.rcParams.update({"font.size": 16})
plt.show()
def kmeans(
data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False
):
"""This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.(default=500)
record_heterogeneity: (optional) a list, to store the history of heterogeneity
as function of iterations
if None, do not store the history.
verbose: if True, print how many data points changed their cluster labels in
each iteration"""
centroids = initial_centroids[:]
prev_cluster_assignment = None
for itr in range(maxiter):
if verbose:
print(itr, end="")
# 1. Make cluster assignments using nearest centroids
cluster_assignment = assign_clusters(data, centroids)
# 2. Compute a new centroid for each of the k clusters, averaging all data
# points assigned to that cluster.
centroids = revise_centroids(data, k, cluster_assignment)
# Check for convergence: if none of the assignments changed, stop
if (
prev_cluster_assignment is not None
and (prev_cluster_assignment == cluster_assignment).all()
):
break
# Print number of new assignments
if prev_cluster_assignment is not None:
num_changed = np.sum(prev_cluster_assignment != cluster_assignment)
if verbose:
print(
" {:5d} elements changed their cluster assignment.".format(
num_changed
)
)
# Record heterogeneity convergence metric
if record_heterogeneity is not None:
# YOUR CODE HERE
score = compute_heterogeneity(data, k, centroids, cluster_assignment)
record_heterogeneity.append(score)
prev_cluster_assignment = cluster_assignment[:]
return centroids, cluster_assignment
# Mock test below
if False: # change to true to run this test case.
from sklearn import datasets as ds
dataset = ds.load_iris()
k = 3
heterogeneity = []
initial_centroids = get_initial_centroids(dataset["data"], k, seed=0)
centroids, cluster_assignment = kmeans(
dataset["data"],
k,
initial_centroids,
maxiter=400,
record_heterogeneity=heterogeneity,
verbose=True,
)
plot_heterogeneity(heterogeneity, k)
def ReportGenerator(
df: pd.DataFrame, ClusteringVariables: np.array, FillMissingReport=None
) -> pd.DataFrame:
"""
Function generates easy-erading clustering report. It takes 2 arguments as an input:
DataFrame - dataframe with predicted cluester column;
FillMissingReport - dictionary of rules how we are going to fill missing
values of for final report generate (not included in modeling);
in order to run the function following libraries must be imported:
import pandas as pd
import numpy as np
>>> data = pd.DataFrame()
>>> data['numbers'] = [1, 2, 3]
>>> data['col1'] = [0.5, 2.5, 4.5]
>>> data['col2'] = [100, 200, 300]
>>> data['col3'] = [10, 20, 30]
>>> data['Cluster'] = [1, 1, 2]
>>> ReportGenerator(data, ['col1', 'col2'], 0)
Features Type Mark 1 2
0 # of Customers ClusterSize False 2.000000 1.000000
1 % of Customers ClusterProportion False 0.666667 0.333333
2 col1 mean_with_zeros True 1.500000 4.500000
3 col2 mean_with_zeros True 150.000000 300.000000
4 numbers mean_with_zeros False 1.500000 3.000000
.. ... ... ... ... ...
99 dummy 5% False 1.000000 1.000000
100 dummy 95% False 1.000000 1.000000
101 dummy stdev False 0.000000 NaN
102 dummy mode False 1.000000 1.000000
103 dummy median False 1.000000 1.000000
<BLANKLINE>
[104 rows x 5 columns]
"""
# Fill missing values with given rules
if FillMissingReport:
df.fillna(value=FillMissingReport, inplace=True)
df["dummy"] = 1
numeric_cols = df.select_dtypes(np.number).columns
report = (
df.groupby(["Cluster"])[ # construct report dataframe
numeric_cols
] # group by cluster number
.agg(
[
("sum", np.sum),
("mean_with_zeros", lambda x: np.mean(np.nan_to_num(x))),
("mean_without_zeros", lambda x: x.replace(0, np.NaN).mean()),
(
"mean_25-75",
lambda x: np.mean(
np.nan_to_num(
sorted(x)[
round(len(x) * 25 / 100) : round(len(x) * 75 / 100)
]
)
),
),
("mean_with_na", np.mean),
("min", lambda x: x.min()),
("5%", lambda x: x.quantile(0.05)),
("25%", lambda x: x.quantile(0.25)),
("50%", lambda x: x.quantile(0.50)),
("75%", lambda x: x.quantile(0.75)),
("95%", lambda x: x.quantile(0.95)),
("max", lambda x: x.max()),
("count", lambda x: x.count()),
("stdev", lambda x: x.std()),
("mode", lambda x: x.mode()[0]),
("median", lambda x: x.median()),
("# > 0", lambda x: (x > 0).sum()),
]
)
.T.reset_index()
.rename(index=str, columns={"level_0": "Features", "level_1": "Type"})
) # rename columns
# calculate the size of cluster(count of clientID's)
clustersize = report[
(report["Features"] == "dummy") & (report["Type"] == "count")
].copy() # avoid SettingWithCopyWarning
clustersize.Type = (
"ClusterSize" # rename created cluster df to match report column names
)
clustersize.Features = "# of Customers"
clusterproportion = pd.DataFrame(
clustersize.iloc[:, 2:].values
/ clustersize.iloc[:, 2:].values.sum() # calculating the proportion of cluster
)
clusterproportion[
"Type"
] = "% of Customers" # rename created cluster df to match report column names
clusterproportion["Features"] = "ClusterProportion"
cols = clusterproportion.columns.tolist()
cols = cols[-2:] + cols[:-2]
clusterproportion = clusterproportion[cols] # rearrange columns to match report
clusterproportion.columns = report.columns
a = pd.DataFrame(
abs(
report[report["Type"] == "count"].iloc[:, 2:].values
- clustersize.iloc[:, 2:].values
)
) # generating df with count of nan values
a["Features"] = 0
a["Type"] = "# of nan"
a.Features = report[
report["Type"] == "count"
].Features.tolist() # filling values in order to match report
cols = a.columns.tolist()
cols = cols[-2:] + cols[:-2]
a = a[cols] # rearrange columns to match report
a.columns = report.columns # rename columns to match report
report = report.drop(
report[report.Type == "count"].index
) # drop count values except cluster size
report = pd.concat(
[report, a, clustersize, clusterproportion], axis=0
) # concat report with clustert size and nan values
report["Mark"] = report["Features"].isin(ClusteringVariables)
cols = report.columns.tolist()
cols = cols[0:2] + cols[-1:] + cols[2:-1]
report = report[cols]
sorter1 = {
"ClusterSize": 9,
"ClusterProportion": 8,
"mean_with_zeros": 7,
"mean_with_na": 6,
"max": 5,
"50%": 4,
"min": 3,
"25%": 2,
"75%": 1,
"# of nan": 0,
"# > 0": -1,
"sum_with_na": -2,
}
report = (
report.assign(
Sorter1=lambda x: x.Type.map(sorter1),
Sorter2=lambda x: list(reversed(range(len(x)))),
)
.sort_values(["Sorter1", "Mark", "Sorter2"], ascending=False)
.drop(["Sorter1", "Sorter2"], axis=1)
)
report.columns.name = ""
report = report.reset_index()
report.drop(columns=["index"], inplace=True)
return report
if __name__ == "__main__":
import doctest
doctest.testmod()
| """README, Author - Anurag Kumar(mailto:[email protected])
Requirements:
- sklearn
- numpy
- matplotlib
Python:
- 3.5
Inputs:
- X , a 2D numpy array of features.
- k , number of clusters to create.
- initial_centroids , initial centroid values generated by utility function(mentioned
in usage).
- maxiter , maximum number of iterations to process.
- heterogeneity , empty list that will be filled with hetrogeneity values if passed
to kmeans func.
Usage:
1. define 'k' value, 'X' features array and 'hetrogeneity' empty list
2. create initial_centroids,
initial_centroids = get_initial_centroids(
X,
k,
seed=0 # seed value for initial centroid generation,
# None for randomness(default=None)
)
3. find centroids and clusters using kmeans function.
centroids, cluster_assignment = kmeans(
X,
k,
initial_centroids,
maxiter=400,
record_heterogeneity=heterogeneity,
verbose=True # whether to print logs in console or not.(default=False)
)
4. Plot the loss function, hetrogeneity values for every iteration saved in
hetrogeneity list.
plot_heterogeneity(
heterogeneity,
k
)
5. Transfers Dataframe into excel format it must have feature called
'Clust' with k means clustering numbers in it.
"""
import warnings
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import pairwise_distances
warnings.filterwarnings("ignore")
TAG = "K-MEANS-CLUST/ "
def get_initial_centroids(data, k, seed=None):
"""Randomly choose k data points as initial centroids"""
if seed is not None: # useful for obtaining consistent results
np.random.seed(seed)
n = data.shape[0] # number of data points
# Pick K indices from range [0, N).
rand_indices = np.random.randint(0, n, k)
# Keep centroids as dense format, as many entries will be nonzero due to averaging.
# As long as at least one document in a cluster contains a word,
# it will carry a nonzero weight in the TF-IDF vector of the centroid.
centroids = data[rand_indices, :]
return centroids
def centroid_pairwise_dist(X, centroids):
return pairwise_distances(X, centroids, metric="euclidean")
def assign_clusters(data, centroids):
# Compute distances between each data point and the set of centroids:
# Fill in the blank (RHS only)
distances_from_centroids = centroid_pairwise_dist(data, centroids)
# Compute cluster assignments for each data point:
# Fill in the blank (RHS only)
cluster_assignment = np.argmin(distances_from_centroids, axis=1)
return cluster_assignment
def revise_centroids(data, k, cluster_assignment):
new_centroids = []
for i in range(k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = data[cluster_assignment == i]
# Compute the mean of the data points. Fill in the blank (RHS only)
centroid = member_data_points.mean(axis=0)
new_centroids.append(centroid)
new_centroids = np.array(new_centroids)
return new_centroids
def compute_heterogeneity(data, k, centroids, cluster_assignment):
heterogeneity = 0.0
for i in range(k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = data[cluster_assignment == i, :]
if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty
# Compute distances from centroid to data points (RHS only)
distances = pairwise_distances(
member_data_points, [centroids[i]], metric="euclidean"
)
squared_distances = distances ** 2
heterogeneity += np.sum(squared_distances)
return heterogeneity
def plot_heterogeneity(heterogeneity, k):
plt.figure(figsize=(7, 4))
plt.plot(heterogeneity, linewidth=4)
plt.xlabel("# Iterations")
plt.ylabel("Heterogeneity")
plt.title(f"Heterogeneity of clustering over time, K={k:d}")
plt.rcParams.update({"font.size": 16})
plt.show()
def kmeans(
data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False
):
"""This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.(default=500)
record_heterogeneity: (optional) a list, to store the history of heterogeneity
as function of iterations
if None, do not store the history.
verbose: if True, print how many data points changed their cluster labels in
each iteration"""
centroids = initial_centroids[:]
prev_cluster_assignment = None
for itr in range(maxiter):
if verbose:
print(itr, end="")
# 1. Make cluster assignments using nearest centroids
cluster_assignment = assign_clusters(data, centroids)
# 2. Compute a new centroid for each of the k clusters, averaging all data
# points assigned to that cluster.
centroids = revise_centroids(data, k, cluster_assignment)
# Check for convergence: if none of the assignments changed, stop
if (
prev_cluster_assignment is not None
and (prev_cluster_assignment == cluster_assignment).all()
):
break
# Print number of new assignments
if prev_cluster_assignment is not None:
num_changed = np.sum(prev_cluster_assignment != cluster_assignment)
if verbose:
print(
" {:5d} elements changed their cluster assignment.".format(
num_changed
)
)
# Record heterogeneity convergence metric
if record_heterogeneity is not None:
# YOUR CODE HERE
score = compute_heterogeneity(data, k, centroids, cluster_assignment)
record_heterogeneity.append(score)
prev_cluster_assignment = cluster_assignment[:]
return centroids, cluster_assignment
# Mock test below
if False: # change to true to run this test case.
from sklearn import datasets as ds
dataset = ds.load_iris()
k = 3
heterogeneity = []
initial_centroids = get_initial_centroids(dataset["data"], k, seed=0)
centroids, cluster_assignment = kmeans(
dataset["data"],
k,
initial_centroids,
maxiter=400,
record_heterogeneity=heterogeneity,
verbose=True,
)
plot_heterogeneity(heterogeneity, k)
def ReportGenerator(
df: pd.DataFrame, ClusteringVariables: np.array, FillMissingReport=None
) -> pd.DataFrame:
"""
Function generates easy-erading clustering report. It takes 2 arguments as an input:
DataFrame - dataframe with predicted cluester column;
FillMissingReport - dictionary of rules how we are going to fill missing
values of for final report generate (not included in modeling);
in order to run the function following libraries must be imported:
import pandas as pd
import numpy as np
>>> data = pd.DataFrame()
>>> data['numbers'] = [1, 2, 3]
>>> data['col1'] = [0.5, 2.5, 4.5]
>>> data['col2'] = [100, 200, 300]
>>> data['col3'] = [10, 20, 30]
>>> data['Cluster'] = [1, 1, 2]
>>> ReportGenerator(data, ['col1', 'col2'], 0)
Features Type Mark 1 2
0 # of Customers ClusterSize False 2.000000 1.000000
1 % of Customers ClusterProportion False 0.666667 0.333333
2 col1 mean_with_zeros True 1.500000 4.500000
3 col2 mean_with_zeros True 150.000000 300.000000
4 numbers mean_with_zeros False 1.500000 3.000000
.. ... ... ... ... ...
99 dummy 5% False 1.000000 1.000000
100 dummy 95% False 1.000000 1.000000
101 dummy stdev False 0.000000 NaN
102 dummy mode False 1.000000 1.000000
103 dummy median False 1.000000 1.000000
<BLANKLINE>
[104 rows x 5 columns]
"""
# Fill missing values with given rules
if FillMissingReport:
df.fillna(value=FillMissingReport, inplace=True)
df["dummy"] = 1
numeric_cols = df.select_dtypes(np.number).columns
report = (
df.groupby(["Cluster"])[ # construct report dataframe
numeric_cols
] # group by cluster number
.agg(
[
("sum", np.sum),
("mean_with_zeros", lambda x: np.mean(np.nan_to_num(x))),
("mean_without_zeros", lambda x: x.replace(0, np.NaN).mean()),
(
"mean_25-75",
lambda x: np.mean(
np.nan_to_num(
sorted(x)[
round(len(x) * 25 / 100) : round(len(x) * 75 / 100)
]
)
),
),
("mean_with_na", np.mean),
("min", lambda x: x.min()),
("5%", lambda x: x.quantile(0.05)),
("25%", lambda x: x.quantile(0.25)),
("50%", lambda x: x.quantile(0.50)),
("75%", lambda x: x.quantile(0.75)),
("95%", lambda x: x.quantile(0.95)),
("max", lambda x: x.max()),
("count", lambda x: x.count()),
("stdev", lambda x: x.std()),
("mode", lambda x: x.mode()[0]),
("median", lambda x: x.median()),
("# > 0", lambda x: (x > 0).sum()),
]
)
.T.reset_index()
.rename(index=str, columns={"level_0": "Features", "level_1": "Type"})
) # rename columns
# calculate the size of cluster(count of clientID's)
clustersize = report[
(report["Features"] == "dummy") & (report["Type"] == "count")
].copy() # avoid SettingWithCopyWarning
clustersize.Type = (
"ClusterSize" # rename created cluster df to match report column names
)
clustersize.Features = "# of Customers"
clusterproportion = pd.DataFrame(
clustersize.iloc[:, 2:].values
/ clustersize.iloc[:, 2:].values.sum() # calculating the proportion of cluster
)
clusterproportion[
"Type"
] = "% of Customers" # rename created cluster df to match report column names
clusterproportion["Features"] = "ClusterProportion"
cols = clusterproportion.columns.tolist()
cols = cols[-2:] + cols[:-2]
clusterproportion = clusterproportion[cols] # rearrange columns to match report
clusterproportion.columns = report.columns
a = pd.DataFrame(
abs(
report[report["Type"] == "count"].iloc[:, 2:].values
- clustersize.iloc[:, 2:].values
)
) # generating df with count of nan values
a["Features"] = 0
a["Type"] = "# of nan"
a.Features = report[
report["Type"] == "count"
].Features.tolist() # filling values in order to match report
cols = a.columns.tolist()
cols = cols[-2:] + cols[:-2]
a = a[cols] # rearrange columns to match report
a.columns = report.columns # rename columns to match report
report = report.drop(
report[report.Type == "count"].index
) # drop count values except cluster size
report = pd.concat(
[report, a, clustersize, clusterproportion], axis=0
) # concat report with clustert size and nan values
report["Mark"] = report["Features"].isin(ClusteringVariables)
cols = report.columns.tolist()
cols = cols[0:2] + cols[-1:] + cols[2:-1]
report = report[cols]
sorter1 = {
"ClusterSize": 9,
"ClusterProportion": 8,
"mean_with_zeros": 7,
"mean_with_na": 6,
"max": 5,
"50%": 4,
"min": 3,
"25%": 2,
"75%": 1,
"# of nan": 0,
"# > 0": -1,
"sum_with_na": -2,
}
report = (
report.assign(
Sorter1=lambda x: x.Type.map(sorter1),
Sorter2=lambda x: list(reversed(range(len(x)))),
)
.sort_values(["Sorter1", "Mark", "Sorter2"], ascending=False)
.drop(["Sorter1", "Sorter2"], axis=1)
)
report.columns.name = ""
report = report.reset_index()
report.drop(columns=["index"], inplace=True)
return report
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
from .hash_table import HashTable
class QuadraticProbing(HashTable):
"""
Basic Hash Table example with open addressing using Quadratic Probing
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _collision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(key + i * i)
while self.values[new_key] is not None and self.values[new_key] != key:
i += 1
new_key = (
self.hash_function(key + i * i)
if not self.balanced_factor() >= self.lim_charge
else None
)
if new_key is None:
break
return new_key
| #!/usr/bin/env python3
from .hash_table import HashTable
class QuadraticProbing(HashTable):
"""
Basic Hash Table example with open addressing using Quadratic Probing
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _collision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(key + i * i)
while self.values[new_key] is not None and self.values[new_key] != key:
i += 1
new_key = (
self.hash_function(key + i * i)
if not self.balanced_factor() >= self.lim_charge
else None
)
if new_key is None:
break
return new_key
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A non-recursive Segment Tree implementation with range query and single element update,
works virtually with any list of the same type of elements with a "commutative"
combiner.
Explanation:
https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/
https://www.geeksforgeeks.org/segment-tree-efficient-implementation/
>>> SegmentTree([1, 2, 3], lambda a, b: a + b).query(0, 2)
6
>>> SegmentTree([3, 1, 2], min).query(0, 2)
1
>>> SegmentTree([2, 3, 1], max).query(0, 2)
3
>>> st = SegmentTree([1, 5, 7, -1, 6], lambda a, b: a + b)
>>> st.update(1, -1)
>>> st.update(2, 3)
>>> st.query(1, 2)
2
>>> st.query(1, 1)
-1
>>> st.update(4, 1)
>>> st.query(3, 4)
0
>>> st = SegmentTree([[1, 2, 3], [3, 2, 1], [1, 1, 1]], lambda a, b: [a[i] + b[i] for i
... in range(len(a))])
>>> st.query(0, 1)
[4, 4, 4]
>>> st.query(1, 2)
[4, 3, 2]
>>> st.update(1, [-1, -1, -1])
>>> st.query(1, 2)
[0, 0, 0]
>>> st.query(0, 2)
[1, 2, 3]
"""
from __future__ import annotations
from typing import Callable, TypeVar
T = TypeVar("T")
class SegmentTree:
def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None:
"""
Segment Tree constructor, it works just with commutative combiner.
:param arr: list of elements for the segment tree
:param fnc: commutative function for combine two elements
>>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2)
'abc'
>>> SegmentTree([(1, 2), (2, 3), (3, 4)],
... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2)
(6, 9)
"""
self.N = len(arr)
self.st = [None for _ in range(len(arr))] + arr
self.fn = fnc
self.build()
def build(self) -> None:
for p in range(self.N - 1, 0, -1):
self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])
def update(self, p: int, v: T) -> None:
"""
Update an element in log(N) time
:param p: position to be update
:param v: new value
>>> st = SegmentTree([3, 1, 2, 4], min)
>>> st.query(0, 3)
1
>>> st.update(2, -1)
>>> st.query(0, 3)
-1
"""
p += self.N
self.st[p] = v
while p > 1:
p = p // 2
self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])
def query(self, l: int, r: int) -> T: # noqa: E741
"""
Get range query value in log(N) time
:param l: left element index
:param r: right element index
:return: element combined in the range [l, r]
>>> st = SegmentTree([1, 2, 3, 4], lambda a, b: a + b)
>>> st.query(0, 2)
6
>>> st.query(1, 2)
5
>>> st.query(0, 3)
10
>>> st.query(2, 3)
7
"""
l, r = l + self.N, r + self.N # noqa: E741
res = None
while l <= r: # noqa: E741
if l % 2 == 1:
res = self.st[l] if res is None else self.fn(res, self.st[l])
if r % 2 == 0:
res = self.st[r] if res is None else self.fn(res, self.st[r])
l, r = (l + 1) // 2, (r - 1) // 2
return res
if __name__ == "__main__":
from functools import reduce
test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]
test_updates = {
0: 7,
1: 2,
2: 6,
3: -14,
4: 5,
5: 4,
6: 7,
7: -10,
8: 9,
9: 10,
10: 12,
11: 1,
}
min_segment_tree = SegmentTree(test_array, min)
max_segment_tree = SegmentTree(test_array, max)
sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b)
def test_all_segments():
"""
Test all possible segments
"""
for i in range(len(test_array)):
for j in range(i, len(test_array)):
min_range = reduce(min, test_array[i : j + 1])
max_range = reduce(max, test_array[i : j + 1])
sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1])
assert min_range == min_segment_tree.query(i, j)
assert max_range == max_segment_tree.query(i, j)
assert sum_range == sum_segment_tree.query(i, j)
test_all_segments()
for index, value in test_updates.items():
test_array[index] = value
min_segment_tree.update(index, value)
max_segment_tree.update(index, value)
sum_segment_tree.update(index, value)
test_all_segments()
| """
A non-recursive Segment Tree implementation with range query and single element update,
works virtually with any list of the same type of elements with a "commutative"
combiner.
Explanation:
https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/
https://www.geeksforgeeks.org/segment-tree-efficient-implementation/
>>> SegmentTree([1, 2, 3], lambda a, b: a + b).query(0, 2)
6
>>> SegmentTree([3, 1, 2], min).query(0, 2)
1
>>> SegmentTree([2, 3, 1], max).query(0, 2)
3
>>> st = SegmentTree([1, 5, 7, -1, 6], lambda a, b: a + b)
>>> st.update(1, -1)
>>> st.update(2, 3)
>>> st.query(1, 2)
2
>>> st.query(1, 1)
-1
>>> st.update(4, 1)
>>> st.query(3, 4)
0
>>> st = SegmentTree([[1, 2, 3], [3, 2, 1], [1, 1, 1]], lambda a, b: [a[i] + b[i] for i
... in range(len(a))])
>>> st.query(0, 1)
[4, 4, 4]
>>> st.query(1, 2)
[4, 3, 2]
>>> st.update(1, [-1, -1, -1])
>>> st.query(1, 2)
[0, 0, 0]
>>> st.query(0, 2)
[1, 2, 3]
"""
from __future__ import annotations
from typing import Callable, TypeVar
T = TypeVar("T")
class SegmentTree:
def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None:
"""
Segment Tree constructor, it works just with commutative combiner.
:param arr: list of elements for the segment tree
:param fnc: commutative function for combine two elements
>>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2)
'abc'
>>> SegmentTree([(1, 2), (2, 3), (3, 4)],
... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2)
(6, 9)
"""
self.N = len(arr)
self.st = [None for _ in range(len(arr))] + arr
self.fn = fnc
self.build()
def build(self) -> None:
for p in range(self.N - 1, 0, -1):
self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])
def update(self, p: int, v: T) -> None:
"""
Update an element in log(N) time
:param p: position to be update
:param v: new value
>>> st = SegmentTree([3, 1, 2, 4], min)
>>> st.query(0, 3)
1
>>> st.update(2, -1)
>>> st.query(0, 3)
-1
"""
p += self.N
self.st[p] = v
while p > 1:
p = p // 2
self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])
def query(self, l: int, r: int) -> T: # noqa: E741
"""
Get range query value in log(N) time
:param l: left element index
:param r: right element index
:return: element combined in the range [l, r]
>>> st = SegmentTree([1, 2, 3, 4], lambda a, b: a + b)
>>> st.query(0, 2)
6
>>> st.query(1, 2)
5
>>> st.query(0, 3)
10
>>> st.query(2, 3)
7
"""
l, r = l + self.N, r + self.N # noqa: E741
res = None
while l <= r: # noqa: E741
if l % 2 == 1:
res = self.st[l] if res is None else self.fn(res, self.st[l])
if r % 2 == 0:
res = self.st[r] if res is None else self.fn(res, self.st[r])
l, r = (l + 1) // 2, (r - 1) // 2
return res
if __name__ == "__main__":
from functools import reduce
test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]
test_updates = {
0: 7,
1: 2,
2: 6,
3: -14,
4: 5,
5: 4,
6: 7,
7: -10,
8: 9,
9: 10,
10: 12,
11: 1,
}
min_segment_tree = SegmentTree(test_array, min)
max_segment_tree = SegmentTree(test_array, max)
sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b)
def test_all_segments():
"""
Test all possible segments
"""
for i in range(len(test_array)):
for j in range(i, len(test_array)):
min_range = reduce(min, test_array[i : j + 1])
max_range = reduce(max, test_array[i : j + 1])
sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1])
assert min_range == min_segment_tree.query(i, j)
assert max_range == max_segment_tree.query(i, j)
assert sum_range == sum_segment_tree.query(i, j)
test_all_segments()
for index, value in test_updates.items():
test_array[index] = value
min_segment_tree.update(index, value)
max_segment_tree.update(index, value)
sum_segment_tree.update(index, value)
test_all_segments()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # flake8: noqa
"""
Binomial Heap
Reference: Advanced Data Structures, Peter Brass
"""
class Node:
"""
Node in a doubly-linked binomial tree, containing:
- value
- size of left subtree
- link to left, right and parent nodes
"""
def __init__(self, val):
self.val = val
# Number of nodes in left subtree
self.left_tree_size = 0
self.left = None
self.right = None
self.parent = None
def mergeTrees(self, other):
"""
In-place merge of two binomial trees of equal size.
Returns the root of the resulting tree
"""
assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks"
if self.val < other.val:
other.left = self.right
other.parent = None
if self.right:
self.right.parent = other
self.right = other
self.left_tree_size = self.left_tree_size * 2 + 1
return self
else:
self.left = other.right
self.parent = None
if other.right:
other.right.parent = self
other.right = self
other.left_tree_size = other.left_tree_size * 2 + 1
return other
class BinomialHeap:
r"""
Min-oriented priority queue implemented with the Binomial Heap data
structure implemented with the BinomialHeap class. It supports:
- Insert element in a heap with n elements: Guaranteed logn, amoratized 1
- Merge (meld) heaps of size m and n: O(logn + logm)
- Delete Min: O(logn)
- Peek (return min without deleting it): O(1)
Example:
Create a random permutation of 30 integers to be inserted and 19 of them deleted
>>> import numpy as np
>>> permutation = np.random.permutation(list(range(30)))
Create a Heap and insert the 30 integers
__init__() test
>>> first_heap = BinomialHeap()
30 inserts - insert() test
>>> for number in permutation:
... first_heap.insert(number)
Size test
>>> print(first_heap.size)
30
Deleting - delete() test
>>> for i in range(25):
... print(first_heap.deleteMin(), end=" ")
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Create a new Heap
>>> second_heap = BinomialHeap()
>>> vals = [17, 20, 31, 34]
>>> for value in vals:
... second_heap.insert(value)
The heap should have the following structure:
17
/ \
# 31
/ \
20 34
/ \ / \
# # # #
preOrder() test
>>> print(second_heap.preOrder())
[(17, 0), ('#', 1), (31, 1), (20, 2), ('#', 3), ('#', 3), (34, 2), ('#', 3), ('#', 3)]
printing Heap - __str__() test
>>> print(second_heap)
17
-#
-31
--20
---#
---#
--34
---#
---#
mergeHeaps() test
>>> merged = second_heap.mergeHeaps(first_heap)
>>> merged.peek()
17
values in merged heap; (merge is inplace)
>>> while not first_heap.isEmpty():
... print(first_heap.deleteMin(), end=" ")
17 20 25 26 27 28 29 31 34
"""
def __init__(self, bottom_root=None, min_node=None, heap_size=0):
self.size = heap_size
self.bottom_root = bottom_root
self.min_node = min_node
def mergeHeaps(self, other):
"""
In-place merge of two binomial heaps.
Both of them become the resulting merged heap
"""
# Empty heaps corner cases
if other.size == 0:
return
if self.size == 0:
self.size = other.size
self.bottom_root = other.bottom_root
self.min_node = other.min_node
return
# Update size
self.size = self.size + other.size
# Update min.node
if self.min_node.val > other.min_node.val:
self.min_node = other.min_node
# Merge
# Order roots by left_subtree_size
combined_roots_list = []
i, j = self.bottom_root, other.bottom_root
while i or j:
if i and ((not j) or i.left_tree_size < j.left_tree_size):
combined_roots_list.append((i, True))
i = i.parent
else:
combined_roots_list.append((j, False))
j = j.parent
# Insert links between them
for i in range(len(combined_roots_list) - 1):
if combined_roots_list[i][1] != combined_roots_list[i + 1][1]:
combined_roots_list[i][0].parent = combined_roots_list[i + 1][0]
combined_roots_list[i + 1][0].left = combined_roots_list[i][0]
# Consecutively merge roots with same left_tree_size
i = combined_roots_list[0][0]
while i.parent:
if (
(i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent)
) or (
i.left_tree_size == i.parent.left_tree_size
and i.left_tree_size != i.parent.parent.left_tree_size
):
# Neighbouring Nodes
previous_node = i.left
next_node = i.parent.parent
# Merging trees
i = i.mergeTrees(i.parent)
# Updating links
i.left = previous_node
i.parent = next_node
if previous_node:
previous_node.parent = i
if next_node:
next_node.left = i
else:
i = i.parent
# Updating self.bottom_root
while i.left:
i = i.left
self.bottom_root = i
# Update other
other.size = self.size
other.bottom_root = self.bottom_root
other.min_node = self.min_node
# Return the merged heap
return self
def insert(self, val):
"""
insert a value in the heap
"""
if self.size == 0:
self.bottom_root = Node(val)
self.size = 1
self.min_node = self.bottom_root
else:
# Create new node
new_node = Node(val)
# Update size
self.size += 1
# update min_node
if val < self.min_node.val:
self.min_node = new_node
# Put new_node as a bottom_root in heap
self.bottom_root.left = new_node
new_node.parent = self.bottom_root
self.bottom_root = new_node
# Consecutively merge roots with same left_tree_size
while (
self.bottom_root.parent
and self.bottom_root.left_tree_size
== self.bottom_root.parent.left_tree_size
):
# Next node
next_node = self.bottom_root.parent.parent
# Merge
self.bottom_root = self.bottom_root.mergeTrees(self.bottom_root.parent)
# Update Links
self.bottom_root.parent = next_node
self.bottom_root.left = None
if next_node:
next_node.left = self.bottom_root
def peek(self):
"""
return min element without deleting it
"""
return self.min_node.val
def isEmpty(self):
return self.size == 0
def deleteMin(self):
"""
delete min element and return it
"""
# assert not self.isEmpty(), "Empty Heap"
# Save minimal value
min_value = self.min_node.val
# Last element in heap corner case
if self.size == 1:
# Update size
self.size = 0
# Update bottom root
self.bottom_root = None
# Update min_node
self.min_node = None
return min_value
# No right subtree corner case
# The structure of the tree implies that this should be the bottom root
# and there is at least one other root
if self.min_node.right is None:
# Update size
self.size -= 1
# Update bottom root
self.bottom_root = self.bottom_root.parent
self.bottom_root.left = None
# Update min_node
self.min_node = self.bottom_root
i = self.bottom_root.parent
while i:
if i.val < self.min_node.val:
self.min_node = i
i = i.parent
return min_value
# General case
# Find the BinomialHeap of the right subtree of min_node
bottom_of_new = self.min_node.right
bottom_of_new.parent = None
min_of_new = bottom_of_new
size_of_new = 1
# Size, min_node and bottom_root
while bottom_of_new.left:
size_of_new = size_of_new * 2 + 1
bottom_of_new = bottom_of_new.left
if bottom_of_new.val < min_of_new.val:
min_of_new = bottom_of_new
# Corner case of single root on top left path
if (not self.min_node.left) and (not self.min_node.parent):
self.size = size_of_new
self.bottom_root = bottom_of_new
self.min_node = min_of_new
# print("Single root, multiple nodes case")
return min_value
# Remaining cases
# Construct heap of right subtree
newHeap = BinomialHeap(
bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new
)
# Update size
self.size = self.size - 1 - size_of_new
# Neighbour nodes
previous_node = self.min_node.left
next_node = self.min_node.parent
# Initialize new bottom_root and min_node
self.min_node = previous_node or next_node
self.bottom_root = next_node
# Update links of previous_node and search below for new min_node and
# bottom_root
if previous_node:
previous_node.parent = next_node
# Update bottom_root and search for min_node below
self.bottom_root = previous_node
self.min_node = previous_node
while self.bottom_root.left:
self.bottom_root = self.bottom_root.left
if self.bottom_root.val < self.min_node.val:
self.min_node = self.bottom_root
if next_node:
next_node.left = previous_node
# Search for new min_node above min_node
i = next_node
while i:
if i.val < self.min_node.val:
self.min_node = i
i = i.parent
# Merge heaps
self.mergeHeaps(newHeap)
return min_value
def preOrder(self):
"""
Returns the Pre-order representation of the heap including
values of nodes plus their level distance from the root;
Empty nodes appear as #
"""
# Find top root
top_root = self.bottom_root
while top_root.parent:
top_root = top_root.parent
# preorder
heap_preOrder = []
self.__traversal(top_root, heap_preOrder)
return heap_preOrder
def __traversal(self, curr_node, preorder, level=0):
"""
Pre-order traversal of nodes
"""
if curr_node:
preorder.append((curr_node.val, level))
self.__traversal(curr_node.left, preorder, level + 1)
self.__traversal(curr_node.right, preorder, level + 1)
else:
preorder.append(("#", level))
def __str__(self):
"""
Overwriting str for a pre-order print of nodes in heap;
Performance is poor, so use only for small examples
"""
if self.isEmpty():
return ""
preorder_heap = self.preOrder()
return "\n".join(("-" * level + str(value)) for value, level in preorder_heap)
# Unit Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| # flake8: noqa
"""
Binomial Heap
Reference: Advanced Data Structures, Peter Brass
"""
class Node:
"""
Node in a doubly-linked binomial tree, containing:
- value
- size of left subtree
- link to left, right and parent nodes
"""
def __init__(self, val):
self.val = val
# Number of nodes in left subtree
self.left_tree_size = 0
self.left = None
self.right = None
self.parent = None
def mergeTrees(self, other):
"""
In-place merge of two binomial trees of equal size.
Returns the root of the resulting tree
"""
assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks"
if self.val < other.val:
other.left = self.right
other.parent = None
if self.right:
self.right.parent = other
self.right = other
self.left_tree_size = self.left_tree_size * 2 + 1
return self
else:
self.left = other.right
self.parent = None
if other.right:
other.right.parent = self
other.right = self
other.left_tree_size = other.left_tree_size * 2 + 1
return other
class BinomialHeap:
r"""
Min-oriented priority queue implemented with the Binomial Heap data
structure implemented with the BinomialHeap class. It supports:
- Insert element in a heap with n elements: Guaranteed logn, amoratized 1
- Merge (meld) heaps of size m and n: O(logn + logm)
- Delete Min: O(logn)
- Peek (return min without deleting it): O(1)
Example:
Create a random permutation of 30 integers to be inserted and 19 of them deleted
>>> import numpy as np
>>> permutation = np.random.permutation(list(range(30)))
Create a Heap and insert the 30 integers
__init__() test
>>> first_heap = BinomialHeap()
30 inserts - insert() test
>>> for number in permutation:
... first_heap.insert(number)
Size test
>>> print(first_heap.size)
30
Deleting - delete() test
>>> for i in range(25):
... print(first_heap.deleteMin(), end=" ")
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Create a new Heap
>>> second_heap = BinomialHeap()
>>> vals = [17, 20, 31, 34]
>>> for value in vals:
... second_heap.insert(value)
The heap should have the following structure:
17
/ \
# 31
/ \
20 34
/ \ / \
# # # #
preOrder() test
>>> print(second_heap.preOrder())
[(17, 0), ('#', 1), (31, 1), (20, 2), ('#', 3), ('#', 3), (34, 2), ('#', 3), ('#', 3)]
printing Heap - __str__() test
>>> print(second_heap)
17
-#
-31
--20
---#
---#
--34
---#
---#
mergeHeaps() test
>>> merged = second_heap.mergeHeaps(first_heap)
>>> merged.peek()
17
values in merged heap; (merge is inplace)
>>> while not first_heap.isEmpty():
... print(first_heap.deleteMin(), end=" ")
17 20 25 26 27 28 29 31 34
"""
def __init__(self, bottom_root=None, min_node=None, heap_size=0):
self.size = heap_size
self.bottom_root = bottom_root
self.min_node = min_node
def mergeHeaps(self, other):
"""
In-place merge of two binomial heaps.
Both of them become the resulting merged heap
"""
# Empty heaps corner cases
if other.size == 0:
return
if self.size == 0:
self.size = other.size
self.bottom_root = other.bottom_root
self.min_node = other.min_node
return
# Update size
self.size = self.size + other.size
# Update min.node
if self.min_node.val > other.min_node.val:
self.min_node = other.min_node
# Merge
# Order roots by left_subtree_size
combined_roots_list = []
i, j = self.bottom_root, other.bottom_root
while i or j:
if i and ((not j) or i.left_tree_size < j.left_tree_size):
combined_roots_list.append((i, True))
i = i.parent
else:
combined_roots_list.append((j, False))
j = j.parent
# Insert links between them
for i in range(len(combined_roots_list) - 1):
if combined_roots_list[i][1] != combined_roots_list[i + 1][1]:
combined_roots_list[i][0].parent = combined_roots_list[i + 1][0]
combined_roots_list[i + 1][0].left = combined_roots_list[i][0]
# Consecutively merge roots with same left_tree_size
i = combined_roots_list[0][0]
while i.parent:
if (
(i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent)
) or (
i.left_tree_size == i.parent.left_tree_size
and i.left_tree_size != i.parent.parent.left_tree_size
):
# Neighbouring Nodes
previous_node = i.left
next_node = i.parent.parent
# Merging trees
i = i.mergeTrees(i.parent)
# Updating links
i.left = previous_node
i.parent = next_node
if previous_node:
previous_node.parent = i
if next_node:
next_node.left = i
else:
i = i.parent
# Updating self.bottom_root
while i.left:
i = i.left
self.bottom_root = i
# Update other
other.size = self.size
other.bottom_root = self.bottom_root
other.min_node = self.min_node
# Return the merged heap
return self
def insert(self, val):
"""
insert a value in the heap
"""
if self.size == 0:
self.bottom_root = Node(val)
self.size = 1
self.min_node = self.bottom_root
else:
# Create new node
new_node = Node(val)
# Update size
self.size += 1
# update min_node
if val < self.min_node.val:
self.min_node = new_node
# Put new_node as a bottom_root in heap
self.bottom_root.left = new_node
new_node.parent = self.bottom_root
self.bottom_root = new_node
# Consecutively merge roots with same left_tree_size
while (
self.bottom_root.parent
and self.bottom_root.left_tree_size
== self.bottom_root.parent.left_tree_size
):
# Next node
next_node = self.bottom_root.parent.parent
# Merge
self.bottom_root = self.bottom_root.mergeTrees(self.bottom_root.parent)
# Update Links
self.bottom_root.parent = next_node
self.bottom_root.left = None
if next_node:
next_node.left = self.bottom_root
def peek(self):
"""
return min element without deleting it
"""
return self.min_node.val
def isEmpty(self):
return self.size == 0
def deleteMin(self):
"""
delete min element and return it
"""
# assert not self.isEmpty(), "Empty Heap"
# Save minimal value
min_value = self.min_node.val
# Last element in heap corner case
if self.size == 1:
# Update size
self.size = 0
# Update bottom root
self.bottom_root = None
# Update min_node
self.min_node = None
return min_value
# No right subtree corner case
# The structure of the tree implies that this should be the bottom root
# and there is at least one other root
if self.min_node.right is None:
# Update size
self.size -= 1
# Update bottom root
self.bottom_root = self.bottom_root.parent
self.bottom_root.left = None
# Update min_node
self.min_node = self.bottom_root
i = self.bottom_root.parent
while i:
if i.val < self.min_node.val:
self.min_node = i
i = i.parent
return min_value
# General case
# Find the BinomialHeap of the right subtree of min_node
bottom_of_new = self.min_node.right
bottom_of_new.parent = None
min_of_new = bottom_of_new
size_of_new = 1
# Size, min_node and bottom_root
while bottom_of_new.left:
size_of_new = size_of_new * 2 + 1
bottom_of_new = bottom_of_new.left
if bottom_of_new.val < min_of_new.val:
min_of_new = bottom_of_new
# Corner case of single root on top left path
if (not self.min_node.left) and (not self.min_node.parent):
self.size = size_of_new
self.bottom_root = bottom_of_new
self.min_node = min_of_new
# print("Single root, multiple nodes case")
return min_value
# Remaining cases
# Construct heap of right subtree
newHeap = BinomialHeap(
bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new
)
# Update size
self.size = self.size - 1 - size_of_new
# Neighbour nodes
previous_node = self.min_node.left
next_node = self.min_node.parent
# Initialize new bottom_root and min_node
self.min_node = previous_node or next_node
self.bottom_root = next_node
# Update links of previous_node and search below for new min_node and
# bottom_root
if previous_node:
previous_node.parent = next_node
# Update bottom_root and search for min_node below
self.bottom_root = previous_node
self.min_node = previous_node
while self.bottom_root.left:
self.bottom_root = self.bottom_root.left
if self.bottom_root.val < self.min_node.val:
self.min_node = self.bottom_root
if next_node:
next_node.left = previous_node
# Search for new min_node above min_node
i = next_node
while i:
if i.val < self.min_node.val:
self.min_node = i
i = i.parent
# Merge heaps
self.mergeHeaps(newHeap)
return min_value
def preOrder(self):
"""
Returns the Pre-order representation of the heap including
values of nodes plus their level distance from the root;
Empty nodes appear as #
"""
# Find top root
top_root = self.bottom_root
while top_root.parent:
top_root = top_root.parent
# preorder
heap_preOrder = []
self.__traversal(top_root, heap_preOrder)
return heap_preOrder
def __traversal(self, curr_node, preorder, level=0):
"""
Pre-order traversal of nodes
"""
if curr_node:
preorder.append((curr_node.val, level))
self.__traversal(curr_node.left, preorder, level + 1)
self.__traversal(curr_node.right, preorder, level + 1)
else:
preorder.append(("#", level))
def __str__(self):
"""
Overwriting str for a pre-order print of nodes in heap;
Performance is poor, so use only for small examples
"""
if self.isEmpty():
return ""
preorder_heap = self.preOrder()
return "\n".join(("-" * level + str(value)) for value, level in preorder_heap)
# Unit Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The convex hull problem is problem of finding all the vertices of convex polygon, P of
a set of points in a plane such that all the points are either on the vertices of P or
inside P. TH convex hull problem has several applications in geometrical problems,
computer graphics and game development.
Two algorithms have been implemented for the convex hull problem here.
1. A brute-force algorithm which runs in O(n^3)
2. A divide-and-conquer algorithm which runs in O(n log(n))
There are other several other algorithms for the convex hull problem
which have not been implemented here, yet.
"""
from typing import Iterable, List, Set, Union
class Point:
"""
Defines a 2-d point for use by all convex-hull algorithms.
Parameters
----------
x: an int or a float, the x-coordinate of the 2-d point
y: an int or a float, the y-coordinate of the 2-d point
Examples
--------
>>> Point(1, 2)
(1.0, 2.0)
>>> Point("1", "2")
(1.0, 2.0)
>>> Point(1, 2) > Point(0, 1)
True
>>> Point(1, 1) == Point(1, 1)
True
>>> Point(-0.5, 1) == Point(0.5, 1)
False
>>> Point("pi", "e")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'pi'
"""
def __init__(self, x, y):
self.x, self.y = float(x), float(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False
def __lt__(self, other):
return not self > other
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False
def __repr__(self):
return f"({self.x}, {self.y})"
def __hash__(self):
return hash(self.x)
def _construct_points(
list_of_tuples: Union[List[Point], List[List[float]], Iterable[List[float]]]
) -> List[Point]:
"""
constructs a list of points from an array-like object of numbers
Arguments
---------
list_of_tuples: array-like object of type numbers. Acceptable types so far
are lists, tuples and sets.
Returns
--------
points: a list where each item is of type Point. This contains only objects
which can be converted into a Point.
Examples
-------
>>> _construct_points([[1, 1], [2, -1], [0.3, 4]])
[(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)]
>>> _construct_points([1, 2])
Ignoring deformed point 1. All points must have at least 2 coordinates.
Ignoring deformed point 2. All points must have at least 2 coordinates.
[]
>>> _construct_points([])
[]
>>> _construct_points(None)
[]
"""
points: List[Point] = []
if list_of_tuples:
for p in list_of_tuples:
if isinstance(p, Point):
points.append(p)
else:
try:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print(
f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates."
)
return points
def _validate_input(points: Union[List[Point], List[List[float]]]) -> List[Point]:
"""
validates an input instance before a convex-hull algorithms uses it
Parameters
---------
points: array-like, the 2d points to validate before using with
a convex-hull algorithm. The elements of points must be either lists, tuples or
Points.
Returns
-------
points: array_like, an iterable of all well-defined Points constructed passed in.
Exception
---------
ValueError: if points is empty or None, or if a wrong data structure like a scalar
is passed
TypeError: if an iterable but non-indexable object (eg. dictionary) is passed.
The exception to this a set which we'll convert to a list before using
Examples
-------
>>> _validate_input([[1, 2]])
[(1.0, 2.0)]
>>> _validate_input([(1, 2)])
[(1.0, 2.0)]
>>> _validate_input([Point(2, 1), Point(-1, 2)])
[(2.0, 1.0), (-1.0, 2.0)]
>>> _validate_input([])
Traceback (most recent call last):
...
ValueError: Expecting a list of points but got []
>>> _validate_input(1)
Traceback (most recent call last):
...
ValueError: Expecting an iterable object but got an non-iterable type 1
"""
if not hasattr(points, "__iter__"):
raise ValueError(
f"Expecting an iterable object but got an non-iterable type {points}"
)
if not points:
raise ValueError(f"Expecting a list of points but got {points}")
return _construct_points(points)
def _det(a: Point, b: Point, c: Point) -> float:
"""
Computes the sign perpendicular distance of a 2d point c from a line segment
ab. The sign indicates the direction of c relative to ab.
A Positive value means c is above ab (to the left), while a negative value
means c is below ab (to the right). 0 means all three points are on a straight line.
As a side note, 0.5 * abs|det| is the area of triangle abc
Parameters
----------
a: point, the point on the left end of line segment ab
b: point, the point on the right end of line segment ab
c: point, the point for which the direction and location is desired.
Returns
--------
det: float, abs(det) is the distance of c from ab. The sign
indicates which side of line segment ab c is. det is computed as
(a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x)
Examples
----------
>>> _det(Point(1, 1), Point(1, 2), Point(1, 5))
0.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, 10))
100.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, -10))
-100.0
"""
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det
def convex_hull_bf(points: List[Point]) -> List[Point]:
"""
Constructs the convex hull of a set of 2D points using a brute force algorithm.
The algorithm basically considers all combinations of points (i, j) and uses the
definition of convexity to determine whether (i, j) is part of the convex hull or
not. (i, j) is part of the convex hull if and only iff there are no points on both
sides of the line segment connecting the ij, and there is no point k such that k is
on either end of the ij.
Runtime: O(n^3) - definitely horrible
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
convex_hull_recursive,
Examples
---------
>>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n - 1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
for k in range(n):
if k != i and k != j:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
else:
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
if points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set)
def convex_hull_recursive(points: List[Point]) -> List[Point]:
"""
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
The algorithm exploits the geometric properties of the problem by repeatedly
partitioning the set of points into smaller hulls, and finding the convex hull of
these smaller hulls. The union of the convex hull from smaller hulls is the
solution to the convex hull of the larger problem.
Parameter
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Runtime: O(n log n)
Returns
-------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
Examples
---------
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
# divide all the points into an upper hull and a lower hull
# the left most point and the right most point are definitely
# members of the convex hull by definition.
# use these two anchors to divide all the points into two hulls,
# an upper hull and a lower hull.
# all points to the left (above) the line joining the extreme points belong to the
# upper hull
# all points to the right (below) the line joining the extreme points below to the
# lower hull
# ignore all points on the line joining the extreme points since they cannot be
# part of the convex hull
left_most_point = points[0]
right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point}
upper_hull = []
lower_hull = []
for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upper_hull.append(points[i])
elif det < 0:
lower_hull.append(points[i])
_construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set)
def _construct_hull(
points: List[Point], left: Point, right: Point, convex_set: Set[Point]
) -> None:
"""
Parameters
---------
points: list or None, the hull of points from which to choose the next convex-hull
point
left: Point, the point to the left of line segment joining left and right
right: The point to the right of the line segment joining left and right
convex_set: set, the current convex-hull. The state of convex-set gets updated by
this function
Note
----
For the line segment 'ab', 'a' is on the left and 'b' on the right.
but the reverse is true for the line segment 'ba'.
Returns
-------
Nothing, only updates the state of convex-set
"""
if points:
extreme_point = None
extreme_point_distance = float("-inf")
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set)
def convex_hull_melkman(points: List[Point]) -> List[Point]:
"""
Constructs the convex hull of a set of 2D points using the melkman algorithm.
The algorithm works by iteratively inserting points of a simple polygonal chain
(meaning that no line segments between two consecutive points cross each other).
Sorting the points yields such a polygonal chain.
For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html
Runtime: O(n log n) - O(n) if points are already sorted in the input
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
Examples
---------
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_hull = points[:2]
for i in range(2, n):
det = _det(convex_hull[1], convex_hull[0], points[i])
if det > 0:
convex_hull.insert(0, points[i])
break
elif det < 0:
convex_hull.append(points[i])
break
else:
convex_hull[1] = points[i]
i += 1
for i in range(i, n):
if (
_det(convex_hull[0], convex_hull[-1], points[i]) > 0
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
):
# The point lies within the convex hull
continue
convex_hull.insert(0, points[i])
convex_hull.append(points[i])
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
del convex_hull[1]
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
del convex_hull[-2]
# `convex_hull` is contains the convex hull in circular order
return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull)
def main():
points = [
(0, 3),
(2, 2),
(1, 1),
(2, 1),
(3, 0),
(0, 0),
(3, 3),
(2, -1),
(2, -4),
(1, -3),
]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_bf = convex_hull_bf(points)
results_recursive = convex_hull_recursive(points)
assert results_bf == results_recursive
results_melkman = convex_hull_melkman(points)
assert results_bf == results_melkman
print(results_bf)
if __name__ == "__main__":
main()
| """
The convex hull problem is problem of finding all the vertices of convex polygon, P of
a set of points in a plane such that all the points are either on the vertices of P or
inside P. TH convex hull problem has several applications in geometrical problems,
computer graphics and game development.
Two algorithms have been implemented for the convex hull problem here.
1. A brute-force algorithm which runs in O(n^3)
2. A divide-and-conquer algorithm which runs in O(n log(n))
There are other several other algorithms for the convex hull problem
which have not been implemented here, yet.
"""
from typing import Iterable, List, Set, Union
class Point:
"""
Defines a 2-d point for use by all convex-hull algorithms.
Parameters
----------
x: an int or a float, the x-coordinate of the 2-d point
y: an int or a float, the y-coordinate of the 2-d point
Examples
--------
>>> Point(1, 2)
(1.0, 2.0)
>>> Point("1", "2")
(1.0, 2.0)
>>> Point(1, 2) > Point(0, 1)
True
>>> Point(1, 1) == Point(1, 1)
True
>>> Point(-0.5, 1) == Point(0.5, 1)
False
>>> Point("pi", "e")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'pi'
"""
def __init__(self, x, y):
self.x, self.y = float(x), float(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False
def __lt__(self, other):
return not self > other
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False
def __repr__(self):
return f"({self.x}, {self.y})"
def __hash__(self):
return hash(self.x)
def _construct_points(
list_of_tuples: Union[List[Point], List[List[float]], Iterable[List[float]]]
) -> List[Point]:
"""
constructs a list of points from an array-like object of numbers
Arguments
---------
list_of_tuples: array-like object of type numbers. Acceptable types so far
are lists, tuples and sets.
Returns
--------
points: a list where each item is of type Point. This contains only objects
which can be converted into a Point.
Examples
-------
>>> _construct_points([[1, 1], [2, -1], [0.3, 4]])
[(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)]
>>> _construct_points([1, 2])
Ignoring deformed point 1. All points must have at least 2 coordinates.
Ignoring deformed point 2. All points must have at least 2 coordinates.
[]
>>> _construct_points([])
[]
>>> _construct_points(None)
[]
"""
points: List[Point] = []
if list_of_tuples:
for p in list_of_tuples:
if isinstance(p, Point):
points.append(p)
else:
try:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print(
f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates."
)
return points
def _validate_input(points: Union[List[Point], List[List[float]]]) -> List[Point]:
"""
validates an input instance before a convex-hull algorithms uses it
Parameters
---------
points: array-like, the 2d points to validate before using with
a convex-hull algorithm. The elements of points must be either lists, tuples or
Points.
Returns
-------
points: array_like, an iterable of all well-defined Points constructed passed in.
Exception
---------
ValueError: if points is empty or None, or if a wrong data structure like a scalar
is passed
TypeError: if an iterable but non-indexable object (eg. dictionary) is passed.
The exception to this a set which we'll convert to a list before using
Examples
-------
>>> _validate_input([[1, 2]])
[(1.0, 2.0)]
>>> _validate_input([(1, 2)])
[(1.0, 2.0)]
>>> _validate_input([Point(2, 1), Point(-1, 2)])
[(2.0, 1.0), (-1.0, 2.0)]
>>> _validate_input([])
Traceback (most recent call last):
...
ValueError: Expecting a list of points but got []
>>> _validate_input(1)
Traceback (most recent call last):
...
ValueError: Expecting an iterable object but got an non-iterable type 1
"""
if not hasattr(points, "__iter__"):
raise ValueError(
f"Expecting an iterable object but got an non-iterable type {points}"
)
if not points:
raise ValueError(f"Expecting a list of points but got {points}")
return _construct_points(points)
def _det(a: Point, b: Point, c: Point) -> float:
"""
Computes the sign perpendicular distance of a 2d point c from a line segment
ab. The sign indicates the direction of c relative to ab.
A Positive value means c is above ab (to the left), while a negative value
means c is below ab (to the right). 0 means all three points are on a straight line.
As a side note, 0.5 * abs|det| is the area of triangle abc
Parameters
----------
a: point, the point on the left end of line segment ab
b: point, the point on the right end of line segment ab
c: point, the point for which the direction and location is desired.
Returns
--------
det: float, abs(det) is the distance of c from ab. The sign
indicates which side of line segment ab c is. det is computed as
(a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x)
Examples
----------
>>> _det(Point(1, 1), Point(1, 2), Point(1, 5))
0.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, 10))
100.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, -10))
-100.0
"""
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det
def convex_hull_bf(points: List[Point]) -> List[Point]:
"""
Constructs the convex hull of a set of 2D points using a brute force algorithm.
The algorithm basically considers all combinations of points (i, j) and uses the
definition of convexity to determine whether (i, j) is part of the convex hull or
not. (i, j) is part of the convex hull if and only iff there are no points on both
sides of the line segment connecting the ij, and there is no point k such that k is
on either end of the ij.
Runtime: O(n^3) - definitely horrible
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
convex_hull_recursive,
Examples
---------
>>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n - 1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
for k in range(n):
if k != i and k != j:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
else:
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
if points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set)
def convex_hull_recursive(points: List[Point]) -> List[Point]:
"""
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
The algorithm exploits the geometric properties of the problem by repeatedly
partitioning the set of points into smaller hulls, and finding the convex hull of
these smaller hulls. The union of the convex hull from smaller hulls is the
solution to the convex hull of the larger problem.
Parameter
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Runtime: O(n log n)
Returns
-------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
Examples
---------
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
# divide all the points into an upper hull and a lower hull
# the left most point and the right most point are definitely
# members of the convex hull by definition.
# use these two anchors to divide all the points into two hulls,
# an upper hull and a lower hull.
# all points to the left (above) the line joining the extreme points belong to the
# upper hull
# all points to the right (below) the line joining the extreme points below to the
# lower hull
# ignore all points on the line joining the extreme points since they cannot be
# part of the convex hull
left_most_point = points[0]
right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point}
upper_hull = []
lower_hull = []
for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upper_hull.append(points[i])
elif det < 0:
lower_hull.append(points[i])
_construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set)
def _construct_hull(
points: List[Point], left: Point, right: Point, convex_set: Set[Point]
) -> None:
"""
Parameters
---------
points: list or None, the hull of points from which to choose the next convex-hull
point
left: Point, the point to the left of line segment joining left and right
right: The point to the right of the line segment joining left and right
convex_set: set, the current convex-hull. The state of convex-set gets updated by
this function
Note
----
For the line segment 'ab', 'a' is on the left and 'b' on the right.
but the reverse is true for the line segment 'ba'.
Returns
-------
Nothing, only updates the state of convex-set
"""
if points:
extreme_point = None
extreme_point_distance = float("-inf")
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set)
def convex_hull_melkman(points: List[Point]) -> List[Point]:
"""
Constructs the convex hull of a set of 2D points using the melkman algorithm.
The algorithm works by iteratively inserting points of a simple polygonal chain
(meaning that no line segments between two consecutive points cross each other).
Sorting the points yields such a polygonal chain.
For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html
Runtime: O(n log n) - O(n) if points are already sorted in the input
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
Examples
---------
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_hull = points[:2]
for i in range(2, n):
det = _det(convex_hull[1], convex_hull[0], points[i])
if det > 0:
convex_hull.insert(0, points[i])
break
elif det < 0:
convex_hull.append(points[i])
break
else:
convex_hull[1] = points[i]
i += 1
for i in range(i, n):
if (
_det(convex_hull[0], convex_hull[-1], points[i]) > 0
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
):
# The point lies within the convex hull
continue
convex_hull.insert(0, points[i])
convex_hull.append(points[i])
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
del convex_hull[1]
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
del convex_hull[-2]
# `convex_hull` is contains the convex hull in circular order
return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull)
def main():
points = [
(0, 3),
(2, 2),
(1, 1),
(2, 1),
(3, 0),
(0, 0),
(3, 3),
(2, -1),
(2, -4),
(1, -3),
]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_bf = convex_hull_bf(points)
results_recursive = convex_hull_recursive(points)
assert results_bf == results_recursive
results_melkman = convex_hull_melkman(points)
assert results_bf == results_melkman
print(results_bf)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import math
class SegmentTree:
def __init__(self, A):
self.N = len(A)
self.st = [0] * (
4 * self.N
) # approximate the overall size of segment tree with array N
self.build(1, 0, self.N - 1)
def left(self, idx):
return idx * 2
def right(self, idx):
return idx * 2 + 1
def build(self, idx, l, r): # noqa: E741
if l == r: # noqa: E741
self.st[idx] = A[l]
else:
mid = (l + r) // 2
self.build(self.left(idx), l, mid)
self.build(self.right(idx), mid + 1, r)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
def update(self, a, b, val):
return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)
def update_recursive(self, idx, l, r, a, b, val): # noqa: E741
"""
update(1, 1, N, a, b, v) for update val v to [a,b]
"""
if r < a or l > b:
return True
if l == r: # noqa: E741
self.st[idx] = val
return True
mid = (l + r) // 2
self.update_recursive(self.left(idx), l, mid, a, b, val)
self.update_recursive(self.right(idx), mid + 1, r, a, b, val)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
return True
def query(self, a, b):
return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1)
def query_recursive(self, idx, l, r, a, b): # noqa: E741
"""
query(1, 1, N, a, b) for query max of [a,b]
"""
if r < a or l > b:
return -math.inf
if l >= a and r <= b: # noqa: E741
return self.st[idx]
mid = (l + r) // 2
q1 = self.query_recursive(self.left(idx), l, mid, a, b)
q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b)
return max(q1, q2)
def showData(self):
showList = []
for i in range(1, N + 1):
showList += [self.query(i, i)]
print(showList)
if __name__ == "__main__":
A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
N = 15
segt = SegmentTree(A)
print(segt.query(4, 6))
print(segt.query(7, 11))
print(segt.query(7, 12))
segt.update(1, 3, 111)
print(segt.query(1, 15))
segt.update(7, 8, 235)
segt.showData()
| import math
class SegmentTree:
def __init__(self, A):
self.N = len(A)
self.st = [0] * (
4 * self.N
) # approximate the overall size of segment tree with array N
self.build(1, 0, self.N - 1)
def left(self, idx):
return idx * 2
def right(self, idx):
return idx * 2 + 1
def build(self, idx, l, r): # noqa: E741
if l == r: # noqa: E741
self.st[idx] = A[l]
else:
mid = (l + r) // 2
self.build(self.left(idx), l, mid)
self.build(self.right(idx), mid + 1, r)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
def update(self, a, b, val):
return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)
def update_recursive(self, idx, l, r, a, b, val): # noqa: E741
"""
update(1, 1, N, a, b, v) for update val v to [a,b]
"""
if r < a or l > b:
return True
if l == r: # noqa: E741
self.st[idx] = val
return True
mid = (l + r) // 2
self.update_recursive(self.left(idx), l, mid, a, b, val)
self.update_recursive(self.right(idx), mid + 1, r, a, b, val)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
return True
def query(self, a, b):
return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1)
def query_recursive(self, idx, l, r, a, b): # noqa: E741
"""
query(1, 1, N, a, b) for query max of [a,b]
"""
if r < a or l > b:
return -math.inf
if l >= a and r <= b: # noqa: E741
return self.st[idx]
mid = (l + r) // 2
q1 = self.query_recursive(self.left(idx), l, mid, a, b)
q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b)
return max(q1, q2)
def showData(self):
showList = []
for i in range(1, N + 1):
showList += [self.query(i, i)]
print(showList)
if __name__ == "__main__":
A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
N = 15
segt = SegmentTree(A)
print(segt.query(4, 6))
print(segt.query(7, 11))
print(segt.query(7, 12))
segt.update(1, 3, 111)
print(segt.query(1, 15))
segt.update(7, 8, 235)
segt.showData()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In this problem, we want to rotate the matrix elements by 90, 180, 270
(counterclockwise)
Discussion in stackoverflow:
https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
"""
from __future__ import annotations
def make_matrix(row_size: int = 4) -> list[list]:
"""
>>> make_matrix()
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> make_matrix(1)
[[1]]
>>> make_matrix(-2)
[[1, 2], [3, 4]]
>>> make_matrix(3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> make_matrix() == make_matrix(4)
True
"""
row_size = abs(row_size) or 4
return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)]
def rotate_90(matrix: list[list]) -> list[list]:
"""
>>> rotate_90(make_matrix())
[[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]
>>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix()))
True
"""
return reverse_row(transpose(matrix))
# OR.. transpose(reverse_column(matrix))
def rotate_180(matrix: list[list]) -> list[list]:
"""
>>> rotate_180(make_matrix())
[[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]]
>>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix()))
True
"""
return reverse_row(reverse_column(matrix))
# OR.. reverse_column(reverse_row(matrix))
def rotate_270(matrix: list[list]) -> list[list]:
"""
>>> rotate_270(make_matrix())
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
>>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix()))
True
"""
return reverse_column(transpose(matrix))
# OR.. transpose(reverse_row(matrix))
def transpose(matrix: list[list]) -> list[list]:
matrix[:] = [list(x) for x in zip(*matrix)]
return matrix
def reverse_row(matrix: list[list]) -> list[list]:
matrix[:] = matrix[::-1]
return matrix
def reverse_column(matrix: list[list]) -> list[list]:
matrix[:] = [x[::-1] for x in matrix]
return matrix
def print_matrix(matrix: list[list]) -> None:
for i in matrix:
print(*i)
if __name__ == "__main__":
matrix = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 90 counterclockwise:\n")
print_matrix(rotate_90(matrix))
matrix = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 180:\n")
print_matrix(rotate_180(matrix))
matrix = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 270 counterclockwise:\n")
print_matrix(rotate_270(matrix))
| """
In this problem, we want to rotate the matrix elements by 90, 180, 270
(counterclockwise)
Discussion in stackoverflow:
https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
"""
from __future__ import annotations
def make_matrix(row_size: int = 4) -> list[list]:
"""
>>> make_matrix()
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> make_matrix(1)
[[1]]
>>> make_matrix(-2)
[[1, 2], [3, 4]]
>>> make_matrix(3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> make_matrix() == make_matrix(4)
True
"""
row_size = abs(row_size) or 4
return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)]
def rotate_90(matrix: list[list]) -> list[list]:
"""
>>> rotate_90(make_matrix())
[[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]
>>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix()))
True
"""
return reverse_row(transpose(matrix))
# OR.. transpose(reverse_column(matrix))
def rotate_180(matrix: list[list]) -> list[list]:
"""
>>> rotate_180(make_matrix())
[[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]]
>>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix()))
True
"""
return reverse_row(reverse_column(matrix))
# OR.. reverse_column(reverse_row(matrix))
def rotate_270(matrix: list[list]) -> list[list]:
"""
>>> rotate_270(make_matrix())
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
>>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix()))
True
"""
return reverse_column(transpose(matrix))
# OR.. transpose(reverse_row(matrix))
def transpose(matrix: list[list]) -> list[list]:
matrix[:] = [list(x) for x in zip(*matrix)]
return matrix
def reverse_row(matrix: list[list]) -> list[list]:
matrix[:] = matrix[::-1]
return matrix
def reverse_column(matrix: list[list]) -> list[list]:
matrix[:] = [x[::-1] for x in matrix]
return matrix
def print_matrix(matrix: list[list]) -> None:
for i in matrix:
print(*i)
if __name__ == "__main__":
matrix = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 90 counterclockwise:\n")
print_matrix(rotate_90(matrix))
matrix = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 180:\n")
print_matrix(rotate_180(matrix))
matrix = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 270 counterclockwise:\n")
print_matrix(rotate_270(matrix))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # https://en.wikipedia.org/wiki/Continuous_knapsack_problem
# https://www.guru99.com/fractional-knapsack-problem-greedy.html
# https://medium.com/walkinthecode/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93
from __future__ import annotations
def fractional_knapsack(
value: list[int], weight: list[int], capacity: int
) -> tuple[int, list[int]]:
"""
>>> value = [1, 3, 5, 7, 9]
>>> weight = [0.9, 0.7, 0.5, 0.3, 0.1]
>>> fractional_knapsack(value, weight, 5)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, 15)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, 25)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, 26)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, -1)
(-90.0, [0, 0, 0, 0, -10.0])
>>> fractional_knapsack([1, 3, 5, 7], weight, 30)
(16, [1, 1, 1, 1])
>>> fractional_knapsack(value, [0.9, 0.7, 0.5, 0.3, 0.1], 30)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack([], [], 30)
(0, [])
"""
index = list(range(len(value)))
ratio = [v / w for v, w in zip(value, weight)]
index.sort(key=lambda i: ratio[i], reverse=True)
max_value = 0
fractions = [0] * len(value)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += value[i]
capacity -= weight[i]
else:
fractions[i] = capacity / weight[i]
max_value += value[i] * capacity / weight[i]
break
return max_value, fractions
if __name__ == "__main__":
n = int(input("Enter number of items: "))
value = input(f"Enter the values of the {n} item(s) in order: ").split()
value = [int(v) for v in value]
weight = input(f"Enter the positive weights of the {n} item(s) in order: ".split())
weight = [int(w) for w in weight]
capacity = int(input("Enter maximum weight: "))
max_value, fractions = fractional_knapsack(value, weight, capacity)
print("The maximum value of items that can be carried:", max_value)
print("The fractions in which the items should be taken:", fractions)
| # https://en.wikipedia.org/wiki/Continuous_knapsack_problem
# https://www.guru99.com/fractional-knapsack-problem-greedy.html
# https://medium.com/walkinthecode/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93
from __future__ import annotations
def fractional_knapsack(
value: list[int], weight: list[int], capacity: int
) -> tuple[int, list[int]]:
"""
>>> value = [1, 3, 5, 7, 9]
>>> weight = [0.9, 0.7, 0.5, 0.3, 0.1]
>>> fractional_knapsack(value, weight, 5)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, 15)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, 25)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, 26)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack(value, weight, -1)
(-90.0, [0, 0, 0, 0, -10.0])
>>> fractional_knapsack([1, 3, 5, 7], weight, 30)
(16, [1, 1, 1, 1])
>>> fractional_knapsack(value, [0.9, 0.7, 0.5, 0.3, 0.1], 30)
(25, [1, 1, 1, 1, 1])
>>> fractional_knapsack([], [], 30)
(0, [])
"""
index = list(range(len(value)))
ratio = [v / w for v, w in zip(value, weight)]
index.sort(key=lambda i: ratio[i], reverse=True)
max_value = 0
fractions = [0] * len(value)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += value[i]
capacity -= weight[i]
else:
fractions[i] = capacity / weight[i]
max_value += value[i] * capacity / weight[i]
break
return max_value, fractions
if __name__ == "__main__":
n = int(input("Enter number of items: "))
value = input(f"Enter the values of the {n} item(s) in order: ").split()
value = [int(v) for v in value]
weight = input(f"Enter the positive weights of the {n} item(s) in order: ".split())
weight = [int(w) for w in weight]
capacity = int(input("Enter maximum weight: "))
max_value, fractions = fractional_knapsack(value, weight, capacity)
print("The maximum value of items that can be carried:", max_value)
print("The fractions in which the items should be taken:", fractions)
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import math
def perfect_square(num: int) -> bool:
"""
Check if a number is perfect square number or not
:param num: the number to be checked
:return: True if number is square number, otherwise False
>>> perfect_square(9)
True
>>> perfect_square(16)
True
>>> perfect_square(1)
True
>>> perfect_square(0)
True
>>> perfect_square(10)
False
"""
return math.sqrt(num) * math.sqrt(num) == num
def perfect_square_binary_search(n: int) -> bool:
"""
Check if a number is perfect square using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)
>>> perfect_square_binary_search(9)
True
>>> perfect_square_binary_search(16)
True
>>> perfect_square_binary_search(1)
True
>>> perfect_square_binary_search(0)
True
>>> perfect_square_binary_search(10)
False
>>> perfect_square_binary_search(-1)
False
>>> perfect_square_binary_search(1.1)
False
>>> perfect_square_binary_search("a")
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> perfect_square_binary_search(None)
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'NoneType'
>>> perfect_square_binary_search([])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
left = 0
right = n
while left <= right:
mid = (left + right) // 2
if mid ** 2 == n:
return True
elif mid ** 2 > n:
right = mid - 1
else:
left = mid + 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| import math
def perfect_square(num: int) -> bool:
"""
Check if a number is perfect square number or not
:param num: the number to be checked
:return: True if number is square number, otherwise False
>>> perfect_square(9)
True
>>> perfect_square(16)
True
>>> perfect_square(1)
True
>>> perfect_square(0)
True
>>> perfect_square(10)
False
"""
return math.sqrt(num) * math.sqrt(num) == num
def perfect_square_binary_search(n: int) -> bool:
"""
Check if a number is perfect square using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)
>>> perfect_square_binary_search(9)
True
>>> perfect_square_binary_search(16)
True
>>> perfect_square_binary_search(1)
True
>>> perfect_square_binary_search(0)
True
>>> perfect_square_binary_search(10)
False
>>> perfect_square_binary_search(-1)
False
>>> perfect_square_binary_search(1.1)
False
>>> perfect_square_binary_search("a")
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> perfect_square_binary_search(None)
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'NoneType'
>>> perfect_square_binary_search([])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
left = 0
right = n
while left <= right:
mid = (left + right) // 2
if mid ** 2 == n:
return True
elif mid ** 2 > n:
right = mid - 1
else:
left = mid + 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Hey, we are going to find an exciting number called Catalan number which is use to find
the number of possible binary search trees from tree of a given number of nodes.
We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i)
Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number
"""
"""
Our Contribution:
Basically we Create the 2 function:
1. catalan_number(node_count: int) -> int
Returns the number of possible binary search trees for n nodes.
2. binary_tree_count(node_count: int) -> int
Returns the number of possible binary trees for n nodes.
"""
def binomial_coefficient(n: int, k: int) -> int:
"""
Since Here we Find the Binomial Coefficient:
https://en.wikipedia.org/wiki/Binomial_coefficient
C(n,k) = n! / k!(n-k)!
:param n: 2 times of Number of nodes
:param k: Number of nodes
:return: Integer Value
>>> binomial_coefficient(4, 2)
6
"""
result = 1 # To kept the Calculated Value
# Since C(n, k) = C(n, n-k)
if k > (n - k):
k = n - k
# Calculate C(n,k)
for i in range(k):
result *= n - i
result //= i + 1
return result
def catalan_number(node_count: int) -> int:
"""
We can find Catalan number many ways but here we use Binomial Coefficient because it
does the job in O(n)
return the Catalan number of n using 2nCn/(n+1).
:param n: number of nodes
:return: Catalan number of n nodes
>>> catalan_number(5)
42
>>> catalan_number(6)
132
"""
return binomial_coefficient(2 * node_count, node_count) // (node_count + 1)
def factorial(n: int) -> int:
"""
Return the factorial of a number.
:param n: Number to find the Factorial of.
:return: Factorial of n.
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(10))
True
>>> factorial(-5) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: factorial() not defined for negative values
"""
if n < 0:
raise ValueError("factorial() not defined for negative values")
result = 1
for i in range(1, n + 1):
result *= i
return result
def binary_tree_count(node_count: int) -> int:
"""
Return the number of possible of binary trees.
:param n: number of nodes
:return: Number of possible binary trees
>>> binary_tree_count(5)
5040
>>> binary_tree_count(6)
95040
"""
return catalan_number(node_count) * factorial(node_count)
if __name__ == "__main__":
node_count = int(input("Enter the number of nodes: ").strip() or 0)
if node_count <= 0:
raise ValueError("We need some nodes to work with.")
print(
f"Given {node_count} nodes, there are {binary_tree_count(node_count)} "
f"binary trees and {catalan_number(node_count)} binary search trees."
)
| """
Hey, we are going to find an exciting number called Catalan number which is use to find
the number of possible binary search trees from tree of a given number of nodes.
We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i)
Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number
"""
"""
Our Contribution:
Basically we Create the 2 function:
1. catalan_number(node_count: int) -> int
Returns the number of possible binary search trees for n nodes.
2. binary_tree_count(node_count: int) -> int
Returns the number of possible binary trees for n nodes.
"""
def binomial_coefficient(n: int, k: int) -> int:
"""
Since Here we Find the Binomial Coefficient:
https://en.wikipedia.org/wiki/Binomial_coefficient
C(n,k) = n! / k!(n-k)!
:param n: 2 times of Number of nodes
:param k: Number of nodes
:return: Integer Value
>>> binomial_coefficient(4, 2)
6
"""
result = 1 # To kept the Calculated Value
# Since C(n, k) = C(n, n-k)
if k > (n - k):
k = n - k
# Calculate C(n,k)
for i in range(k):
result *= n - i
result //= i + 1
return result
def catalan_number(node_count: int) -> int:
"""
We can find Catalan number many ways but here we use Binomial Coefficient because it
does the job in O(n)
return the Catalan number of n using 2nCn/(n+1).
:param n: number of nodes
:return: Catalan number of n nodes
>>> catalan_number(5)
42
>>> catalan_number(6)
132
"""
return binomial_coefficient(2 * node_count, node_count) // (node_count + 1)
def factorial(n: int) -> int:
"""
Return the factorial of a number.
:param n: Number to find the Factorial of.
:return: Factorial of n.
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(10))
True
>>> factorial(-5) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: factorial() not defined for negative values
"""
if n < 0:
raise ValueError("factorial() not defined for negative values")
result = 1
for i in range(1, n + 1):
result *= i
return result
def binary_tree_count(node_count: int) -> int:
"""
Return the number of possible of binary trees.
:param n: number of nodes
:return: Number of possible binary trees
>>> binary_tree_count(5)
5040
>>> binary_tree_count(6)
95040
"""
return catalan_number(node_count) * factorial(node_count)
if __name__ == "__main__":
node_count = int(input("Enter the number of nodes: ").strip() or 0)
if node_count <= 0:
raise ValueError("We need some nodes to work with.")
print(
f"Given {node_count} nodes, there are {binary_tree_count(node_count)} "
f"binary trees and {catalan_number(node_count)} binary search trees."
)
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Heap's algorithm returns the list of all permutations possible from a list.
It minimizes movement by generating each permutation from the previous one
by swapping only two elements.
More information:
https://en.wikipedia.org/wiki/Heap%27s_algorithm.
"""
def heaps(arr: list) -> list:
"""
Pure python implementation of the Heap's algorithm (recursive version),
returning all permutations of a list.
>>> heaps([])
[()]
>>> heaps([0])
[(0,)]
>>> heaps([-1, 1])
[(-1, 1), (1, -1)]
>>> heaps([1, 2, 3])
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]
>>> from itertools import permutations
>>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))
True
>>> all(sorted(heaps(x)) == sorted(permutations(x))
... for x in ([], [0], [-1, 1], [1, 2, 3]))
True
"""
if len(arr) <= 1:
return [tuple(arr)]
res = []
def generate(k: int, arr: list):
if k == 1:
res.append(tuple(arr[:]))
return
generate(k - 1, arr)
for i in range(k - 1):
if k % 2 == 0: # k is even
arr[i], arr[k - 1] = arr[k - 1], arr[i]
else: # k is odd
arr[0], arr[k - 1] = arr[k - 1], arr[0]
generate(k - 1, arr)
generate(len(arr), arr)
return res
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
print(heaps(arr))
| """
Heap's algorithm returns the list of all permutations possible from a list.
It minimizes movement by generating each permutation from the previous one
by swapping only two elements.
More information:
https://en.wikipedia.org/wiki/Heap%27s_algorithm.
"""
def heaps(arr: list) -> list:
"""
Pure python implementation of the Heap's algorithm (recursive version),
returning all permutations of a list.
>>> heaps([])
[()]
>>> heaps([0])
[(0,)]
>>> heaps([-1, 1])
[(-1, 1), (1, -1)]
>>> heaps([1, 2, 3])
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]
>>> from itertools import permutations
>>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))
True
>>> all(sorted(heaps(x)) == sorted(permutations(x))
... for x in ([], [0], [-1, 1], [1, 2, 3]))
True
"""
if len(arr) <= 1:
return [tuple(arr)]
res = []
def generate(k: int, arr: list):
if k == 1:
res.append(tuple(arr[:]))
return
generate(k - 1, arr)
for i in range(k - 1):
if k % 2 == 0: # k is even
arr[i], arr[k - 1] = arr[k - 1], arr[i]
else: # k is odd
arr[0], arr[k - 1] = arr[k - 1], arr[0]
generate(k - 1, arr)
generate(len(arr), arr)
return res
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
print(heaps(arr))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a pure Python implementation of the pancake sort algorithm
For doctests run following command:
python3 -m doctest -v pancake_sort.py
or
python -m doctest -v pancake_sort.py
For manual testing run:
python pancake_sort.py
"""
def pancake_sort(arr):
"""Sort Array with Pancake Sort.
:param arr: Collection containing comparable items
:return: Collection ordered in ascending order of items
Examples:
>>> pancake_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([-2, -5, -45])
[-45, -5, -2]
"""
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
cur -= 1
return arr
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(pancake_sort(unsorted))
| """
This is a pure Python implementation of the pancake sort algorithm
For doctests run following command:
python3 -m doctest -v pancake_sort.py
or
python -m doctest -v pancake_sort.py
For manual testing run:
python pancake_sort.py
"""
def pancake_sort(arr):
"""Sort Array with Pancake Sort.
:param arr: Collection containing comparable items
:return: Collection ordered in ascending order of items
Examples:
>>> pancake_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([-2, -5, -45])
[-45, -5, -2]
"""
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
cur -= 1
return arr
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(pancake_sort(unsorted))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Segmented Sieve."""
import math
def sieve(n):
"""Segmented Sieve."""
in_prime = []
start = 2
end = int(math.sqrt(n)) # Size of every segment
temp = [True] * (end + 1)
prime = []
while start <= end:
if temp[start] is True:
in_prime.append(start)
for i in range(start * start, end + 1, start):
if temp[i] is True:
temp[i] = False
start += 1
prime += in_prime
low = end + 1
high = low + end - 1
if high > n:
high = n
while low <= n:
temp = [True] * (high - low + 1)
for each in in_prime:
t = math.floor(low / each) * each
if t < low:
t += each
for j in range(t, high + 1, each):
temp[j - low] = False
for j in range(len(temp)):
if temp[j] is True:
prime.append(j + low)
low = high + 1
high = low + end - 1
if high > n:
high = n
return prime
print(sieve(10 ** 6))
| """Segmented Sieve."""
import math
def sieve(n):
"""Segmented Sieve."""
in_prime = []
start = 2
end = int(math.sqrt(n)) # Size of every segment
temp = [True] * (end + 1)
prime = []
while start <= end:
if temp[start] is True:
in_prime.append(start)
for i in range(start * start, end + 1, start):
if temp[i] is True:
temp[i] = False
start += 1
prime += in_prime
low = end + 1
high = low + end - 1
if high > n:
high = n
while low <= n:
temp = [True] * (high - low + 1)
for each in in_prime:
t = math.floor(low / each) * each
if t < low:
t += each
for j in range(t, high + 1, each):
temp[j - low] = False
for j in range(len(temp)):
if temp[j] is True:
prime.append(j + low)
low = high + 1
high = low + end - 1
if high > n:
high = n
return prime
print(sieve(10 ** 6))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Lychrel numbers
Problem 55: https://projecteuler.net/problem=55
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196,
never produce a palindrome. A number that never forms a palindrome through the
reverse and add process is called a Lychrel number. Due to the theoretical nature
of these numbers, and for the purpose of this problem, we shall assume that a number
is Lychrel until proven otherwise. In addition you are given that for every number
below ten-thousand, it will either (i) become a palindrome in less than fifty
iterations, or, (ii) no one, with all the computing power that exists, has managed
so far to map it to a palindrome. In fact, 10677 is the first number to be shown
to require over fifty iterations before producing a palindrome:
4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers;
the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
"""
def is_palindrome(n: int) -> bool:
"""
Returns True if a number is palindrome.
>>> is_palindrome(12567321)
False
>>> is_palindrome(1221)
True
>>> is_palindrome(9876789)
True
"""
return str(n) == str(n)[::-1]
def sum_reverse(n: int) -> int:
"""
Returns the sum of n and reverse of n.
>>> sum_reverse(123)
444
>>> sum_reverse(3478)
12221
>>> sum_reverse(12)
33
"""
return int(n) + int(str(n)[::-1])
def solution(limit: int = 10000) -> int:
"""
Returns the count of all lychrel numbers below limit.
>>> solution(10000)
249
>>> solution(5000)
76
>>> solution(1000)
13
"""
lychrel_nums = []
for num in range(1, limit):
iterations = 0
a = num
while iterations < 50:
num = sum_reverse(num)
iterations += 1
if is_palindrome(num):
break
else:
lychrel_nums.append(a)
return len(lychrel_nums)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Lychrel numbers
Problem 55: https://projecteuler.net/problem=55
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196,
never produce a palindrome. A number that never forms a palindrome through the
reverse and add process is called a Lychrel number. Due to the theoretical nature
of these numbers, and for the purpose of this problem, we shall assume that a number
is Lychrel until proven otherwise. In addition you are given that for every number
below ten-thousand, it will either (i) become a palindrome in less than fifty
iterations, or, (ii) no one, with all the computing power that exists, has managed
so far to map it to a palindrome. In fact, 10677 is the first number to be shown
to require over fifty iterations before producing a palindrome:
4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers;
the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
"""
def is_palindrome(n: int) -> bool:
"""
Returns True if a number is palindrome.
>>> is_palindrome(12567321)
False
>>> is_palindrome(1221)
True
>>> is_palindrome(9876789)
True
"""
return str(n) == str(n)[::-1]
def sum_reverse(n: int) -> int:
"""
Returns the sum of n and reverse of n.
>>> sum_reverse(123)
444
>>> sum_reverse(3478)
12221
>>> sum_reverse(12)
33
"""
return int(n) + int(str(n)[::-1])
def solution(limit: int = 10000) -> int:
"""
Returns the count of all lychrel numbers below limit.
>>> solution(10000)
249
>>> solution(5000)
76
>>> solution(1000)
13
"""
lychrel_nums = []
for num in range(1, limit):
iterations = 0
a = num
while iterations < 50:
num = sum_reverse(num)
iterations += 1
if is_palindrome(num):
break
else:
lychrel_nums.append(a)
return len(lychrel_nums)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 8: https://projecteuler.net/problem=8
Largest product in a series
The four adjacent digits in the 1000-digit number that have the greatest
product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Find the thirteen adjacent digits in the 1000-digit number that have the
greatest product. What is the value of this product?
"""
from functools import reduce
N = (
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450"
)
def solution(n: str = N) -> int:
"""
Find the thirteen adjacent digits in the 1000-digit number n that have
the greatest product and returns it.
>>> solution("13978431290823798458352374")
609638400
>>> solution("13978431295823798458352374")
2612736000
>>> solution("1397843129582379841238352374")
209018880
"""
return max(
[
reduce(lambda x, y: int(x) * int(y), n[i : i + 13])
for i in range(len(n) - 12)
]
)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 8: https://projecteuler.net/problem=8
Largest product in a series
The four adjacent digits in the 1000-digit number that have the greatest
product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Find the thirteen adjacent digits in the 1000-digit number that have the
greatest product. What is the value of this product?
"""
from functools import reduce
N = (
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450"
)
def solution(n: str = N) -> int:
"""
Find the thirteen adjacent digits in the 1000-digit number n that have
the greatest product and returns it.
>>> solution("13978431290823798458352374")
609638400
>>> solution("13978431295823798458352374")
2612736000
>>> solution("1397843129582379841238352374")
209018880
"""
return max(
[
reduce(lambda x, y: int(x) * int(y), n[i : i + 13])
for i in range(len(n) - 12)
]
)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def base64_encode(data: bytes) -> bytes:
"""Encodes data according to RFC4648.
The data is first transformed to binary and appended with binary digits so that its
length becomes a multiple of 6, then each 6 binary digits will match a character in
the B64_CHARSET string. The number of appended binary digits would later determine
how many "=" sign should be added, the padding.
For every 2 binary digits added, a "=" sign is added in the output.
We can add any binary digits to make it a multiple of 6, for instance, consider the
following example:
"AA" -> 0010100100101001 -> 001010 010010 1001
As can be seen above, 2 more binary digits should be added, so there's 4
possibilities here: 00, 01, 10 or 11.
That being said, Base64 encoding can be used in Steganography to hide data in these
appended digits.
>>> from base64 import b64encode
>>> a = b"This pull request is part of Hacktoberfest20!"
>>> b = b"https://tools.ietf.org/html/rfc4648"
>>> c = b"A"
>>> base64_encode(a) == b64encode(a)
True
>>> base64_encode(b) == b64encode(b)
True
>>> base64_encode(c) == b64encode(c)
True
>>> base64_encode("abc")
Traceback (most recent call last):
...
TypeError: a bytes-like object is required, not 'str'
"""
# Make sure the supplied data is a bytes-like object
if not isinstance(data, bytes):
raise TypeError(
f"a bytes-like object is required, not '{data.__class__.__name__}'"
)
binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)
padding_needed = len(binary_stream) % 6 != 0
if padding_needed:
# The padding that will be added later
padding = b"=" * ((6 - len(binary_stream) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(binary_stream) % 6)
else:
padding = b""
# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6], 2)]
for index in range(0, len(binary_stream), 6)
).encode()
+ padding
)
def base64_decode(encoded_data: str) -> bytes:
"""Decodes data according to RFC4648.
This does the reverse operation of base64_encode.
We first transform the encoded data back to a binary stream, take off the
previously appended binary digits according to the padding, at this point we
would have a binary stream whose length is multiple of 8, the last step is
to convert every 8 bits to a byte.
>>> from base64 import b64decode
>>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh"
>>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg="
>>> c = "QQ=="
>>> base64_decode(a) == b64decode(a)
True
>>> base64_decode(b) == b64decode(b)
True
>>> base64_decode(c) == b64decode(c)
True
>>> base64_decode("abc")
Traceback (most recent call last):
...
AssertionError: Incorrect padding
"""
# Make sure encoded_data is either a string or a bytes-like object
if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
raise TypeError(
"argument should be a bytes-like object or ASCII string, not "
f"'{encoded_data.__class__.__name__}'"
)
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if isinstance(encoded_data, bytes):
try:
encoded_data = encoded_data.decode("utf-8")
except UnicodeDecodeError:
raise ValueError("base64 encoded data should only contain ASCII characters")
padding = encoded_data.count("=")
# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
encoded_data = encoded_data[:-padding]
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)[: -padding * 2]
else:
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)
data = [
int(binary_stream[index : index + 8], 2)
for index in range(0, len(binary_stream), 8)
]
return bytes(data)
if __name__ == "__main__":
import doctest
doctest.testmod()
| B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def base64_encode(data: bytes) -> bytes:
"""Encodes data according to RFC4648.
The data is first transformed to binary and appended with binary digits so that its
length becomes a multiple of 6, then each 6 binary digits will match a character in
the B64_CHARSET string. The number of appended binary digits would later determine
how many "=" sign should be added, the padding.
For every 2 binary digits added, a "=" sign is added in the output.
We can add any binary digits to make it a multiple of 6, for instance, consider the
following example:
"AA" -> 0010100100101001 -> 001010 010010 1001
As can be seen above, 2 more binary digits should be added, so there's 4
possibilities here: 00, 01, 10 or 11.
That being said, Base64 encoding can be used in Steganography to hide data in these
appended digits.
>>> from base64 import b64encode
>>> a = b"This pull request is part of Hacktoberfest20!"
>>> b = b"https://tools.ietf.org/html/rfc4648"
>>> c = b"A"
>>> base64_encode(a) == b64encode(a)
True
>>> base64_encode(b) == b64encode(b)
True
>>> base64_encode(c) == b64encode(c)
True
>>> base64_encode("abc")
Traceback (most recent call last):
...
TypeError: a bytes-like object is required, not 'str'
"""
# Make sure the supplied data is a bytes-like object
if not isinstance(data, bytes):
raise TypeError(
f"a bytes-like object is required, not '{data.__class__.__name__}'"
)
binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)
padding_needed = len(binary_stream) % 6 != 0
if padding_needed:
# The padding that will be added later
padding = b"=" * ((6 - len(binary_stream) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(binary_stream) % 6)
else:
padding = b""
# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6], 2)]
for index in range(0, len(binary_stream), 6)
).encode()
+ padding
)
def base64_decode(encoded_data: str) -> bytes:
"""Decodes data according to RFC4648.
This does the reverse operation of base64_encode.
We first transform the encoded data back to a binary stream, take off the
previously appended binary digits according to the padding, at this point we
would have a binary stream whose length is multiple of 8, the last step is
to convert every 8 bits to a byte.
>>> from base64 import b64decode
>>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh"
>>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg="
>>> c = "QQ=="
>>> base64_decode(a) == b64decode(a)
True
>>> base64_decode(b) == b64decode(b)
True
>>> base64_decode(c) == b64decode(c)
True
>>> base64_decode("abc")
Traceback (most recent call last):
...
AssertionError: Incorrect padding
"""
# Make sure encoded_data is either a string or a bytes-like object
if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
raise TypeError(
"argument should be a bytes-like object or ASCII string, not "
f"'{encoded_data.__class__.__name__}'"
)
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if isinstance(encoded_data, bytes):
try:
encoded_data = encoded_data.decode("utf-8")
except UnicodeDecodeError:
raise ValueError("base64 encoded data should only contain ASCII characters")
padding = encoded_data.count("=")
# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."
# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
encoded_data = encoded_data[:-padding]
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)[: -padding * 2]
else:
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)
data = [
int(binary_stream[index : index + 8], 2)
for index in range(0, len(binary_stream), 8)
]
return bytes(data)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def perfect_cube(n: int) -> bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val = n ** (1 / 3)
return (val * val * val) == n
if __name__ == "__main__":
print(perfect_cube(27))
print(perfect_cube(4))
| def perfect_cube(n: int) -> bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val = n ** (1 / 3)
return (val * val * val) == n
if __name__ == "__main__":
print(perfect_cube(27))
print(perfect_cube(4))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Author : Mehdi ALAOUI
This is a pure Python implementation of Dynamic Programming solution to the longest
increasing subsequence of a given sequence.
The problem is :
Given an array, to find the longest and increasing sub-array in that given array and
return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return
[10, 22, 33, 41, 60, 80] as output
"""
from __future__ import annotations
def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive
"""
Some examples
>>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])
[10, 22, 33, 41, 60, 80]
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
[1, 2, 3, 9]
>>> longest_subsequence([9, 8, 7, 6, 5, 7])
[8]
>>> longest_subsequence([1, 1, 1])
[1, 1, 1]
>>> longest_subsequence([])
[]
"""
array_length = len(array)
# If the array contains only one element, we return it (it's the stop condition of
# recursion)
if array_length <= 1:
return array
# Else
pivot = array[0]
isFound = False
i = 1
longest_subseq = []
while not isFound and i < array_length:
if array[i] < pivot:
isFound = True
temp_array = [element for element in array[i:] if element >= array[i]]
temp_array = longest_subsequence(temp_array)
if len(temp_array) > len(longest_subseq):
longest_subseq = temp_array
else:
i += 1
temp_array = [element for element in array[1:] if element >= pivot]
temp_array = [pivot] + longest_subsequence(temp_array)
if len(temp_array) > len(longest_subseq):
return temp_array
else:
return longest_subseq
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Author : Mehdi ALAOUI
This is a pure Python implementation of Dynamic Programming solution to the longest
increasing subsequence of a given sequence.
The problem is :
Given an array, to find the longest and increasing sub-array in that given array and
return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return
[10, 22, 33, 41, 60, 80] as output
"""
from __future__ import annotations
def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive
"""
Some examples
>>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])
[10, 22, 33, 41, 60, 80]
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
[1, 2, 3, 9]
>>> longest_subsequence([9, 8, 7, 6, 5, 7])
[8]
>>> longest_subsequence([1, 1, 1])
[1, 1, 1]
>>> longest_subsequence([])
[]
"""
array_length = len(array)
# If the array contains only one element, we return it (it's the stop condition of
# recursion)
if array_length <= 1:
return array
# Else
pivot = array[0]
isFound = False
i = 1
longest_subseq = []
while not isFound and i < array_length:
if array[i] < pivot:
isFound = True
temp_array = [element for element in array[i:] if element >= array[i]]
temp_array = longest_subsequence(temp_array)
if len(temp_array) > len(longest_subseq):
longest_subseq = temp_array
else:
i += 1
temp_array = [element for element in array[1:] if element >= pivot]
temp_array = [pivot] + longest_subsequence(temp_array)
if len(temp_array) > len(longest_subseq):
return temp_array
else:
return longest_subseq
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from typing import List
def merge(left_half: List, right_half: List) -> List:
"""Helper function for mergesort.
>>> left_half = [-2]
>>> right_half = [-1]
>>> merge(left_half, right_half)
[-2, -1]
>>> left_half = [1,2,3]
>>> right_half = [4,5,6]
>>> merge(left_half, right_half)
[1, 2, 3, 4, 5, 6]
>>> left_half = [-2]
>>> right_half = [-1]
>>> merge(left_half, right_half)
[-2, -1]
>>> left_half = [12, 15]
>>> right_half = [13, 14]
>>> merge(left_half, right_half)
[12, 13, 14, 15]
>>> left_half = []
>>> right_half = []
>>> merge(left_half, right_half)
[]
"""
sorted_array = [None] * (len(right_half) + len(left_half))
pointer1 = 0 # pointer to current index for left Half
pointer2 = 0 # pointer to current index for the right Half
index = 0 # pointer to current index for the sorted array Half
while pointer1 < len(left_half) and pointer2 < len(right_half):
if left_half[pointer1] < right_half[pointer2]:
sorted_array[index] = left_half[pointer1]
pointer1 += 1
index += 1
else:
sorted_array[index] = right_half[pointer2]
pointer2 += 1
index += 1
while pointer1 < len(left_half):
sorted_array[index] = left_half[pointer1]
pointer1 += 1
index += 1
while pointer2 < len(right_half):
sorted_array[index] = right_half[pointer2]
pointer2 += 1
index += 1
return sorted_array
def merge_sort(array: List) -> List:
"""Returns a list of sorted array elements using merge sort.
>>> from random import shuffle
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> array = [-200]
>>> merge_sort(array)
[-200]
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> sorted(array) == merge_sort(array)
True
>>> array = [-2]
>>> merge_sort(array)
[-2]
>>> array = []
>>> merge_sort(array)
[]
>>> array = [10000000, 1, -1111111111, 101111111112, 9000002]
>>> sorted(array) == merge_sort(array)
True
"""
if len(array) <= 1:
return array
# the actual formula to calculate the middle element = left + (right - left) // 2
# this avoids integer overflow in case of large N
middle = 0 + (len(array) - 0) // 2
# Split the array into halves till the array length becomes equal to One
# merge the arrays of single length returned by mergeSort function and
# pass them into the merge arrays function which merges the array
left_half = array[:middle]
right_half = array[middle:]
return merge(merge_sort(left_half), merge_sort(right_half))
if __name__ == "__main__":
import doctest
doctest.testmod()
| from typing import List
def merge(left_half: List, right_half: List) -> List:
"""Helper function for mergesort.
>>> left_half = [-2]
>>> right_half = [-1]
>>> merge(left_half, right_half)
[-2, -1]
>>> left_half = [1,2,3]
>>> right_half = [4,5,6]
>>> merge(left_half, right_half)
[1, 2, 3, 4, 5, 6]
>>> left_half = [-2]
>>> right_half = [-1]
>>> merge(left_half, right_half)
[-2, -1]
>>> left_half = [12, 15]
>>> right_half = [13, 14]
>>> merge(left_half, right_half)
[12, 13, 14, 15]
>>> left_half = []
>>> right_half = []
>>> merge(left_half, right_half)
[]
"""
sorted_array = [None] * (len(right_half) + len(left_half))
pointer1 = 0 # pointer to current index for left Half
pointer2 = 0 # pointer to current index for the right Half
index = 0 # pointer to current index for the sorted array Half
while pointer1 < len(left_half) and pointer2 < len(right_half):
if left_half[pointer1] < right_half[pointer2]:
sorted_array[index] = left_half[pointer1]
pointer1 += 1
index += 1
else:
sorted_array[index] = right_half[pointer2]
pointer2 += 1
index += 1
while pointer1 < len(left_half):
sorted_array[index] = left_half[pointer1]
pointer1 += 1
index += 1
while pointer2 < len(right_half):
sorted_array[index] = right_half[pointer2]
pointer2 += 1
index += 1
return sorted_array
def merge_sort(array: List) -> List:
"""Returns a list of sorted array elements using merge sort.
>>> from random import shuffle
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> array = [-200]
>>> merge_sort(array)
[-200]
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> sorted(array) == merge_sort(array)
True
>>> array = [-2]
>>> merge_sort(array)
[-2]
>>> array = []
>>> merge_sort(array)
[]
>>> array = [10000000, 1, -1111111111, 101111111112, 9000002]
>>> sorted(array) == merge_sort(array)
True
"""
if len(array) <= 1:
return array
# the actual formula to calculate the middle element = left + (right - left) // 2
# this avoids integer overflow in case of large N
middle = 0 + (len(array) - 0) // 2
# Split the array into halves till the array length becomes equal to One
# merge the arrays of single length returned by mergeSort function and
# pass them into the merge arrays function which merges the array
left_half = array[:middle]
right_half = array[middle:]
return merge(merge_sort(left_half), merge_sort(right_half))
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In this problem, we want to determine all possible subsequences
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(2^n),
where n denotes the length of the given sequence.
"""
from typing import Any, List
def generate_all_subsequences(sequence: List[Any]) -> None:
create_state_space_tree(sequence, [], 0)
def create_state_space_tree(
sequence: List[Any], current_subsequence: List[Any], index: int
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly two children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_subsequence)
return
create_state_space_tree(sequence, current_subsequence, index + 1)
current_subsequence.append(sequence[index])
create_state_space_tree(sequence, current_subsequence, index + 1)
current_subsequence.pop()
if __name__ == "__main__":
seq: List[Any] = [3, 1, 2, 4]
generate_all_subsequences(seq)
seq.clear()
seq.extend(["A", "B", "C"])
generate_all_subsequences(seq)
| """
In this problem, we want to determine all possible subsequences
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(2^n),
where n denotes the length of the given sequence.
"""
from typing import Any, List
def generate_all_subsequences(sequence: List[Any]) -> None:
create_state_space_tree(sequence, [], 0)
def create_state_space_tree(
sequence: List[Any], current_subsequence: List[Any], index: int
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly two children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_subsequence)
return
create_state_space_tree(sequence, current_subsequence, index + 1)
current_subsequence.append(sequence[index])
create_state_space_tree(sequence, current_subsequence, index + 1)
current_subsequence.pop()
if __name__ == "__main__":
seq: List[Any] = [3, 1, 2, 4]
generate_all_subsequences(seq)
seq.clear()
seq.extend(["A", "B", "C"])
generate_all_subsequences(seq)
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 28
Url: https://projecteuler.net/problem=28
Statement:
Starting with the number 1 and moving to the right in a clockwise direction a 5
by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed
in the same way?
"""
from math import ceil
def solution(n: int = 1001) -> int:
"""Returns the sum of the numbers on the diagonals in a n by n spiral
formed in the same way.
>>> solution(1001)
669171001
>>> solution(500)
82959497
>>> solution(100)
651897
>>> solution(50)
79697
>>> solution(10)
537
"""
total = 1
for i in range(1, int(ceil(n / 2.0))):
odd = 2 * i + 1
even = 2 * i
total = total + 4 * odd ** 2 - 6 * even
return total
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution())
else:
try:
n = int(sys.argv[1])
print(solution(n))
except ValueError:
print("Invalid entry - please enter a number")
| """
Problem 28
Url: https://projecteuler.net/problem=28
Statement:
Starting with the number 1 and moving to the right in a clockwise direction a 5
by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed
in the same way?
"""
from math import ceil
def solution(n: int = 1001) -> int:
"""Returns the sum of the numbers on the diagonals in a n by n spiral
formed in the same way.
>>> solution(1001)
669171001
>>> solution(500)
82959497
>>> solution(100)
651897
>>> solution(50)
79697
>>> solution(10)
537
"""
total = 1
for i in range(1, int(ceil(n / 2.0))):
odd = 2 * i + 1
even = 2 * i
total = total + 4 * odd ** 2 - 6 * even
return total
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution())
else:
try:
n = int(sys.argv[1])
print(solution(n))
except ValueError:
print("Invalid entry - please enter a number")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Eulers Totient function finds the number of relative primes of a number n from 1 to n
def totient(n: int) -> list:
is_prime = [True for i in range(n + 1)]
totients = [i - 1 for i in range(n + 1)]
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
if i % primes[j] == 0:
totients[i * primes[j]] = totients[i] * primes[j]
break
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
return totients
def test_totient() -> None:
"""
>>> n = 10
>>> totient_calculation = totient(n)
>>> for i in range(1, n):
... print(f"{i} has {totient_calculation[i]} relative primes.")
1 has 0 relative primes.
2 has 1 relative primes.
3 has 2 relative primes.
4 has 2 relative primes.
5 has 4 relative primes.
6 has 2 relative primes.
7 has 6 relative primes.
8 has 4 relative primes.
9 has 6 relative primes.
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Eulers Totient function finds the number of relative primes of a number n from 1 to n
def totient(n: int) -> list:
is_prime = [True for i in range(n + 1)]
totients = [i - 1 for i in range(n + 1)]
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
if i % primes[j] == 0:
totients[i * primes[j]] = totients[i] * primes[j]
break
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
return totients
def test_totient() -> None:
"""
>>> n = 10
>>> totient_calculation = totient(n)
>>> for i in range(1, n):
... print(f"{i} has {totient_calculation[i]} relative primes.")
1 has 0 relative primes.
2 has 1 relative primes.
3 has 2 relative primes.
4 has 2 relative primes.
5 has 4 relative primes.
6 has 2 relative primes.
7 has 6 relative primes.
8 has 4 relative primes.
9 has 6 relative primes.
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Get the site emails from URL."""
__author__ = "Muhammad Umer Farooq"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Muhammad Umer Farooq"
__email__ = "[email protected]"
__status__ = "Alpha"
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class Parser(HTMLParser):
def __init__(self, domain: str):
HTMLParser.__init__(self)
self.data = []
self.domain = domain
def handle_starttag(self, tag: str, attrs: str) -> None:
"""
This function parse html to take takes url from tags
"""
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in data.
if value not in self.data:
url = parse.urljoin(self.domain, value)
self.data.append(url)
# Get main domain name (example.com)
def get_domain_name(url: str) -> str:
"""
This function get the main domain name
>>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'c.d'
>>> get_domain_name("Not a URL!")
''
"""
return ".".join(get_sub_domain_name(url).split(".")[-2:])
# Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str:
"""
>>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'a.b.c.d'
>>> get_sub_domain_name("Not a URL!")
''
"""
return parse.urlparse(url).netloc
def emails_from_url(url: str = "https://github.com") -> list:
"""
This function takes url and return all valid urls
"""
# Get the base domain from the url
domain = get_domain_name(url)
# Initialize the parser
parser = Parser(domain)
try:
# Open URL
r = requests.get(url)
# pass the raw HTML to the parser to get links
parser.feed(r.text)
# Get links and loop through
valid_emails = set()
for link in parser.data:
# open URL.
# read = requests.get(link)
try:
read = requests.get(link)
# Get the valid email.
emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text)
# If not in list then append it.
for email in emails:
valid_emails.add(email)
except ValueError:
pass
except ValueError:
exit(-1)
# Finally return a sorted list of email addresses with no duplicates.
return sorted(valid_emails)
if __name__ == "__main__":
emails = emails_from_url("https://github.com")
print(f"{len(emails)} emails found:")
print("\n".join(sorted(emails)))
| """Get the site emails from URL."""
__author__ = "Muhammad Umer Farooq"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Muhammad Umer Farooq"
__email__ = "[email protected]"
__status__ = "Alpha"
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class Parser(HTMLParser):
def __init__(self, domain: str):
HTMLParser.__init__(self)
self.data = []
self.domain = domain
def handle_starttag(self, tag: str, attrs: str) -> None:
"""
This function parse html to take takes url from tags
"""
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in data.
if value not in self.data:
url = parse.urljoin(self.domain, value)
self.data.append(url)
# Get main domain name (example.com)
def get_domain_name(url: str) -> str:
"""
This function get the main domain name
>>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'c.d'
>>> get_domain_name("Not a URL!")
''
"""
return ".".join(get_sub_domain_name(url).split(".")[-2:])
# Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str:
"""
>>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'a.b.c.d'
>>> get_sub_domain_name("Not a URL!")
''
"""
return parse.urlparse(url).netloc
def emails_from_url(url: str = "https://github.com") -> list:
"""
This function takes url and return all valid urls
"""
# Get the base domain from the url
domain = get_domain_name(url)
# Initialize the parser
parser = Parser(domain)
try:
# Open URL
r = requests.get(url)
# pass the raw HTML to the parser to get links
parser.feed(r.text)
# Get links and loop through
valid_emails = set()
for link in parser.data:
# open URL.
# read = requests.get(link)
try:
read = requests.get(link)
# Get the valid email.
emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text)
# If not in list then append it.
for email in emails:
valid_emails.add(email)
except ValueError:
pass
except ValueError:
exit(-1)
# Finally return a sorted list of email addresses with no duplicates.
return sorted(valid_emails)
if __name__ == "__main__":
emails = emails_from_url("https://github.com")
print(f"{len(emails)} emails found:")
print("\n".join(sorted(emails)))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Changing contrast with PIL
This algorithm is used in
https://noivce.pythonanywhere.com/ Python web app.
python/black: True
flake8 : True
"""
from PIL import Image
def change_contrast(img: Image, level: int) -> Image:
"""
Function to change contrast
"""
factor = (259 * (level + 255)) / (255 * (259 - level))
def contrast(c: int) -> int:
"""
Fundamental Transformation/Operation that'll be performed on
every bit.
"""
return int(128 + factor * (c - 128))
return img.point(contrast)
if __name__ == "__main__":
# Load image
with Image.open("image_data/lena.jpg") as img:
# Change contrast to 170
cont_img = change_contrast(img, 170)
cont_img.save("image_data/lena_high_contrast.png", format="png")
| """
Changing contrast with PIL
This algorithm is used in
https://noivce.pythonanywhere.com/ Python web app.
python/black: True
flake8 : True
"""
from PIL import Image
def change_contrast(img: Image, level: int) -> Image:
"""
Function to change contrast
"""
factor = (259 * (level + 255)) / (255 * (259 - level))
def contrast(c: int) -> int:
"""
Fundamental Transformation/Operation that'll be performed on
every bit.
"""
return int(128 + factor * (c - 128))
return img.point(contrast)
if __name__ == "__main__":
# Load image
with Image.open("image_data/lena.jpg") as img:
# Change contrast to 170
cont_img = change_contrast(img, 170)
cont_img.save("image_data/lena_high_contrast.png", format="png")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A pure Python implementation of the insertion sort algorithm
This algorithm sorts a collection by comparing adjacent elements.
When it finds that order is not respected, it moves the element compared
backward until the order is correct. It then goes back directly to the
element's initial position resuming forward comparison.
For doctests run following command:
python3 -m doctest -v insertion_sort.py
For manual testing run:
python3 insertion_sort.py
"""
def insertion_sort(collection: list) -> list:
"""A pure Python implementation of the insertion sort algorithm
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> insertion_sort([]) == sorted([])
True
>>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45])
True
>>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> insertion_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> insertion_sort(collection) == sorted(collection)
True
"""
for insert_index, insert_value in enumerate(collection[1:]):
temp_index = insert_index
while insert_index >= 0 and insert_value < collection[insert_index]:
collection[insert_index + 1] = collection[insert_index]
insert_index -= 1
if insert_index != temp_index:
collection[insert_index + 1] = insert_value
return collection
if __name__ == "__main__":
from doctest import testmod
testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{insertion_sort(unsorted) = }")
| """
A pure Python implementation of the insertion sort algorithm
This algorithm sorts a collection by comparing adjacent elements.
When it finds that order is not respected, it moves the element compared
backward until the order is correct. It then goes back directly to the
element's initial position resuming forward comparison.
For doctests run following command:
python3 -m doctest -v insertion_sort.py
For manual testing run:
python3 insertion_sort.py
"""
def insertion_sort(collection: list) -> list:
"""A pure Python implementation of the insertion sort algorithm
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> insertion_sort([]) == sorted([])
True
>>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45])
True
>>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> insertion_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> insertion_sort(collection) == sorted(collection)
True
"""
for insert_index, insert_value in enumerate(collection[1:]):
temp_index = insert_index
while insert_index >= 0 and insert_value < collection[insert_index]:
collection[insert_index + 1] = collection[insert_index]
insert_index -= 1
if insert_index != temp_index:
collection[insert_index + 1] = insert_value
return collection
if __name__ == "__main__":
from doctest import testmod
testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{insertion_sort(unsorted) = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Pure Python implementation of the jump search algorithm.
This algorithm iterates through a sorted collection with a step of n^(1/2),
until the element compared is bigger than the one searched.
It will then perform a linear search until it matches the wanted number.
If not found, it returns -1.
"""
import math
def jump_search(arr: list, x: int) -> int:
"""
Pure Python implementation of the jump search algorithm.
Examples:
>>> jump_search([0, 1, 2, 3, 4, 5], 3)
3
>>> jump_search([-5, -2, -1], -1)
2
>>> jump_search([0, 5, 10, 20], 8)
-1
>>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
10
"""
n = len(arr)
step = int(math.floor(math.sqrt(n)))
prev = 0
while arr[min(step, n) - 1] < x:
prev = step
step += int(math.floor(math.sqrt(n)))
if prev >= n:
return -1
while arr[prev] < x:
prev = prev + 1
if prev == min(step, n):
return -1
if arr[prev] == x:
return prev
return -1
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
x = int(input("Enter the number to be searched:\n"))
res = jump_search(arr, x)
if res == -1:
print("Number not found!")
else:
print(f"Number {x} is at index {res}")
| """
Pure Python implementation of the jump search algorithm.
This algorithm iterates through a sorted collection with a step of n^(1/2),
until the element compared is bigger than the one searched.
It will then perform a linear search until it matches the wanted number.
If not found, it returns -1.
"""
import math
def jump_search(arr: list, x: int) -> int:
"""
Pure Python implementation of the jump search algorithm.
Examples:
>>> jump_search([0, 1, 2, 3, 4, 5], 3)
3
>>> jump_search([-5, -2, -1], -1)
2
>>> jump_search([0, 5, 10, 20], 8)
-1
>>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
10
"""
n = len(arr)
step = int(math.floor(math.sqrt(n)))
prev = 0
while arr[min(step, n) - 1] < x:
prev = step
step += int(math.floor(math.sqrt(n)))
if prev >= n:
return -1
while arr[prev] < x:
prev = prev + 1
if prev == min(step, n):
return -1
if arr[prev] == x:
return prev
return -1
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
x = int(input("Enter the number to be searched:\n"))
res = jump_search(arr, x)
if res == -1:
print("Number not found!")
else:
print(f"Number {x} is at index {res}")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/Rayleigh_quotient
"""
import numpy as np
def is_hermitian(matrix: np.array) -> bool:
"""
Checks if a matrix is Hermitian.
>>> import numpy as np
>>> A = np.array([
... [2, 2+1j, 4],
... [2-1j, 3, 1j],
... [4, -1j, 1]])
>>> is_hermitian(A)
True
>>> A = np.array([
... [2, 2+1j, 4+1j],
... [2-1j, 3, 1j],
... [4, -1j, 1]])
>>> is_hermitian(A)
False
"""
return np.array_equal(matrix, matrix.conjugate().T)
def rayleigh_quotient(A: np.array, v: np.array) -> float:
"""
Returns the Rayleigh quotient of a Hermitian matrix A and
vector v.
>>> import numpy as np
>>> A = np.array([
... [1, 2, 4],
... [2, 3, -1],
... [4, -1, 1]
... ])
>>> v = np.array([
... [1],
... [2],
... [3]
... ])
>>> rayleigh_quotient(A, v)
array([[3.]])
"""
v_star = v.conjugate().T
return (v_star.dot(A).dot(v)) / (v_star.dot(v))
def tests() -> None:
A = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]])
v = np.array([[1], [2], [3]])
assert is_hermitian(A), f"{A} is not hermitian."
print(rayleigh_quotient(A, v))
A = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]])
assert is_hermitian(A), f"{A} is not hermitian."
assert rayleigh_quotient(A, v) == float(3)
if __name__ == "__main__":
import doctest
doctest.testmod()
tests()
| """
https://en.wikipedia.org/wiki/Rayleigh_quotient
"""
import numpy as np
def is_hermitian(matrix: np.array) -> bool:
"""
Checks if a matrix is Hermitian.
>>> import numpy as np
>>> A = np.array([
... [2, 2+1j, 4],
... [2-1j, 3, 1j],
... [4, -1j, 1]])
>>> is_hermitian(A)
True
>>> A = np.array([
... [2, 2+1j, 4+1j],
... [2-1j, 3, 1j],
... [4, -1j, 1]])
>>> is_hermitian(A)
False
"""
return np.array_equal(matrix, matrix.conjugate().T)
def rayleigh_quotient(A: np.array, v: np.array) -> float:
"""
Returns the Rayleigh quotient of a Hermitian matrix A and
vector v.
>>> import numpy as np
>>> A = np.array([
... [1, 2, 4],
... [2, 3, -1],
... [4, -1, 1]
... ])
>>> v = np.array([
... [1],
... [2],
... [3]
... ])
>>> rayleigh_quotient(A, v)
array([[3.]])
"""
v_star = v.conjugate().T
return (v_star.dot(A).dot(v)) / (v_star.dot(v))
def tests() -> None:
A = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]])
v = np.array([[1], [2], [3]])
assert is_hermitian(A), f"{A} is not hermitian."
print(rayleigh_quotient(A, v))
A = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]])
assert is_hermitian(A), f"{A} is not hermitian."
assert rayleigh_quotient(A, v) == float(3)
if __name__ == "__main__":
import doctest
doctest.testmod()
tests()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The Reverse Polish Nation also known as Polish postfix notation
or simply postfix notation.
https://en.wikipedia.org/wiki/Reverse_Polish_notation
Classic examples of simple stack implementations
Valid operators are +, -, *, /.
Each operand may be an integer or another expression.
"""
def evaluate_postfix(postfix_notation: list) -> int:
"""
>>> evaluate_postfix(["2", "1", "+", "3", "*"])
9
>>> evaluate_postfix(["4", "13", "5", "/", "+"])
6
>>> evaluate_postfix([])
0
"""
if not postfix_notation:
return 0
operations = {"+", "-", "*", "/"}
stack = []
for token in postfix_notation:
if token in operations:
b, a = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1)
else:
stack.append(a // b)
else:
stack.append(int(token))
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
The Reverse Polish Nation also known as Polish postfix notation
or simply postfix notation.
https://en.wikipedia.org/wiki/Reverse_Polish_notation
Classic examples of simple stack implementations
Valid operators are +, -, *, /.
Each operand may be an integer or another expression.
"""
def evaluate_postfix(postfix_notation: list) -> int:
"""
>>> evaluate_postfix(["2", "1", "+", "3", "*"])
9
>>> evaluate_postfix(["4", "13", "5", "/", "+"])
6
>>> evaluate_postfix([])
0
"""
if not postfix_notation:
return 0
operations = {"+", "-", "*", "/"}
stack = []
for token in postfix_notation:
if token in operations:
b, a = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1)
else:
stack.append(a // b)
else:
stack.append(int(token))
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import json
import requests
from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
def test_fetch_github_info(monkeypatch):
class FakeResponse:
def __init__(self, content) -> None:
assert isinstance(content, (bytes, str))
self.content = content
def json(self):
return json.loads(self.content)
def mock_response(*args, **kwargs):
assert args[0] == AUTHENTICATED_USER_ENDPOINT
assert "Authorization" in kwargs["headers"]
assert kwargs["headers"]["Authorization"].startswith("token ")
assert "Accept" in kwargs["headers"]
return FakeResponse(b'{"login":"test","id":1}')
monkeypatch.setattr(requests, "get", mock_response)
result = fetch_github_info("token")
assert result["login"] == "test"
assert result["id"] == 1
| import json
import requests
from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
def test_fetch_github_info(monkeypatch):
class FakeResponse:
def __init__(self, content) -> None:
assert isinstance(content, (bytes, str))
self.content = content
def json(self):
return json.loads(self.content)
def mock_response(*args, **kwargs):
assert args[0] == AUTHENTICATED_USER_ENDPOINT
assert "Authorization" in kwargs["headers"]
assert kwargs["headers"]["Authorization"].startswith("token ")
assert "Accept" in kwargs["headers"]
return FakeResponse(b'{"login":"test","id":1}')
monkeypatch.setattr(requests, "get", mock_response)
result = fetch_github_info("token")
assert result["login"] == "test"
assert result["id"] == 1
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
python/black : True
"""
from __future__ import annotations
def prime_factors(n: int) -> list[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)
[]
>>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
>>> x == [2]*241 + [5]*241
True
>>> prime_factors(10**-354)
[]
>>> prime_factors('hello')
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> prime_factors([1,2,'hello'])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
python/black : True
"""
from __future__ import annotations
def prime_factors(n: int) -> list[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)
[]
>>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
>>> x == [2]*241 + [5]*241
True
>>> prime_factors(10**-354)
[]
>>> prime_factors('hello')
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> prime_factors([1,2,'hello'])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 56: https://projecteuler.net/problem=56
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100,
what is the maximum digital sum?
"""
def solution(a: int = 100, b: int = 100) -> int:
"""
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
:param a:
:param b:
:return:
>>> solution(10,10)
45
>>> solution(100,100)
972
>>> solution(100,200)
1872
"""
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
# BASE raised to the POWER
return max(
[
sum([int(x) for x in str(base ** power)])
for base in range(a)
for power in range(b)
]
)
# Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Project Euler Problem 56: https://projecteuler.net/problem=56
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100,
what is the maximum digital sum?
"""
def solution(a: int = 100, b: int = 100) -> int:
"""
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
:param a:
:param b:
:return:
>>> solution(10,10)
45
>>> solution(100,100)
972
>>> solution(100,200)
1872
"""
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
# BASE raised to the POWER
return max(
[
sum([int(x) for x in str(base ** power)])
for base in range(a)
for power in range(b)
]
)
# Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from typing import List
def kmp(pattern: str, text: str) -> bool:
"""
The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
with complexity O(n + m)
1) Preprocess pattern to identify any suffixes that are identical to prefixes
This tells us where to continue from if we get a mismatch between a character
in our pattern and the text.
2) Step through the text one character at a time and compare it to a character in
the pattern updating our location within the pattern if necessary
"""
# 1) Construct the failure array
failure = get_failure_array(pattern)
# 2) Step through text searching for pattern
i, j = 0, 0 # index into text, pattern
while i < len(text):
if pattern[j] == text[i]:
if j == (len(pattern) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
j = failure[j - 1]
continue
i += 1
return False
def get_failure_array(pattern: str) -> List[int]:
"""
Calculates the new index we should go to if we fail a comparison
:param pattern:
:return:
"""
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i - 1]
continue
j += 1
failure.append(i)
return failure
if __name__ == "__main__":
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert kmp(pattern, text1) and not kmp(pattern, text2)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert kmp(pattern, text)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert kmp(pattern, text)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert kmp(pattern, text)
# Test 5)
pattern = "aabaabaaa"
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| from typing import List
def kmp(pattern: str, text: str) -> bool:
"""
The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
with complexity O(n + m)
1) Preprocess pattern to identify any suffixes that are identical to prefixes
This tells us where to continue from if we get a mismatch between a character
in our pattern and the text.
2) Step through the text one character at a time and compare it to a character in
the pattern updating our location within the pattern if necessary
"""
# 1) Construct the failure array
failure = get_failure_array(pattern)
# 2) Step through text searching for pattern
i, j = 0, 0 # index into text, pattern
while i < len(text):
if pattern[j] == text[i]:
if j == (len(pattern) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
j = failure[j - 1]
continue
i += 1
return False
def get_failure_array(pattern: str) -> List[int]:
"""
Calculates the new index we should go to if we fail a comparison
:param pattern:
:return:
"""
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i - 1]
continue
j += 1
failure.append(i)
return failure
if __name__ == "__main__":
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert kmp(pattern, text1) and not kmp(pattern, text2)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert kmp(pattern, text)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert kmp(pattern, text)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert kmp(pattern, text)
# Test 5)
pattern = "aabaabaaa"
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 34: https://projecteuler.net/problem=34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
"""
from math import factorial
def sum_of_digit_factorial(n: int) -> int:
"""
Returns the sum of the digits in n
>>> sum_of_digit_factorial(15)
121
>>> sum_of_digit_factorial(0)
1
"""
return sum(factorial(int(char)) for char in str(n))
def solution() -> int:
"""
Returns the sum of all numbers whose
sum of the factorials of all digits
add up to the number itself.
>>> solution()
40730
"""
limit = 7 * factorial(9) + 1
return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)
if __name__ == "__main__":
print(f"{solution()} = ")
| """
Problem 34: https://projecteuler.net/problem=34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
"""
from math import factorial
def sum_of_digit_factorial(n: int) -> int:
"""
Returns the sum of the digits in n
>>> sum_of_digit_factorial(15)
121
>>> sum_of_digit_factorial(0)
1
"""
return sum(factorial(int(char)) for char in str(n))
def solution() -> int:
"""
Returns the sum of all numbers whose
sum of the factorials of all digits
add up to the number itself.
>>> solution()
40730
"""
limit = 7 * factorial(9) + 1
return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)
if __name__ == "__main__":
print(f"{solution()} = ")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def 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
"""
sum = 0.0
for sum_index in range(digit_pos_to_extract + precision):
denominator = 8 * sum_index + denominator_addend
exponential_term = 0.0
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)
sum += exponential_term / denominator
return sum
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
"""
sum = 0.0
for sum_index in range(digit_pos_to_extract + precision):
denominator = 8 * sum_index + denominator_addend
exponential_term = 0.0
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)
sum += exponential_term / denominator
return sum
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 120 Square remainders: https://projecteuler.net/problem=120
Description:
Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2.
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49.
And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
For 3 ≤ a ≤ 1000, find ∑ r_max.
Solution:
On expanding the terms, we get 2 if n is even and 2an if n is odd.
For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
"""
def solution(n: int = 1000) -> int:
"""
Returns ∑ r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1))
if __name__ == "__main__":
print(solution())
| """
Problem 120 Square remainders: https://projecteuler.net/problem=120
Description:
Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2.
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49.
And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
For 3 ≤ a ≤ 1000, find ∑ r_max.
Solution:
On expanding the terms, we get 2 if n is even and 2an if n is odd.
For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
"""
def solution(n: int = 1000) -> int:
"""
Returns ∑ r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1))
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 4: https://projecteuler.net/problem=4
Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
References:
- https://en.wikipedia.org/wiki/Palindromic_number
"""
def solution(n: int = 998001) -> int:
"""
Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
29992
>>> solution(40000)
39893
>>> solution(10000)
Traceback (most recent call last):
...
ValueError: That number is larger than our acceptable range.
"""
# fetches the next number
for number in range(n - 1, 9999, -1):
str_number = str(number)
# checks whether 'str_number' is a palindrome.
if str_number == str_number[::-1]:
divisor = 999
# if 'number' is a product of two 3-digit numbers
# then number is the answer otherwise fetch next number.
while divisor != 99:
if (number % divisor == 0) and (len(str(number // divisor)) == 3.0):
return number
divisor -= 1
raise ValueError("That number is larger than our acceptable range.")
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 4: https://projecteuler.net/problem=4
Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
References:
- https://en.wikipedia.org/wiki/Palindromic_number
"""
def solution(n: int = 998001) -> int:
"""
Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
29992
>>> solution(40000)
39893
>>> solution(10000)
Traceback (most recent call last):
...
ValueError: That number is larger than our acceptable range.
"""
# fetches the next number
for number in range(n - 1, 9999, -1):
str_number = str(number)
# checks whether 'str_number' is a palindrome.
if str_number == str_number[::-1]:
divisor = 999
# if 'number' is a product of two 3-digit numbers
# then number is the answer otherwise fetch next number.
while divisor != 99:
if (number % divisor == 0) and (len(str(number // divisor)) == 3.0):
return number
divisor -= 1
raise ValueError("That number is larger than our acceptable range.")
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 1: https://projecteuler.net/problem=1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def solution(n: int = 1000) -> int:
"""
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
"""
total = 0
terms = (n - 1) // 3
total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P.
terms = (n - 1) // 5
total += ((terms) * (10 + (terms - 1) * 5)) // 2
terms = (n - 1) // 15
total -= ((terms) * (30 + (terms - 1) * 15)) // 2
return total
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 1: https://projecteuler.net/problem=1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def solution(n: int = 1000) -> int:
"""
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
"""
total = 0
terms = (n - 1) // 3
total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P.
terms = (n - 1) // 5
total += ((terms) * (10 + (terms - 1) * 5)) // 2
terms = (n - 1) // 15
total -= ((terms) * (30 + (terms - 1) * 15)) // 2
return total
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In this problem, we want to determine all possible permutations
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(n! * n),
where n denotes the length of the given sequence.
"""
from typing import List, Union
def generate_all_permutations(sequence: List[Union[int, str]]) -> None:
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
def create_state_space_tree(
sequence: List[Union[int, str]],
current_sequence: List[Union[int, str]],
index: int,
index_used: List[int],
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_sequence)
return
for i in range(len(sequence)):
if not index_used[i]:
current_sequence.append(sequence[i])
index_used[i] = True
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
current_sequence.pop()
index_used[i] = False
"""
remove the comment to take an input from the user
print("Enter the elements")
sequence = list(map(int, input().split()))
"""
sequence: List[Union[int, str]] = [3, 1, 2, 4]
generate_all_permutations(sequence)
sequence_2: List[Union[int, str]] = ["A", "B", "C"]
generate_all_permutations(sequence_2)
| """
In this problem, we want to determine all possible permutations
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(n! * n),
where n denotes the length of the given sequence.
"""
from typing import List, Union
def generate_all_permutations(sequence: List[Union[int, str]]) -> None:
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
def create_state_space_tree(
sequence: List[Union[int, str]],
current_sequence: List[Union[int, str]],
index: int,
index_used: List[int],
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_sequence)
return
for i in range(len(sequence)):
if not index_used[i]:
current_sequence.append(sequence[i])
index_used[i] = True
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
current_sequence.pop()
index_used[i] = False
"""
remove the comment to take an input from the user
print("Enter the elements")
sequence = list(map(int, input().split()))
"""
sequence: List[Union[int, str]] = [3, 1, 2, 4]
generate_all_permutations(sequence)
sequence_2: List[Union[int, str]] = ["A", "B", "C"]
generate_all_permutations(sequence_2)
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from typing import Callable
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
"""
finds where function becomes 0 in [a,b] using bolzano
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
1.0000000149011612
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
1.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
3.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
"""
start: float = a
end: float = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
function(a) * function(b) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval.")
else:
mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
mid = start + (end - start) / 2.0
return mid
def f(x: float) -> float:
return x ** 3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| from typing import Callable
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
"""
finds where function becomes 0 in [a,b] using bolzano
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
1.0000000149011612
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
1.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
3.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
"""
start: float = a
end: float = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
function(a) * function(b) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval.")
else:
mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
mid = start + (end - start) / 2.0
return mid
def f(x: float) -> float:
return x ** 3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century
unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
def solution():
"""Returns the number of mondays that fall on the first of the month during
the twentieth century (1 Jan 1901 to 31 Dec 2000)?
>>> solution()
171
"""
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = 6
month = 1
year = 1901
sundays = 0
while year < 2001:
day += 7
if (year % 4 == 0 and not year % 100 == 0) or (year % 400 == 0):
if day > days_per_month[month - 1] and month != 2:
month += 1
day = day - days_per_month[month - 2]
elif day > 29 and month == 2:
month += 1
day = day - 29
else:
if day > days_per_month[month - 1]:
month += 1
day = day - days_per_month[month - 2]
if month > 12:
year += 1
month = 1
if year < 2001 and day == 1:
sundays += 1
return sundays
if __name__ == "__main__":
print(solution())
| """
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century
unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
def solution():
"""Returns the number of mondays that fall on the first of the month during
the twentieth century (1 Jan 1901 to 31 Dec 2000)?
>>> solution()
171
"""
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = 6
month = 1
year = 1901
sundays = 0
while year < 2001:
day += 7
if (year % 4 == 0 and not year % 100 == 0) or (year % 400 == 0):
if day > days_per_month[month - 1] and month != 2:
month += 1
day = day - days_per_month[month - 2]
elif day > 29 and month == 2:
month += 1
day = day - 29
else:
if day > days_per_month[month - 1]:
month += 1
day = day - days_per_month[month - 2]
if month > 12:
year += 1
month = 1
if year < 2001 and day == 1:
sundays += 1
return sundays
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is to show simple COVID19 info fetching from worldometers site using lxml
* The main motivation to use lxml in place of bs4 is that it is faster and therefore
more convenient to use in Python web projects (e.g. Django or Flask-based)
"""
from collections import namedtuple
import requests
from lxml import html # type: ignore
covid_data = namedtuple("covid_data", "cases deaths recovered")
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
fmt = """Total COVID-19 cases in the world: {}
Total deaths due to COVID-19 in the world: {}
Total COVID-19 patients recovered in the world: {}"""
print(fmt.format(*covid_stats()))
| """
This is to show simple COVID19 info fetching from worldometers site using lxml
* The main motivation to use lxml in place of bs4 is that it is faster and therefore
more convenient to use in Python web projects (e.g. Django or Flask-based)
"""
from collections import namedtuple
import requests
from lxml import html # type: ignore
covid_data = namedtuple("covid_data", "cases deaths recovered")
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
fmt = """Total COVID-19 cases in the world: {}
Total deaths due to COVID-19 in the world: {}
Total COVID-19 patients recovered in the world: {}"""
print(fmt.format(*covid_stats()))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The nested brackets problem is a problem that determines if a sequence of
brackets are properly nested. A sequence of brackets s is considered properly nested
if any of the following conditions are true:
- s is empty
- s has the form (U) or [U] or {U} where U is a properly nested string
- s has the form VW where V and W are properly nested strings
For example, the string "()()[()]" is properly nested but "[(()]" is not.
The function called is_balanced takes as input a string S which is a sequence of
brackets and returns true if S is nested and false otherwise.
"""
def is_balanced(S):
stack = []
open_brackets = set({"(", "[", "{"})
closed_brackets = set({")", "]", "}"})
open_to_closed = dict({"{": "}", "[": "]", "(": ")"})
for i in range(len(S)):
if S[i] in open_brackets:
stack.append(S[i])
elif S[i] in closed_brackets:
if len(stack) == 0 or (
len(stack) > 0 and open_to_closed[stack.pop()] != S[i]
):
return False
return len(stack) == 0
def main():
s = input("Enter sequence of brackets: ")
if is_balanced(s):
print(s, "is balanced")
else:
print(s, "is not balanced")
if __name__ == "__main__":
main()
| """
The nested brackets problem is a problem that determines if a sequence of
brackets are properly nested. A sequence of brackets s is considered properly nested
if any of the following conditions are true:
- s is empty
- s has the form (U) or [U] or {U} where U is a properly nested string
- s has the form VW where V and W are properly nested strings
For example, the string "()()[()]" is properly nested but "[(()]" is not.
The function called is_balanced takes as input a string S which is a sequence of
brackets and returns true if S is nested and false otherwise.
"""
def is_balanced(S):
stack = []
open_brackets = set({"(", "[", "{"})
closed_brackets = set({")", "]", "}"})
open_to_closed = dict({"{": "}", "[": "]", "(": ")"})
for i in range(len(S)):
if S[i] in open_brackets:
stack.append(S[i])
elif S[i] in closed_brackets:
if len(stack) == 0 or (
len(stack) > 0 and open_to_closed[stack.pop()] != S[i]
):
return False
return len(stack) == 0
def main():
s = input("Enter sequence of brackets: ")
if is_balanced(s):
print(s, "is balanced")
else:
print(s, "is not balanced")
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
this algorithm tries to find the pattern from every position of
the mainString if pattern is found from position i it add it to
the answer and does the same for position i+1
Complexity : O(n*m)
n=length of main string
m=length of pattern string
"""
def naive_pattern_search(s: str, pattern: str) -> list:
"""
>>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")
[4, 10, 18]
>>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")
[]
>>> naive_pattern_search("", "ABC")
[]
>>> naive_pattern_search("TEST", "TEST")
[0]
>>> naive_pattern_search("ABCDEGFTEST", "TEST")
[7]
"""
pat_len = len(pattern)
position = []
for i in range(len(s) - pat_len + 1):
match_found = True
for j in range(pat_len):
if s[i + j] != pattern[j]:
match_found = False
break
if match_found:
position.append(i)
return position
if __name__ == "__main__":
assert naive_pattern_search("ABCDEFG", "DE") == [3]
print(f"{naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC') = }")
| """
https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
this algorithm tries to find the pattern from every position of
the mainString if pattern is found from position i it add it to
the answer and does the same for position i+1
Complexity : O(n*m)
n=length of main string
m=length of pattern string
"""
def naive_pattern_search(s: str, pattern: str) -> list:
"""
>>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")
[4, 10, 18]
>>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")
[]
>>> naive_pattern_search("", "ABC")
[]
>>> naive_pattern_search("TEST", "TEST")
[0]
>>> naive_pattern_search("ABCDEGFTEST", "TEST")
[7]
"""
pat_len = len(pattern)
position = []
for i in range(len(s) - pat_len + 1):
match_found = True
for j in range(pat_len):
if s[i + j] != pattern[j]:
match_found = False
break
if match_found:
position.append(i)
return position
if __name__ == "__main__":
assert naive_pattern_search("ABCDEFG", "DE") == [3]
print(f"{naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC') = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import sys
import webbrowser
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print("Googling.....")
url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
res = requests.get(url, headers={"UserAgent": UserAgent().random})
# res.raise_for_status()
with open("project1a.html", "wb") as out_file: # only for knowing the class
for data in res.iter_content(10000):
out_file.write(data)
soup = BeautifulSoup(res.text, "html.parser")
links = list(soup.select(".eZt8xd"))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get("href"))
else:
webbrowser.open(f"http://google.com{link.get('href')}")
| import sys
import webbrowser
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print("Googling.....")
url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
res = requests.get(url, headers={"UserAgent": UserAgent().random})
# res.raise_for_status()
with open("project1a.html", "wb") as out_file: # only for knowing the class
for data in res.iter_content(10000):
out_file.write(data)
soup = BeautifulSoup(res.text, "html.parser")
links = list(soup.select(".eZt8xd"))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get("href"))
else:
webbrowser.open(f"http://google.com{link.get('href')}")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Checks if a system of forces is in static equilibrium.
"""
from typing import List
from numpy import array, cos, cross, radians, sin
def polar_force(
magnitude: float, angle: float, radian_mode: bool = False
) -> List[float]:
"""
Resolves force along rectangular components.
(force, angle) => (force_x, force_y)
>>> polar_force(10, 45)
[7.0710678118654755, 7.071067811865475]
>>> polar_force(10, 3.14, radian_mode=True)
[-9.999987317275394, 0.01592652916486828]
"""
if radian_mode:
return [magnitude * cos(angle), magnitude * sin(angle)]
return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))]
def in_static_equilibrium(
forces: array, location: array, eps: float = 10 ** -1
) -> bool:
"""
Check if a system is in equilibrium.
It takes two numpy.array objects.
forces ==> [
[force1_x, force1_y],
[force2_x, force2_y],
....]
location ==> [
[x1, y1],
[x2, y2],
....]
>>> force = array([[1, 1], [-1, 2]])
>>> location = array([[1, 0], [10, 0]])
>>> in_static_equilibrium(force, location)
False
"""
# summation of moments is zero
moments: array = cross(location, forces)
sum_moments: float = sum(moments)
return abs(sum_moments) < eps
if __name__ == "__main__":
# Test to check if it works
forces = array(
[polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90)]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
forces = array(
[
polar_force(30 * 9.81, 15),
polar_force(215, 180 - 45),
polar_force(264, 90 - 30),
]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])
location = array([[0, 0], [6, 0], [10, 0], [12, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| """
Checks if a system of forces is in static equilibrium.
"""
from typing import List
from numpy import array, cos, cross, radians, sin
def polar_force(
magnitude: float, angle: float, radian_mode: bool = False
) -> List[float]:
"""
Resolves force along rectangular components.
(force, angle) => (force_x, force_y)
>>> polar_force(10, 45)
[7.0710678118654755, 7.071067811865475]
>>> polar_force(10, 3.14, radian_mode=True)
[-9.999987317275394, 0.01592652916486828]
"""
if radian_mode:
return [magnitude * cos(angle), magnitude * sin(angle)]
return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))]
def in_static_equilibrium(
forces: array, location: array, eps: float = 10 ** -1
) -> bool:
"""
Check if a system is in equilibrium.
It takes two numpy.array objects.
forces ==> [
[force1_x, force1_y],
[force2_x, force2_y],
....]
location ==> [
[x1, y1],
[x2, y2],
....]
>>> force = array([[1, 1], [-1, 2]])
>>> location = array([[1, 0], [10, 0]])
>>> in_static_equilibrium(force, location)
False
"""
# summation of moments is zero
moments: array = cross(location, forces)
sum_moments: float = sum(moments)
return abs(sum_moments) < eps
if __name__ == "__main__":
# Test to check if it works
forces = array(
[polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90)]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
forces = array(
[
polar_force(30 * 9.81, 15),
polar_force(215, 180 - 45),
polar_force(264, 90 - 30),
]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])
location = array([[0, 0], [6, 0], [10, 0], [12, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def binomial_coefficient(n, r):
"""
Find binomial coefficient using pascals triangle.
>>> binomial_coefficient(10, 5)
252
"""
C = [0 for i in range(r + 1)]
# nc0 = 1
C[0] = 1
for i in range(1, n + 1):
# to compute current row from previous row.
j = min(i, r)
while j > 0:
C[j] += C[j - 1]
j -= 1
return C[r]
print(binomial_coefficient(n=10, r=5))
| def binomial_coefficient(n, r):
"""
Find binomial coefficient using pascals triangle.
>>> binomial_coefficient(10, 5)
252
"""
C = [0 for i in range(r + 1)]
# nc0 = 1
C[0] = 1
for i in range(1, n + 1):
# to compute current row from previous row.
j = min(i, r)
while j > 0:
C[j] += C[j - 1]
j -= 1
return C[r]
print(binomial_coefficient(n=10, r=5))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 45: https://projecteuler.net/problem=45
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ...
Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ...
Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ...
It can be verified that T(285) = P(165) = H(143) = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
All trinagle numbers are hexagonal numbers.
T(2n-1) = n * (2 * n - 1) = H(n)
So we shall check only for hexagonal numbers which are also pentagonal.
"""
def hexagonal_num(n: int) -> int:
"""
Returns nth hexagonal number
>>> hexagonal_num(143)
40755
>>> hexagonal_num(21)
861
>>> hexagonal_num(10)
190
"""
return n * (2 * n - 1)
def is_pentagonal(n: int) -> bool:
"""
Returns True if n is pentagonal, False otherwise.
>>> is_pentagonal(330)
True
>>> is_pentagonal(7683)
False
>>> is_pentagonal(2380)
True
"""
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(start: int = 144) -> int:
"""
Returns the next number which is traingular, pentagonal and hexagonal.
>>> solution(144)
1533776805
"""
n = start
num = hexagonal_num(n)
while not is_pentagonal(num):
n += 1
num = hexagonal_num(n)
return num
if __name__ == "__main__":
print(f"{solution()} = ")
| """
Problem 45: https://projecteuler.net/problem=45
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ...
Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ...
Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ...
It can be verified that T(285) = P(165) = H(143) = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
All trinagle numbers are hexagonal numbers.
T(2n-1) = n * (2 * n - 1) = H(n)
So we shall check only for hexagonal numbers which are also pentagonal.
"""
def hexagonal_num(n: int) -> int:
"""
Returns nth hexagonal number
>>> hexagonal_num(143)
40755
>>> hexagonal_num(21)
861
>>> hexagonal_num(10)
190
"""
return n * (2 * n - 1)
def is_pentagonal(n: int) -> bool:
"""
Returns True if n is pentagonal, False otherwise.
>>> is_pentagonal(330)
True
>>> is_pentagonal(7683)
False
>>> is_pentagonal(2380)
True
"""
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(start: int = 144) -> int:
"""
Returns the next number which is traingular, pentagonal and hexagonal.
>>> solution(144)
1533776805
"""
n = start
num = hexagonal_num(n)
while not is_pentagonal(num):
n += 1
num = hexagonal_num(n)
return num
if __name__ == "__main__":
print(f"{solution()} = ")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A permutation is an ordered arrangement of objects. For example, 3124 is one
possible permutation of the digits 1, 2, 3 and 4. If all of the permutations
are listed numerically or alphabetically, we call it lexicographic order. The
lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5,
6, 7, 8 and 9?
"""
from itertools import permutations
def solution():
"""Returns the millionth lexicographic permutation of the digits 0, 1, 2,
3, 4, 5, 6, 7, 8 and 9.
>>> solution()
'2783915460'
"""
result = list(map("".join, permutations("0123456789")))
return result[999999]
if __name__ == "__main__":
print(solution())
| """
A permutation is an ordered arrangement of objects. For example, 3124 is one
possible permutation of the digits 1, 2, 3 and 4. If all of the permutations
are listed numerically or alphabetically, we call it lexicographic order. The
lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5,
6, 7, 8 and 9?
"""
from itertools import permutations
def solution():
"""Returns the millionth lexicographic permutation of the digits 0, 1, 2,
3, 4, 5, 6, 7, 8 and 9.
>>> solution()
'2783915460'
"""
result = list(map("".join, permutations("0123456789")))
return result[999999]
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/bin/sh
#
# Copyright (c) 2006, 2008 Junio C Hamano
#
# The "pre-rebase" hook is run just before "git rebase" starts doing
# its job, and can prevent the command from running by exiting with
# non-zero status.
#
# The hook is called with the following parameters:
#
# $1 -- the upstream the series was forked from.
# $2 -- the branch being rebased (or empty when rebasing the current branch).
#
# This sample shows how to prevent topic branches that are already
# merged to 'next' branch from getting rebased, because allowing it
# would result in rebasing already published history.
publish=next
basebranch="$1"
if test "$#" = 2
then
topic="refs/heads/$2"
else
topic=`git symbolic-ref HEAD` ||
exit 0 ;# we do not interrupt rebasing detached HEAD
fi
case "$topic" in
refs/heads/??/*)
;;
*)
exit 0 ;# we do not interrupt others.
;;
esac
# Now we are dealing with a topic branch being rebased
# on top of master. Is it OK to rebase it?
# Does the topic really exist?
git show-ref -q "$topic" || {
echo >&2 "No such branch $topic"
exit 1
}
# Is topic fully merged to master?
not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
if test -z "$not_in_master"
then
echo >&2 "$topic is fully merged to master; better remove it."
exit 1 ;# we could allow it, but there is no point.
fi
# Is topic ever merged to next? If so you should not be rebasing it.
only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
only_next_2=`git rev-list ^master ${publish} | sort`
if test "$only_next_1" = "$only_next_2"
then
not_in_topic=`git rev-list "^$topic" master`
if test -z "$not_in_topic"
then
echo >&2 "$topic is already up to date with master"
exit 1 ;# we could allow it, but there is no point.
else
exit 0
fi
else
not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
/usr/bin/perl -e '
my $topic = $ARGV[0];
my $msg = "* $topic has commits already merged to public branch:\n";
my (%not_in_next) = map {
/^([0-9a-f]+) /;
($1 => 1);
} split(/\n/, $ARGV[1]);
for my $elem (map {
/^([0-9a-f]+) (.*)$/;
[$1 => $2];
} split(/\n/, $ARGV[2])) {
if (!exists $not_in_next{$elem->[0]}) {
if ($msg) {
print STDERR $msg;
undef $msg;
}
print STDERR " $elem->[1]\n";
}
}
' "$topic" "$not_in_next" "$not_in_master"
exit 1
fi
<<\DOC_END
This sample hook safeguards topic branches that have been
published from being rewound.
The workflow assumed here is:
* Once a topic branch forks from "master", "master" is never
merged into it again (either directly or indirectly).
* Once a topic branch is fully cooked and merged into "master",
it is deleted. If you need to build on top of it to correct
earlier mistakes, a new topic branch is created by forking at
the tip of the "master". This is not strictly necessary, but
it makes it easier to keep your history simple.
* Whenever you need to test or publish your changes to topic
branches, merge them into "next" branch.
The script, being an example, hardcodes the publish branch name
to be "next", but it is trivial to make it configurable via
$GIT_DIR/config mechanism.
With this workflow, you would want to know:
(1) ... if a topic branch has ever been merged to "next". Young
topic branches can have stupid mistakes you would rather
clean up before publishing, and things that have not been
merged into other branches can be easily rebased without
affecting other people. But once it is published, you would
not want to rewind it.
(2) ... if a topic branch has been fully merged to "master".
Then you can delete it. More importantly, you should not
build on top of it -- other people may already want to
change things related to the topic as patches against your
"master", so if you need further changes, it is better to
fork the topic (perhaps with the same name) afresh from the
tip of "master".
Let's look at this example:
o---o---o---o---o---o---o---o---o---o "next"
/ / / /
/ a---a---b A / /
/ / / /
/ / c---c---c---c B /
/ / / \ /
/ / / b---b C \ /
/ / / / \ /
---o---o---o---o---o---o---o---o---o---o---o "master"
A, B and C are topic branches.
* A has one fix since it was merged up to "next".
* B has finished. It has been fully merged up to "master" and "next",
and is ready to be deleted.
* C has not merged to "next" at all.
We would want to allow C to be rebased, refuse A, and encourage
B to be deleted.
To compute (1):
git rev-list ^master ^topic next
git rev-list ^master next
if these match, topic has not merged in next at all.
To compute (2):
git rev-list master..topic
if this is empty, it is fully merged to "master".
DOC_END
| #!/bin/sh
#
# Copyright (c) 2006, 2008 Junio C Hamano
#
# The "pre-rebase" hook is run just before "git rebase" starts doing
# its job, and can prevent the command from running by exiting with
# non-zero status.
#
# The hook is called with the following parameters:
#
# $1 -- the upstream the series was forked from.
# $2 -- the branch being rebased (or empty when rebasing the current branch).
#
# This sample shows how to prevent topic branches that are already
# merged to 'next' branch from getting rebased, because allowing it
# would result in rebasing already published history.
publish=next
basebranch="$1"
if test "$#" = 2
then
topic="refs/heads/$2"
else
topic=`git symbolic-ref HEAD` ||
exit 0 ;# we do not interrupt rebasing detached HEAD
fi
case "$topic" in
refs/heads/??/*)
;;
*)
exit 0 ;# we do not interrupt others.
;;
esac
# Now we are dealing with a topic branch being rebased
# on top of master. Is it OK to rebase it?
# Does the topic really exist?
git show-ref -q "$topic" || {
echo >&2 "No such branch $topic"
exit 1
}
# Is topic fully merged to master?
not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
if test -z "$not_in_master"
then
echo >&2 "$topic is fully merged to master; better remove it."
exit 1 ;# we could allow it, but there is no point.
fi
# Is topic ever merged to next? If so you should not be rebasing it.
only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
only_next_2=`git rev-list ^master ${publish} | sort`
if test "$only_next_1" = "$only_next_2"
then
not_in_topic=`git rev-list "^$topic" master`
if test -z "$not_in_topic"
then
echo >&2 "$topic is already up to date with master"
exit 1 ;# we could allow it, but there is no point.
else
exit 0
fi
else
not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
/usr/bin/perl -e '
my $topic = $ARGV[0];
my $msg = "* $topic has commits already merged to public branch:\n";
my (%not_in_next) = map {
/^([0-9a-f]+) /;
($1 => 1);
} split(/\n/, $ARGV[1]);
for my $elem (map {
/^([0-9a-f]+) (.*)$/;
[$1 => $2];
} split(/\n/, $ARGV[2])) {
if (!exists $not_in_next{$elem->[0]}) {
if ($msg) {
print STDERR $msg;
undef $msg;
}
print STDERR " $elem->[1]\n";
}
}
' "$topic" "$not_in_next" "$not_in_master"
exit 1
fi
<<\DOC_END
This sample hook safeguards topic branches that have been
published from being rewound.
The workflow assumed here is:
* Once a topic branch forks from "master", "master" is never
merged into it again (either directly or indirectly).
* Once a topic branch is fully cooked and merged into "master",
it is deleted. If you need to build on top of it to correct
earlier mistakes, a new topic branch is created by forking at
the tip of the "master". This is not strictly necessary, but
it makes it easier to keep your history simple.
* Whenever you need to test or publish your changes to topic
branches, merge them into "next" branch.
The script, being an example, hardcodes the publish branch name
to be "next", but it is trivial to make it configurable via
$GIT_DIR/config mechanism.
With this workflow, you would want to know:
(1) ... if a topic branch has ever been merged to "next". Young
topic branches can have stupid mistakes you would rather
clean up before publishing, and things that have not been
merged into other branches can be easily rebased without
affecting other people. But once it is published, you would
not want to rewind it.
(2) ... if a topic branch has been fully merged to "master".
Then you can delete it. More importantly, you should not
build on top of it -- other people may already want to
change things related to the topic as patches against your
"master", so if you need further changes, it is better to
fork the topic (perhaps with the same name) afresh from the
tip of "master".
Let's look at this example:
o---o---o---o---o---o---o---o---o---o "next"
/ / / /
/ a---a---b A / /
/ / / /
/ / c---c---c---c B /
/ / / \ /
/ / / b---b C \ /
/ / / / \ /
---o---o---o---o---o---o---o---o---o---o---o "master"
A, B and C are topic branches.
* A has one fix since it was merged up to "next".
* B has finished. It has been fully merged up to "master" and "next",
and is ready to be deleted.
* C has not merged to "next" at all.
We would want to allow C to be rebased, refuse A, and encourage
B to be deleted.
To compute (1):
git rev-list ^master ^topic next
git rev-list ^master next
if these match, topic has not merged in next at all.
To compute (2):
git rev-list master..topic
if this is empty, it is fully merged to "master".
DOC_END
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Wiggle Sort.
Given an unsorted array nums, reorder it such
that nums[0] < nums[1] > nums[2] < nums[3]....
For example:
if input numbers = [3, 5, 2, 1, 6, 4]
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
"""
def wiggle_sort(nums: list) -> list:
"""
Python implementation of wiggle.
Example:
>>> wiggle_sort([0, 5, 3, 2, 2])
[0, 5, 2, 3, 2]
>>> wiggle_sort([])
[]
>>> wiggle_sort([-2, -5, -45])
[-45, -2, -5]
>>> wiggle_sort([-2.1, -5.68, -45.11])
[-45.11, -2.1, -5.68]
"""
for i, _ in enumerate(nums):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
return nums
if __name__ == "__main__":
print("Enter the array elements:")
array = list(map(int, input().split()))
print("The unsorted array is:")
print(array)
print("Array after Wiggle sort:")
print(wiggle_sort(array))
| """
Wiggle Sort.
Given an unsorted array nums, reorder it such
that nums[0] < nums[1] > nums[2] < nums[3]....
For example:
if input numbers = [3, 5, 2, 1, 6, 4]
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
"""
def wiggle_sort(nums: list) -> list:
"""
Python implementation of wiggle.
Example:
>>> wiggle_sort([0, 5, 3, 2, 2])
[0, 5, 2, 3, 2]
>>> wiggle_sort([])
[]
>>> wiggle_sort([-2, -5, -45])
[-45, -2, -5]
>>> wiggle_sort([-2.1, -5.68, -45.11])
[-45.11, -2.1, -5.68]
"""
for i, _ in enumerate(nums):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
return nums
if __name__ == "__main__":
print("Enter the array elements:")
array = list(map(int, input().split()))
print("The unsorted array is:")
print(array)
print("Array after Wiggle sort:")
print(wiggle_sort(array))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Algorithm that merges two sorted linked lists into one sorted linked list.
"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import Optional
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class Node:
data: int
next: Optional[Node]
class SortedLinkedList:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Optional[Node] = None
for i in reversed(sorted(ints)):
self.head = Node(i, self.head)
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))
True
>>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))
True
"""
node = self.head
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(SortedLinkedList(range(i))) == i
True
True
True
>>> len(SortedLinkedList(test_data_odd))
8
"""
return len(tuple(iter(self)))
def __str__(self) -> str:
"""
>>> str(SortedLinkedList([]))
''
>>> str(SortedLinkedList(test_data_odd))
'-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'
>>> str(SortedLinkedList(test_data_even))
'-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'
"""
return " -> ".join([str(node) for node in self])
def merge_lists(
sll_one: SortedLinkedList, sll_two: SortedLinkedList
) -> SortedLinkedList:
"""
>>> SSL = SortedLinkedList
>>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))
>>> len(merged)
16
>>> str(merged)
'-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'
>>> list(merged) == list(sorted(test_data_odd + test_data_even))
True
"""
return SortedLinkedList(list(sll_one) + list(sll_two))
if __name__ == "__main__":
import doctest
doctest.testmod()
SSL = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| """
Algorithm that merges two sorted linked lists into one sorted linked list.
"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import Optional
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class Node:
data: int
next: Optional[Node]
class SortedLinkedList:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Optional[Node] = None
for i in reversed(sorted(ints)):
self.head = Node(i, self.head)
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))
True
>>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))
True
"""
node = self.head
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(SortedLinkedList(range(i))) == i
True
True
True
>>> len(SortedLinkedList(test_data_odd))
8
"""
return len(tuple(iter(self)))
def __str__(self) -> str:
"""
>>> str(SortedLinkedList([]))
''
>>> str(SortedLinkedList(test_data_odd))
'-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'
>>> str(SortedLinkedList(test_data_even))
'-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'
"""
return " -> ".join([str(node) for node in self])
def merge_lists(
sll_one: SortedLinkedList, sll_two: SortedLinkedList
) -> SortedLinkedList:
"""
>>> SSL = SortedLinkedList
>>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))
>>> len(merged)
16
>>> str(merged)
'-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'
>>> list(merged) == list(sorted(test_data_odd + test_data_even))
True
"""
return SortedLinkedList(list(sll_one) + list(sll_two))
if __name__ == "__main__":
import doctest
doctest.testmod()
SSL = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Isolate the Decimal part of a Number
https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point
"""
def decimal_isolate(number, digitAmount):
"""
Isolates the decimal part of a number.
If digitAmount > 0 round to that decimal place, else print the entire decimal.
>>> decimal_isolate(1.53, 0)
0.53
>>> decimal_isolate(35.345, 1)
0.3
>>> decimal_isolate(35.345, 2)
0.34
>>> decimal_isolate(35.345, 3)
0.345
>>> decimal_isolate(-14.789, 3)
-0.789
>>> decimal_isolate(0, 2)
0
>>> decimal_isolate(-14.123, 1)
-0.1
>>> decimal_isolate(-14.123, 2)
-0.12
>>> decimal_isolate(-14.123, 3)
-0.123
"""
if digitAmount > 0:
return round(number - int(number), digitAmount)
return number - int(number)
if __name__ == "__main__":
print(decimal_isolate(1.53, 0))
print(decimal_isolate(35.345, 1))
print(decimal_isolate(35.345, 2))
print(decimal_isolate(35.345, 3))
print(decimal_isolate(-14.789, 3))
print(decimal_isolate(0, 2))
print(decimal_isolate(-14.123, 1))
print(decimal_isolate(-14.123, 2))
print(decimal_isolate(-14.123, 3))
| """
Isolate the Decimal part of a Number
https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point
"""
def decimal_isolate(number, digitAmount):
"""
Isolates the decimal part of a number.
If digitAmount > 0 round to that decimal place, else print the entire decimal.
>>> decimal_isolate(1.53, 0)
0.53
>>> decimal_isolate(35.345, 1)
0.3
>>> decimal_isolate(35.345, 2)
0.34
>>> decimal_isolate(35.345, 3)
0.345
>>> decimal_isolate(-14.789, 3)
-0.789
>>> decimal_isolate(0, 2)
0
>>> decimal_isolate(-14.123, 1)
-0.1
>>> decimal_isolate(-14.123, 2)
-0.12
>>> decimal_isolate(-14.123, 3)
-0.123
"""
if digitAmount > 0:
return round(number - int(number), digitAmount)
return number - int(number)
if __name__ == "__main__":
print(decimal_isolate(1.53, 0))
print(decimal_isolate(35.345, 1))
print(decimal_isolate(35.345, 2))
print(decimal_isolate(35.345, 3))
print(decimal_isolate(-14.789, 3))
print(decimal_isolate(0, 2))
print(decimal_isolate(-14.123, 1))
print(decimal_isolate(-14.123, 2))
print(decimal_isolate(-14.123, 3))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Recaptcha is a free captcha service offered by Google in order to secure websites and
forms. At https://www.google.com/recaptcha/admin/create you can create new recaptcha
keys and see the keys that your have already created.
* Keep in mind that recaptcha doesn't work with localhost
When you create a recaptcha key, your will get two separate keys: ClientKey & SecretKey.
ClientKey should be kept in your site's front end
SecretKey should be kept in your site's back end
# An example HTML login form with recaptcha tag is shown below
<form action="" method="post">
<h2 class="text-center">Log in</h2>
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" required="required">
</div>
<div class="form-group">
<input type="password" name="password" required="required">
</div>
<div class="form-group">
<button type="submit">Log in</button>
</div>
<!-- Below is the recaptcha tag of html -->
<div class="g-recaptcha" data-sitekey="ClientKey"></div>
</form>
<!-- Below is the recaptcha script to be kept inside html tag -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Below a Django function for the views.py file contains a login form for demonstrating
recaptcha verification.
"""
import requests
try:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect, render
except ImportError:
authenticate = login = render = redirect = print
def login_using_recaptcha(request):
# Enter your recaptcha secret key here
secret_key = "secretKey"
url = "https://www.google.com/recaptcha/api/siteverify"
# when method is not POST, direct user to login page
if request.method != "POST":
return render(request, "login.html")
# from the frontend, get username, password, and client_key
username = request.POST.get("username")
password = request.POST.get("password")
client_key = request.POST.get("g-recaptcha-response")
# post recaptcha response to Google's recaptcha api
response = requests.post(url, data={"secret": secret_key, "response": client_key})
# if the recaptcha api verified our keys
if response.json().get("success", False):
# authenticate the user
user_in_database = authenticate(request, username=username, password=password)
if user_in_database:
login(request, user_in_database)
return redirect("/your-webpage")
return render(request, "login.html")
| """
Recaptcha is a free captcha service offered by Google in order to secure websites and
forms. At https://www.google.com/recaptcha/admin/create you can create new recaptcha
keys and see the keys that your have already created.
* Keep in mind that recaptcha doesn't work with localhost
When you create a recaptcha key, your will get two separate keys: ClientKey & SecretKey.
ClientKey should be kept in your site's front end
SecretKey should be kept in your site's back end
# An example HTML login form with recaptcha tag is shown below
<form action="" method="post">
<h2 class="text-center">Log in</h2>
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" required="required">
</div>
<div class="form-group">
<input type="password" name="password" required="required">
</div>
<div class="form-group">
<button type="submit">Log in</button>
</div>
<!-- Below is the recaptcha tag of html -->
<div class="g-recaptcha" data-sitekey="ClientKey"></div>
</form>
<!-- Below is the recaptcha script to be kept inside html tag -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Below a Django function for the views.py file contains a login form for demonstrating
recaptcha verification.
"""
import requests
try:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect, render
except ImportError:
authenticate = login = render = redirect = print
def login_using_recaptcha(request):
# Enter your recaptcha secret key here
secret_key = "secretKey"
url = "https://www.google.com/recaptcha/api/siteverify"
# when method is not POST, direct user to login page
if request.method != "POST":
return render(request, "login.html")
# from the frontend, get username, password, and client_key
username = request.POST.get("username")
password = request.POST.get("password")
client_key = request.POST.get("g-recaptcha-response")
# post recaptcha response to Google's recaptcha api
response = requests.post(url, data={"secret": secret_key, "response": client_key})
# if the recaptcha api verified our keys
if response.json().get("success", False):
# authenticate the user
user_in_database = authenticate(request, username=username, password=password)
if user_in_database:
login(request, user_in_database)
return redirect("/your-webpage")
return render(request, "login.html")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """ A Queue using a linked list like structure """
from typing import Any
class Node:
def __init__(self, data: Any) -> None:
self.data = data
self.next = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedQueue:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> queue.put(5)
>>> queue.put(9)
>>> queue.put('python')
>>> queue.is_empty();
False
>>> queue.get()
5
>>> queue.put('algorithms')
>>> queue.get()
9
>>> queue.get()
'python'
>>> queue.get()
'algorithms'
>>> queue.is_empty()
True
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
"""
def __init__(self) -> None:
self.front = self.rear = None
def __iter__(self):
node = self.front
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> len(queue)
5
>>> for i in range(1, 6):
... assert len(queue) == 6 - i
... _ = queue.get()
>>> len(queue)
0
"""
return len(tuple(iter(self)))
def __str__(self) -> str:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 4):
... queue.put(i)
>>> queue.put("Python")
>>> queue.put(3.14)
>>> queue.put(True)
>>> str(queue)
'1 <- 2 <- 3 <- Python <- 3.14 <- True'
"""
return " <- ".join(str(item) for item in self)
def is_empty(self) -> bool:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.is_empty()
False
"""
return len(self) == 0
def put(self, item) -> None:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> for i in range(1, 6):
... queue.put(i)
>>> str(queue)
'1 <- 2 <- 3 <- 4 <- 5'
"""
node = Node(item)
if self.is_empty():
self.front = self.rear = node
else:
assert isinstance(self.rear, Node)
self.rear.next = node
self.rear = node
def get(self) -> Any:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> for i in range(1, 6):
... assert queue.get() == i
>>> len(queue)
0
"""
if self.is_empty():
raise IndexError("dequeue from empty queue")
assert isinstance(self.front, Node)
node = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
return node.data
def clear(self) -> None:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.clear()
>>> len(queue)
0
>>> str(queue)
''
"""
self.front = self.rear = None
if __name__ == "__main__":
from doctest import testmod
testmod()
| """ A Queue using a linked list like structure """
from typing import Any
class Node:
def __init__(self, data: Any) -> None:
self.data = data
self.next = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedQueue:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> queue.put(5)
>>> queue.put(9)
>>> queue.put('python')
>>> queue.is_empty();
False
>>> queue.get()
5
>>> queue.put('algorithms')
>>> queue.get()
9
>>> queue.get()
'python'
>>> queue.get()
'algorithms'
>>> queue.is_empty()
True
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
"""
def __init__(self) -> None:
self.front = self.rear = None
def __iter__(self):
node = self.front
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> len(queue)
5
>>> for i in range(1, 6):
... assert len(queue) == 6 - i
... _ = queue.get()
>>> len(queue)
0
"""
return len(tuple(iter(self)))
def __str__(self) -> str:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 4):
... queue.put(i)
>>> queue.put("Python")
>>> queue.put(3.14)
>>> queue.put(True)
>>> str(queue)
'1 <- 2 <- 3 <- Python <- 3.14 <- True'
"""
return " <- ".join(str(item) for item in self)
def is_empty(self) -> bool:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.is_empty()
False
"""
return len(self) == 0
def put(self, item) -> None:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> for i in range(1, 6):
... queue.put(i)
>>> str(queue)
'1 <- 2 <- 3 <- 4 <- 5'
"""
node = Node(item)
if self.is_empty():
self.front = self.rear = node
else:
assert isinstance(self.rear, Node)
self.rear.next = node
self.rear = node
def get(self) -> Any:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> for i in range(1, 6):
... assert queue.get() == i
>>> len(queue)
0
"""
if self.is_empty():
raise IndexError("dequeue from empty queue")
assert isinstance(self.front, Node)
node = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
return node.data
def clear(self) -> None:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.clear()
>>> len(queue)
0
>>> str(queue)
''
"""
self.front = self.rear = None
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
def n31(a: int) -> tuple[list[int], int]:
"""
Returns the Collatz sequence and its length of any positive integer.
>>> n31(4)
([4, 2, 1], 3)
"""
if not isinstance(a, int):
raise TypeError(f"Must be int, not {type(a).__name__}")
if a < 1:
raise ValueError(f"Given integer must be greater than 1, not {a}")
path = [a]
while a != 1:
if a % 2 == 0:
a = a // 2
else:
a = 3 * a + 1
path += [a]
return path, len(path)
def test_n31():
"""
>>> test_n31()
"""
assert n31(4) == ([4, 2, 1], 3)
assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15)
assert n31(31) == (
[
31,
94,
47,
142,
71,
214,
107,
322,
161,
484,
242,
121,
364,
182,
91,
274,
137,
412,
206,
103,
310,
155,
466,
233,
700,
350,
175,
526,
263,
790,
395,
1186,
593,
1780,
890,
445,
1336,
668,
334,
167,
502,
251,
754,
377,
1132,
566,
283,
850,
425,
1276,
638,
319,
958,
479,
1438,
719,
2158,
1079,
3238,
1619,
4858,
2429,
7288,
3644,
1822,
911,
2734,
1367,
4102,
2051,
6154,
3077,
9232,
4616,
2308,
1154,
577,
1732,
866,
433,
1300,
650,
325,
976,
488,
244,
122,
61,
184,
92,
46,
23,
70,
35,
106,
53,
160,
80,
40,
20,
10,
5,
16,
8,
4,
2,
1,
],
107,
)
if __name__ == "__main__":
num = 4
path, length = n31(num)
print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
| from __future__ import annotations
def n31(a: int) -> tuple[list[int], int]:
"""
Returns the Collatz sequence and its length of any positive integer.
>>> n31(4)
([4, 2, 1], 3)
"""
if not isinstance(a, int):
raise TypeError(f"Must be int, not {type(a).__name__}")
if a < 1:
raise ValueError(f"Given integer must be greater than 1, not {a}")
path = [a]
while a != 1:
if a % 2 == 0:
a = a // 2
else:
a = 3 * a + 1
path += [a]
return path, len(path)
def test_n31():
"""
>>> test_n31()
"""
assert n31(4) == ([4, 2, 1], 3)
assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15)
assert n31(31) == (
[
31,
94,
47,
142,
71,
214,
107,
322,
161,
484,
242,
121,
364,
182,
91,
274,
137,
412,
206,
103,
310,
155,
466,
233,
700,
350,
175,
526,
263,
790,
395,
1186,
593,
1780,
890,
445,
1336,
668,
334,
167,
502,
251,
754,
377,
1132,
566,
283,
850,
425,
1276,
638,
319,
958,
479,
1438,
719,
2158,
1079,
3238,
1619,
4858,
2429,
7288,
3644,
1822,
911,
2734,
1367,
4102,
2051,
6154,
3077,
9232,
4616,
2308,
1154,
577,
1732,
866,
433,
1300,
650,
325,
976,
488,
244,
122,
61,
184,
92,
46,
23,
70,
35,
106,
53,
160,
80,
40,
20,
10,
5,
16,
8,
4,
2,
1,
],
107,
)
if __name__ == "__main__":
num = 4
path, length = n31(num)
print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi
| #!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Absolute Value."""
def abs_val(num):
"""
Find the absolute value of a number.
>>> abs_val(-5.1)
5.1
>>> abs_val(-5) == abs_val(5)
True
>>> abs_val(0)
0
"""
return -num if num < 0 else num
def test_abs_val():
"""
>>> test_abs_val()
"""
assert 0 == abs_val(0)
assert 34 == abs_val(34)
assert 100000000000 == abs_val(-100000000000)
if __name__ == "__main__":
print(abs_val(-34)) # --> 34
| """Absolute Value."""
def abs_val(num):
"""
Find the absolute value of a number.
>>> abs_val(-5.1)
5.1
>>> abs_val(-5) == abs_val(5)
True
>>> abs_val(0)
0
"""
return -num if num < 0 else num
def test_abs_val():
"""
>>> test_abs_val()
"""
assert 0 == abs_val(0)
assert 34 == abs_val(34)
assert 100000000000 == abs_val(-100000000000)
if __name__ == "__main__":
print(abs_val(-34)) # --> 34
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
- A linked list is similar to an array, it holds values. However, links in a linked
list do not have indexes.
- This is an example of a double ended, doubly linked list.
- Each link references the next link and the previous one.
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous
pointer, together with next pointer and data which are there in singly linked list.
- Advantages over SLL - It can be traversed in both forward and backward direction.
Delete operation is more efficient
"""
class Node:
def __init__(self, data: int, previous=None, next_node=None):
self.data = data
self.previous = previous
self.next = next_node
def __str__(self) -> str:
return f"{self.data}"
def get_data(self) -> int:
return self.data
def get_next(self):
return self.next
def get_previous(self):
return self.previous
class LinkedListIterator:
def __init__(self, head):
self.current = head
def __iter__(self):
return self
def __next__(self):
if not self.current:
raise StopIteration
else:
value = self.current.get_data()
self.current = self.current.get_next()
return value
class LinkedList:
def __init__(self):
self.head = None # First node in list
self.tail = None # Last node in list
def __str__(self):
current = self.head
nodes = []
while current is not None:
nodes.append(current.get_data())
current = current.get_next()
return " ".join(str(node) for node in nodes)
def __contains__(self, value: int):
current = self.head
while current:
if current.get_data() == value:
return True
current = current.get_next()
return False
def __iter__(self):
return LinkedListIterator(self.head)
def get_head_data(self):
if self.head:
return self.head.get_data()
return None
def get_tail_data(self):
if self.tail:
return self.tail.get_data()
return None
def set_head(self, node: Node) -> None:
if self.head is None:
self.head = node
self.tail = node
else:
self.insert_before_node(self.head, node)
def set_tail(self, node: Node) -> None:
if self.head is None:
self.set_head(node)
else:
self.insert_after_node(self.tail, node)
def insert(self, value: int) -> None:
node = Node(value)
if self.head is None:
self.set_head(node)
else:
self.set_tail(node)
def insert_before_node(self, node: Node, node_to_insert: Node) -> None:
node_to_insert.next = node
node_to_insert.previous = node.previous
if node.get_previous() is None:
self.head = node_to_insert
else:
node.previous.next = node_to_insert
node.previous = node_to_insert
def insert_after_node(self, node: Node, node_to_insert: Node) -> None:
node_to_insert.previous = node
node_to_insert.next = node.next
if node.get_next() is None:
self.tail = node_to_insert
else:
node.next.previous = node_to_insert
node.next = node_to_insert
def insert_at_position(self, position: int, value: int) -> None:
current_position = 1
new_node = Node(value)
node = self.head
while node:
if current_position == position:
self.insert_before_node(node, new_node)
return None
current_position += 1
node = node.next
self.insert_after_node(self.tail, new_node)
def get_node(self, item: int) -> Node:
node = self.head
while node:
if node.get_data() == item:
return node
node = node.get_next()
raise Exception("Node not found")
def delete_value(self, value):
node = self.get_node(value)
if node is not None:
if node == self.head:
self.head = self.head.get_next()
if node == self.tail:
self.tail = self.tail.get_previous()
self.remove_node_pointers(node)
@staticmethod
def remove_node_pointers(node: Node) -> None:
if node.get_next():
node.next.previous = node.previous
if node.get_previous():
node.previous.next = node.next
node.next = None
node.previous = None
def is_empty(self):
return self.head is None
def create_linked_list() -> None:
"""
>>> new_linked_list = LinkedList()
>>> new_linked_list.get_head_data() is None
True
>>> new_linked_list.get_tail_data() is None
True
>>> new_linked_list.is_empty()
True
>>> new_linked_list.insert(10)
>>> new_linked_list.get_head_data()
10
>>> new_linked_list.get_tail_data()
10
>>> new_linked_list.insert_at_position(position=3, value=20)
>>> new_linked_list.get_head_data()
10
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.set_head(Node(1000))
>>> new_linked_list.get_head_data()
1000
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.set_tail(Node(2000))
>>> new_linked_list.get_head_data()
1000
>>> new_linked_list.get_tail_data()
2000
>>> for value in new_linked_list:
... print(value)
1000
10
20
2000
>>> new_linked_list.is_empty()
False
>>> for value in new_linked_list:
... print(value)
1000
10
20
2000
>>> 10 in new_linked_list
True
>>> new_linked_list.delete_value(value=10)
>>> 10 in new_linked_list
False
>>> new_linked_list.delete_value(value=2000)
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.delete_value(value=1000)
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.get_head_data()
20
>>> for value in new_linked_list:
... print(value)
20
>>> new_linked_list.delete_value(value=20)
>>> for value in new_linked_list:
... print(value)
>>> for value in range(1,10):
... new_linked_list.insert(value=value)
>>> for value in new_linked_list:
... print(value)
1
2
3
4
5
6
7
8
9
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
- A linked list is similar to an array, it holds values. However, links in a linked
list do not have indexes.
- This is an example of a double ended, doubly linked list.
- Each link references the next link and the previous one.
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous
pointer, together with next pointer and data which are there in singly linked list.
- Advantages over SLL - It can be traversed in both forward and backward direction.
Delete operation is more efficient
"""
class Node:
def __init__(self, data: int, previous=None, next_node=None):
self.data = data
self.previous = previous
self.next = next_node
def __str__(self) -> str:
return f"{self.data}"
def get_data(self) -> int:
return self.data
def get_next(self):
return self.next
def get_previous(self):
return self.previous
class LinkedListIterator:
def __init__(self, head):
self.current = head
def __iter__(self):
return self
def __next__(self):
if not self.current:
raise StopIteration
else:
value = self.current.get_data()
self.current = self.current.get_next()
return value
class LinkedList:
def __init__(self):
self.head = None # First node in list
self.tail = None # Last node in list
def __str__(self):
current = self.head
nodes = []
while current is not None:
nodes.append(current.get_data())
current = current.get_next()
return " ".join(str(node) for node in nodes)
def __contains__(self, value: int):
current = self.head
while current:
if current.get_data() == value:
return True
current = current.get_next()
return False
def __iter__(self):
return LinkedListIterator(self.head)
def get_head_data(self):
if self.head:
return self.head.get_data()
return None
def get_tail_data(self):
if self.tail:
return self.tail.get_data()
return None
def set_head(self, node: Node) -> None:
if self.head is None:
self.head = node
self.tail = node
else:
self.insert_before_node(self.head, node)
def set_tail(self, node: Node) -> None:
if self.head is None:
self.set_head(node)
else:
self.insert_after_node(self.tail, node)
def insert(self, value: int) -> None:
node = Node(value)
if self.head is None:
self.set_head(node)
else:
self.set_tail(node)
def insert_before_node(self, node: Node, node_to_insert: Node) -> None:
node_to_insert.next = node
node_to_insert.previous = node.previous
if node.get_previous() is None:
self.head = node_to_insert
else:
node.previous.next = node_to_insert
node.previous = node_to_insert
def insert_after_node(self, node: Node, node_to_insert: Node) -> None:
node_to_insert.previous = node
node_to_insert.next = node.next
if node.get_next() is None:
self.tail = node_to_insert
else:
node.next.previous = node_to_insert
node.next = node_to_insert
def insert_at_position(self, position: int, value: int) -> None:
current_position = 1
new_node = Node(value)
node = self.head
while node:
if current_position == position:
self.insert_before_node(node, new_node)
return None
current_position += 1
node = node.next
self.insert_after_node(self.tail, new_node)
def get_node(self, item: int) -> Node:
node = self.head
while node:
if node.get_data() == item:
return node
node = node.get_next()
raise Exception("Node not found")
def delete_value(self, value):
node = self.get_node(value)
if node is not None:
if node == self.head:
self.head = self.head.get_next()
if node == self.tail:
self.tail = self.tail.get_previous()
self.remove_node_pointers(node)
@staticmethod
def remove_node_pointers(node: Node) -> None:
if node.get_next():
node.next.previous = node.previous
if node.get_previous():
node.previous.next = node.next
node.next = None
node.previous = None
def is_empty(self):
return self.head is None
def create_linked_list() -> None:
"""
>>> new_linked_list = LinkedList()
>>> new_linked_list.get_head_data() is None
True
>>> new_linked_list.get_tail_data() is None
True
>>> new_linked_list.is_empty()
True
>>> new_linked_list.insert(10)
>>> new_linked_list.get_head_data()
10
>>> new_linked_list.get_tail_data()
10
>>> new_linked_list.insert_at_position(position=3, value=20)
>>> new_linked_list.get_head_data()
10
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.set_head(Node(1000))
>>> new_linked_list.get_head_data()
1000
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.set_tail(Node(2000))
>>> new_linked_list.get_head_data()
1000
>>> new_linked_list.get_tail_data()
2000
>>> for value in new_linked_list:
... print(value)
1000
10
20
2000
>>> new_linked_list.is_empty()
False
>>> for value in new_linked_list:
... print(value)
1000
10
20
2000
>>> 10 in new_linked_list
True
>>> new_linked_list.delete_value(value=10)
>>> 10 in new_linked_list
False
>>> new_linked_list.delete_value(value=2000)
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.delete_value(value=1000)
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.get_head_data()
20
>>> for value in new_linked_list:
... print(value)
20
>>> new_linked_list.delete_value(value=20)
>>> for value in new_linked_list:
... print(value)
>>> for value in range(1,10):
... new_linked_list.insert(value=value)
>>> for value in new_linked_list:
... print(value)
1
2
3
4
5
6
7
8
9
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/python
"""
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a
finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random
def FYshuffle(list):
for i in range(len(list)):
a = random.randint(0, len(list) - 1)
b = random.randint(0, len(list) - 1)
list[a], list[b] = list[b], list[a]
return list
if __name__ == "__main__":
integers = [0, 1, 2, 3, 4, 5, 6, 7]
strings = ["python", "says", "hello", "!"]
print("Fisher-Yates Shuffle:")
print("List", integers, strings)
print("FY Shuffle", FYshuffle(integers), FYshuffle(strings))
| #!/usr/bin/python
"""
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a
finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random
def FYshuffle(list):
for i in range(len(list)):
a = random.randint(0, len(list) - 1)
b = random.randint(0, len(list) - 1)
list[a], list[b] = list[b], list[a]
return list
if __name__ == "__main__":
integers = [0, 1, 2, 3, 4, 5, 6, 7]
strings = ["python", "says", "hello", "!"]
print("Fisher-Yates Shuffle:")
print("List", integers, strings)
print("FY Shuffle", FYshuffle(integers), FYshuffle(strings))
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
def abs_max(x: list[int]) -> int:
"""
>>> abs_max([0,5,1,11])
11
>>> abs_max([3,-10,-2])
-10
"""
j = x[0]
for i in x:
if abs(i) > abs(j):
j = i
return j
def abs_max_sort(x):
"""
>>> abs_max_sort([0,5,1,11])
11
>>> abs_max_sort([3,-10,-2])
-10
"""
return sorted(x, key=abs)[-1]
def main():
a = [1, 2, -11]
assert abs_max(a) == -11
assert abs_max_sort(a) == -11
if __name__ == "__main__":
main()
| from __future__ import annotations
def abs_max(x: list[int]) -> int:
"""
>>> abs_max([0,5,1,11])
11
>>> abs_max([3,-10,-2])
-10
"""
j = x[0]
for i in x:
if abs(i) > abs(j):
j = i
return j
def abs_max_sort(x):
"""
>>> abs_max_sort([0,5,1,11])
11
>>> abs_max_sort([3,-10,-2])
-10
"""
return sorted(x, key=abs)[-1]
def main():
a = [1, 2, -11]
assert abs_max(a) == -11
assert abs_max_sort(a) == -11
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Fast Polynomial Multiplication using radix-2 fast Fourier Transform.
"""
import mpmath # for roots of unity
import numpy as np
class FFT:
"""
Fast Polynomial Multiplication using radix-2 fast Fourier Transform.
Reference:
https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case
For polynomials of degree m and n the algorithms has complexity
O(n*logn + m*logm)
The main part of the algorithm is split in two parts:
1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a
bottom-up dynamic approach -
2) __multiply: Once we obtain the DFT of A*B, we can similarly
invert it to obtain A*B
The class FFT takes two polynomials A and B with complex coefficients as arguments;
The two polynomials should be represented as a sequence of coefficients starting
from the free term. Thus, for instance x + 2*x^3 could be represented as
[0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the
polynomials have the same length which is a power of 2 at least the length of
their product.
Example:
Create two polynomials as sequences
>>> A = [0, 1, 0, 2] # x+2x^3
>>> B = (2, 3, 4, 0) # 2+3x+4x^2
Create an FFT object with them
>>> x = FFT(A, B)
Print product
>>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5
[(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)]
__str__ test
>>> print(x)
A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2
B = 0*x^2 + 1*x^3 + 2*x^4
A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j)
"""
def __init__(self, polyA=[0], polyB=[0]):
# Input as list
self.polyA = list(polyA)[:]
self.polyB = list(polyB)[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
self.len_A = len(self.polyA)
while self.polyB[-1] == 0:
self.polyB.pop()
self.len_B = len(self.polyB)
# Add 0 to make lengths equal a power of 2
self.C_max_length = int(
2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1))
)
while len(self.polyA) < self.C_max_length:
self.polyA.append(0)
while len(self.polyB) < self.C_max_length:
self.polyB.append(0)
# A complex root used for the fourier transform
self.root = complex(mpmath.root(x=1, n=self.C_max_length, k=1))
# The product
self.product = self.__multiply()
# Discrete fourier transform of A and B
def __DFT(self, which):
if which == "A":
dft = [[x] for x in self.polyA]
else:
dft = [[x] for x in self.polyB]
# Corner case
if len(dft) <= 1:
return dft[0]
#
next_ncol = self.C_max_length // 2
while next_ncol > 0:
new_dft = [[] for i in range(next_ncol)]
root = self.root ** next_ncol
# First half of next step
current_root = 1
for j in range(self.C_max_length // (next_ncol * 2)):
for i in range(next_ncol):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
current_root *= root
# Second half of next step
current_root = 1
for j in range(self.C_max_length // (next_ncol * 2)):
for i in range(next_ncol):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
current_root *= root
# Update
dft = new_dft
next_ncol = next_ncol // 2
return dft[0]
# multiply the DFTs of A and B and find A*B
def __multiply(self):
dftA = self.__DFT("A")
dftB = self.__DFT("B")
inverseC = [[dftA[i] * dftB[i] for i in range(self.C_max_length)]]
del dftA
del dftB
# Corner Case
if len(inverseC[0]) <= 1:
return inverseC[0]
# Inverse DFT
next_ncol = 2
while next_ncol <= self.C_max_length:
new_inverseC = [[] for i in range(next_ncol)]
root = self.root ** (next_ncol // 2)
current_root = 1
# First half of next step
for j in range(self.C_max_length // next_ncol):
for i in range(next_ncol // 2):
# Even positions
new_inverseC[i].append(
(
inverseC[i][j]
+ inverseC[i][j + self.C_max_length // next_ncol]
)
/ 2
)
# Odd positions
new_inverseC[i + next_ncol // 2].append(
(
inverseC[i][j]
- inverseC[i][j + self.C_max_length // next_ncol]
)
/ (2 * current_root)
)
current_root *= root
# Update
inverseC = new_inverseC
next_ncol *= 2
# Unpack
inverseC = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverseC]
# Remove leading 0's
while inverseC[-1] == 0:
inverseC.pop()
return inverseC
# Overwrite __str__ for print(); Shows A, B and A*B
def __str__(self):
A = "A = " + " + ".join(
f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A])
)
B = "B = " + " + ".join(
f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B])
)
C = "A*B = " + " + ".join(
f"{coef}*x^{i}" for coef, i in enumerate(self.product)
)
return "\n".join((A, B, C))
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Fast Polynomial Multiplication using radix-2 fast Fourier Transform.
"""
import mpmath # for roots of unity
import numpy as np
class FFT:
"""
Fast Polynomial Multiplication using radix-2 fast Fourier Transform.
Reference:
https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case
For polynomials of degree m and n the algorithms has complexity
O(n*logn + m*logm)
The main part of the algorithm is split in two parts:
1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a
bottom-up dynamic approach -
2) __multiply: Once we obtain the DFT of A*B, we can similarly
invert it to obtain A*B
The class FFT takes two polynomials A and B with complex coefficients as arguments;
The two polynomials should be represented as a sequence of coefficients starting
from the free term. Thus, for instance x + 2*x^3 could be represented as
[0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the
polynomials have the same length which is a power of 2 at least the length of
their product.
Example:
Create two polynomials as sequences
>>> A = [0, 1, 0, 2] # x+2x^3
>>> B = (2, 3, 4, 0) # 2+3x+4x^2
Create an FFT object with them
>>> x = FFT(A, B)
Print product
>>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5
[(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)]
__str__ test
>>> print(x)
A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2
B = 0*x^2 + 1*x^3 + 2*x^4
A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j)
"""
def __init__(self, polyA=[0], polyB=[0]):
# Input as list
self.polyA = list(polyA)[:]
self.polyB = list(polyB)[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
self.len_A = len(self.polyA)
while self.polyB[-1] == 0:
self.polyB.pop()
self.len_B = len(self.polyB)
# Add 0 to make lengths equal a power of 2
self.C_max_length = int(
2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1))
)
while len(self.polyA) < self.C_max_length:
self.polyA.append(0)
while len(self.polyB) < self.C_max_length:
self.polyB.append(0)
# A complex root used for the fourier transform
self.root = complex(mpmath.root(x=1, n=self.C_max_length, k=1))
# The product
self.product = self.__multiply()
# Discrete fourier transform of A and B
def __DFT(self, which):
if which == "A":
dft = [[x] for x in self.polyA]
else:
dft = [[x] for x in self.polyB]
# Corner case
if len(dft) <= 1:
return dft[0]
#
next_ncol = self.C_max_length // 2
while next_ncol > 0:
new_dft = [[] for i in range(next_ncol)]
root = self.root ** next_ncol
# First half of next step
current_root = 1
for j in range(self.C_max_length // (next_ncol * 2)):
for i in range(next_ncol):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
current_root *= root
# Second half of next step
current_root = 1
for j in range(self.C_max_length // (next_ncol * 2)):
for i in range(next_ncol):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
current_root *= root
# Update
dft = new_dft
next_ncol = next_ncol // 2
return dft[0]
# multiply the DFTs of A and B and find A*B
def __multiply(self):
dftA = self.__DFT("A")
dftB = self.__DFT("B")
inverseC = [[dftA[i] * dftB[i] for i in range(self.C_max_length)]]
del dftA
del dftB
# Corner Case
if len(inverseC[0]) <= 1:
return inverseC[0]
# Inverse DFT
next_ncol = 2
while next_ncol <= self.C_max_length:
new_inverseC = [[] for i in range(next_ncol)]
root = self.root ** (next_ncol // 2)
current_root = 1
# First half of next step
for j in range(self.C_max_length // next_ncol):
for i in range(next_ncol // 2):
# Even positions
new_inverseC[i].append(
(
inverseC[i][j]
+ inverseC[i][j + self.C_max_length // next_ncol]
)
/ 2
)
# Odd positions
new_inverseC[i + next_ncol // 2].append(
(
inverseC[i][j]
- inverseC[i][j + self.C_max_length // next_ncol]
)
/ (2 * current_root)
)
current_root *= root
# Update
inverseC = new_inverseC
next_ncol *= 2
# Unpack
inverseC = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverseC]
# Remove leading 0's
while inverseC[-1] == 0:
inverseC.pop()
return inverseC
# Overwrite __str__ for print(); Shows A, B and A*B
def __str__(self):
A = "A = " + " + ".join(
f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A])
)
B = "B = " + " + ".join(
f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B])
)
C = "A*B = " + " + ".join(
f"{coef}*x^{i}" for coef, i in enumerate(self.product)
)
return "\n".join((A, B, C))
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Shortest job remaining first
Please note arrival time and burst
Please use spaces to separate times entered.
"""
from typing import List
import pandas as pd
def calculate_waitingtime(
arrival_time: List[int], burst_time: List[int], no_of_processes: int
) -> List[int]:
"""
Calculate the waiting time of each processes
Return: List of waiting times.
>>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4)
[0, 3, 5, 0]
>>> calculate_waitingtime([1,2,3],[2,5,1],3)
[0, 2, 0]
>>> calculate_waitingtime([2,3],[5,1],2)
[1, 0]
"""
remaining_time = [0] * no_of_processes
waiting_time = [0] * no_of_processes
# Copy the burst time into remaining_time[]
for i in range(no_of_processes):
remaining_time[i] = burst_time[i]
complete = 0
increment_time = 0
minm = 999999999
short = 0
check = False
# Process until all processes are completed
while complete != no_of_processes:
for j in range(no_of_processes):
if arrival_time[j] <= increment_time:
if remaining_time[j] > 0:
if remaining_time[j] < minm:
minm = remaining_time[j]
short = j
check = True
if not check:
increment_time += 1
continue
remaining_time[short] -= 1
minm = remaining_time[short]
if minm == 0:
minm = 999999999
if remaining_time[short] == 0:
complete += 1
check = False
# Find finish time of current process
finish_time = increment_time + 1
# Calculate waiting time
finar = finish_time - arrival_time[short]
waiting_time[short] = finar - burst_time[short]
if waiting_time[short] < 0:
waiting_time[short] = 0
# Increment time
increment_time += 1
return waiting_time
def calculate_turnaroundtime(
burst_time: List[int], no_of_processes: int, waiting_time: List[int]
) -> List[int]:
"""
Calculate the turn around time of each Processes
Return: list of turn around times.
>>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0])
[3, 6, 10, 1]
>>> calculate_turnaroundtime([3,3], 2, [0,3])
[3, 6]
>>> calculate_turnaroundtime([8,10,1], 3, [1,0,3])
[9, 10, 4]
"""
turn_around_time = [0] * no_of_processes
for i in range(no_of_processes):
turn_around_time[i] = burst_time[i] + waiting_time[i]
return turn_around_time
def calculate_average_times(
waiting_time: List[int], turn_around_time: List[int], no_of_processes: int
) -> None:
"""
This function calculates the average of the waiting & turnaround times
Prints: Average Waiting time & Average Turn Around Time
>>> calculate_average_times([0,3,5,0],[3,6,10,1],4)
Average waiting time = 2.00000
Average turn around time = 5.0
>>> calculate_average_times([2,3],[3,6],2)
Average waiting time = 2.50000
Average turn around time = 4.5
>>> calculate_average_times([10,4,3],[2,7,6],3)
Average waiting time = 5.66667
Average turn around time = 5.0
"""
total_waiting_time = 0
total_turn_around_time = 0
for i in range(no_of_processes):
total_waiting_time = total_waiting_time + waiting_time[i]
total_turn_around_time = total_turn_around_time + turn_around_time[i]
print("Average waiting time = %.5f" % (total_waiting_time / no_of_processes))
print("Average turn around time =", total_turn_around_time / no_of_processes)
if __name__ == "__main__":
print("Enter how many process you want to analyze")
no_of_processes = int(input())
burst_time = [0] * no_of_processes
arrival_time = [0] * no_of_processes
processes = list(range(1, no_of_processes + 1))
for i in range(no_of_processes):
print("Enter the arrival time and brust time for process:--" + str(i + 1))
arrival_time[i], burst_time[i] = map(int, input().split())
waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes)
bt = burst_time
n = no_of_processes
wt = waiting_time
turn_around_time = calculate_turnaroundtime(bt, n, wt)
calculate_average_times(waiting_time, turn_around_time, no_of_processes)
fcfs = pd.DataFrame(
list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)),
columns=[
"Process",
"BurstTime",
"ArrivalTime",
"WaitingTime",
"TurnAroundTime",
],
)
# Printing the dataFrame
pd.set_option("display.max_rows", fcfs.shape[0] + 1)
print(fcfs)
| """
Shortest job remaining first
Please note arrival time and burst
Please use spaces to separate times entered.
"""
from typing import List
import pandas as pd
def calculate_waitingtime(
arrival_time: List[int], burst_time: List[int], no_of_processes: int
) -> List[int]:
"""
Calculate the waiting time of each processes
Return: List of waiting times.
>>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4)
[0, 3, 5, 0]
>>> calculate_waitingtime([1,2,3],[2,5,1],3)
[0, 2, 0]
>>> calculate_waitingtime([2,3],[5,1],2)
[1, 0]
"""
remaining_time = [0] * no_of_processes
waiting_time = [0] * no_of_processes
# Copy the burst time into remaining_time[]
for i in range(no_of_processes):
remaining_time[i] = burst_time[i]
complete = 0
increment_time = 0
minm = 999999999
short = 0
check = False
# Process until all processes are completed
while complete != no_of_processes:
for j in range(no_of_processes):
if arrival_time[j] <= increment_time:
if remaining_time[j] > 0:
if remaining_time[j] < minm:
minm = remaining_time[j]
short = j
check = True
if not check:
increment_time += 1
continue
remaining_time[short] -= 1
minm = remaining_time[short]
if minm == 0:
minm = 999999999
if remaining_time[short] == 0:
complete += 1
check = False
# Find finish time of current process
finish_time = increment_time + 1
# Calculate waiting time
finar = finish_time - arrival_time[short]
waiting_time[short] = finar - burst_time[short]
if waiting_time[short] < 0:
waiting_time[short] = 0
# Increment time
increment_time += 1
return waiting_time
def calculate_turnaroundtime(
burst_time: List[int], no_of_processes: int, waiting_time: List[int]
) -> List[int]:
"""
Calculate the turn around time of each Processes
Return: list of turn around times.
>>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0])
[3, 6, 10, 1]
>>> calculate_turnaroundtime([3,3], 2, [0,3])
[3, 6]
>>> calculate_turnaroundtime([8,10,1], 3, [1,0,3])
[9, 10, 4]
"""
turn_around_time = [0] * no_of_processes
for i in range(no_of_processes):
turn_around_time[i] = burst_time[i] + waiting_time[i]
return turn_around_time
def calculate_average_times(
waiting_time: List[int], turn_around_time: List[int], no_of_processes: int
) -> None:
"""
This function calculates the average of the waiting & turnaround times
Prints: Average Waiting time & Average Turn Around Time
>>> calculate_average_times([0,3,5,0],[3,6,10,1],4)
Average waiting time = 2.00000
Average turn around time = 5.0
>>> calculate_average_times([2,3],[3,6],2)
Average waiting time = 2.50000
Average turn around time = 4.5
>>> calculate_average_times([10,4,3],[2,7,6],3)
Average waiting time = 5.66667
Average turn around time = 5.0
"""
total_waiting_time = 0
total_turn_around_time = 0
for i in range(no_of_processes):
total_waiting_time = total_waiting_time + waiting_time[i]
total_turn_around_time = total_turn_around_time + turn_around_time[i]
print("Average waiting time = %.5f" % (total_waiting_time / no_of_processes))
print("Average turn around time =", total_turn_around_time / no_of_processes)
if __name__ == "__main__":
print("Enter how many process you want to analyze")
no_of_processes = int(input())
burst_time = [0] * no_of_processes
arrival_time = [0] * no_of_processes
processes = list(range(1, no_of_processes + 1))
for i in range(no_of_processes):
print("Enter the arrival time and brust time for process:--" + str(i + 1))
arrival_time[i], burst_time[i] = map(int, input().split())
waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes)
bt = burst_time
n = no_of_processes
wt = waiting_time
turn_around_time = calculate_turnaroundtime(bt, n, wt)
calculate_average_times(waiting_time, turn_around_time, no_of_processes)
fcfs = pd.DataFrame(
list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)),
columns=[
"Process",
"BurstTime",
"ArrivalTime",
"WaitingTime",
"TurnAroundTime",
],
)
# Printing the dataFrame
pd.set_option("display.max_rows", fcfs.shape[0] + 1)
print(fcfs)
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 57: https://projecteuler.net/problem=57
It is possible to show that the square root of two can be expressed as an infinite
continued fraction.
sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))
By expanding this for the first four iterations, we get:
1 + 1 / 2 = 3 / 2 = 1.5
1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4
1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666...
1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,
1393/985, is the first example where the number of digits in the numerator exceeds
the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with
more digits than the denominator?
"""
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result = []
for i in range(1, n + 1):
numerator = prev_numerator + 2 * prev_denominator
denominator = prev_numerator + prev_denominator
if len(str(numerator)) > len(str(denominator)):
result.append(i)
prev_numerator = numerator
prev_denominator = denominator
return len(result)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 57: https://projecteuler.net/problem=57
It is possible to show that the square root of two can be expressed as an infinite
continued fraction.
sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))
By expanding this for the first four iterations, we get:
1 + 1 / 2 = 3 / 2 = 1.5
1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4
1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666...
1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,
1393/985, is the first example where the number of digits in the numerator exceeds
the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with
more digits than the denominator?
"""
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result = []
for i in range(1, n + 1):
numerator = prev_numerator + 2 * prev_denominator
denominator = prev_numerator + prev_denominator
if len(str(numerator)) > len(str(denominator)):
result.append(i)
prev_numerator = numerator
prev_denominator = denominator
return len(result)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 4,278 | fix(mypy): Fix annotations for 13 cipher algorithms | Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| dhruvmanila | "2021-03-20T09:09:15Z" | "2021-03-22T06:59:51Z" | 99a42f2b5821356718fb7d011ac711a6b4a63a83 | 14bcb580d55ee90614ad258ea31ef8fe4e4b5c40 | fix(mypy): Fix annotations for 13 cipher algorithms. Issue: #4052
```console
$ git diff master --name-only
ciphers/a1z26.py
ciphers/affine_cipher.py
ciphers/atbash.py
ciphers/base32.py
ciphers/base85.py
ciphers/beaufort_cipher.py
ciphers/brute_force_caesar_cipher.py
ciphers/cryptomath_module.py
ciphers/decrypt_caesar_with_chi_squared.py
ciphers/diffie.py
ciphers/elgamal_key_generator.py
ciphers/enigma_machine2.py
ciphers/rsa_key_generator.py
```
Running `mypy`:
```console
$ git diff master --name-only | xargs -I% mypy --strict %
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
Success: no issues found in 1 source file
```
### **Describe your change:**
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### **Checklist:**
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| PNG
IHDR ʮ sRGB gAMA a pHYs t tfx IDATx^דfו _3c46=cfSU% B{pwZkZkIA2H A2sosGXcnUߕgu9b d+dɋ\.p\./O.p\.p\_.Ȃ\.p\.
.Ȃ\.p\.
.Ȃ\.p\.
.Ȃ\.p\.
j@/p_2q!L\./'BYGmںeim¦emX~ӹeٝlز
[\ڲ?
+rm[ОՌZK<ybV?guftߪGjd*8|0JvPl;V wo[.ӱiYྲt,gqYcъ6e7GyfaR6,唦uKi\5~qܫ_;u,Fy~ŷݪ]qh=pcuzySΟܰi~/9gv,,]2[}ߓEujY5vzٮW-KvrѮT,صyZfr*>[^Zvj([7JRɬU:koXD%[%|3QsoUj[7JJ;ǹ8JZ(ٯeR¾}.a[?=
oƿ~ӶuᲶimW(.eh]U֯vw|bޮڮw^hI7(Wq#_۩Lw쏏 x9oTߧo;_D=~FP$iM+.+{5F,empv~ǿؗںmJWJGbU?ܚ'ip|&r*|uʒ+8=G~_}G^߾euYF=ضSHO ڮ]^f 3~ۼeZNSl>K8<BYqϬ=lB6[Na.a#o=l6Ǹm
nm
կYG
)W6,Yj#
\oYj3xL=G9[7v:vv$լ9W8U.Rh+IUmJZv%OؽIЮVd<\*_:t^#yf1[<kW~{$uEɴҙS\r]yW5tuwdS~ٿ wW]G3v|L9|zT#$]k {ķΓ,l~2E]l\D.+Ѳj]ۖ _ٗ_~iVұf%]V30mG+w<j6zb5CV=xpdC d.p gZ?>lHf-ruYv4:ƾ+~gwL#Ct6r){#cBlﹽ: K|>6<'[<hXqOK_D~!isp;-U[k6}=r
{J]B˖Rђ]A
Ec\kwKzxX5`͜fdhƮLi1Xv$s@
=u{QϿWX`xΐKl9-v$Dw߆DyOs _
zLZ{QA~^u5֯nGٖ'!I蓛svb}<m7$Ӿ_z@1߆ׯ8d~ifMQ'׃
m&g~篬axr[~pZ}'6j{MZzbuvUooӍoϟK,;oeop?r1Fc[߮;U
wcJ^9:cnӂo}yɒq)
ɭZľeKi~ {yя}2of}CM1}ŏIiys.*[uܒws2{ó9:9t\r21
~>uoS'#e[`ۮSbWkPgwnـt։%eWb_)CS7;vF8G=TMɾ2]ge[]K!vblإװVjFxƿ~}%\JI>gHYѡ2'UvBEG/8nT
9W`qfmmmqsԡj&'|wWL8|bcٯ(G8?RWd?3YEpkӊh0(x/&p߶M[Yݶ/~jVѷe;8;V3g5c(9{uY5D"TIyPN8)" "'2\ɑ e?
dm>q1 qUv.Z~x6oZ9WD$<;r
+(]B7 o@zNj@]>:GL,'ï9!"
Psқý|$(0a(_ȽJu+ǃSVP?h+(E*M[l Czg:,r$p2cD|0S~vlx]玃w9*϶:zH7A#o¹|_TٮR?8 s_Nئeޡ_Ժ@ H r4$81!AI lGIyLpHDhf5r/i[e?@r-b yxܽK m{^Xeak[zojgl_Xym}ϭmjD`E#V
d?_NB^GvEJ"G2NS8]"p0XY=WbpKq$?8 Gܻv^idn58]۲o1^HoT<(ˁԷwqT8ACu_B "D<QSL3SjӽIzתGP@)odfՆAp~紬nڝap|ƶ?hꫜ8o~"b@Ya^r@.?bZ" tee ~u=zNԈwt5^$h yw8NG}v;/IyPj#*þew!7yc-O9'`/-!1n3/`68hUj XxjOڧ7odJ%=;V@ sfC/H$k
Yv-aۥ;ێjClXI2H|DȂpjpFHoI鄪'[m{8wuJ
}8HKSOk]pzsL_#0Z٫t&(Ul}X.n)6C?Fɴ]E>i.o YYsJɲJUp! tΫl; :.sy8_w.!QsJ!&<
,djpI;'TW7˦úە3ٺ
^G%x<ԃT.[в({-@{jfljy~?oO-[Ekx:[Ȟ5Zc}|kXck{۪|tl#*_|5bunl~ut.ۯ"O\GA28}UeW۴n[~HC|v.T0@0nf>}N ugIS|k])!țq|F:zpc"A)m>3qbkŤP@ DVS#Jn-9.!+fc{P>hKmbΫ\+fNzD Ɂ0سe`_$-tD=/)W h]d6f ǔ7-a#|7.Z'N(m*'
A$& /TG+7jܨfǸVR$_10~nPgDODN"p%ݡſ?}|w_V֭~xǪA6U<l`8" pDDc !$IKdž:w-B&FWFVY1݂6l q(d) 0rDA G]p2@ BB
)Tvd(ȿx{H
,P2 DP-Rx ΟTA`H-^VP-{}V^aphnFd*N_[piz8oL>F 8Y!s#\_PpvJ<Sb[Ur#g!\}@LH6N R@*Ck!z "[ݱu^:@yԩu92JtRΆ!QIJ]NtQA-~%n2`[
EC[zU4?-Xmش"t@ F!K/u
ɸֶ
8eɽZ۽G`imsȹrtE>wv&g90ܪG6]I D v^Dp^۱hw) N -zMϺoE^^&"&ܡo+0쭊IK}ʨIzϮTٍ3
eb߆ ɷ2
E.y.XE^8!Ő.<rCACؗBu|YDG!B= |$4sA7_qF頎\( w"qPcs9X"\u<=FYb*EZ+?a_}GmYȢgTM'Y]pe
)s@Ego@6rEuo?19eZ%()[9KU!ܸgTn؍mtݪ5~fZ: [(B$ʠW^,)8N U_ci!{ArF,S_%85pY,! e
V:kUC~%WyfF+%v
qUrɺˁp 4{9D?3;Oc$Dk?qߵ211" i!"C9+ 6"5P-'"D<$`;L=V{d='C+=C h^Cw~:ߵ6ʆk_!{O{n{בu+ /B_!ʜFv ؓ ,8Qp[?@P;?l_-dJ
P{vmH>G.bٚ
=8oB~C\'!7k[v f픗
T=MȆ;:G }ݏȈB ><;7e3'ɕz=1lfɂ5,sm.f-/?[f]eOۭ>{PfOV~%3v`LY3NI;vM@vmS!&
_ޮr ڎuNy>^'+q_goCϗoΈ@z#9v?7*DOS):qge B2]T ADR>gD]7K=}E;j&8ȓqV&/`/U#[co_Yu?ضmāڳU{vrhk'unj[`AAZEx'Xv7J;KVmmWJ!7aD.@
OIIIq"vɀ$7QNjArGh3P:N獳{][<N绁c
t>/B ҝN(KvtJL!`U,p p7p,4,ྫ&D[`8g< v"BD" ݇qu "& |
u ` ?8pD?8%lppk,h_'H3_=zV'&B
<@yBbwSr 'ADr=`6;߃p:0FP˵zOj;KN h6BBD=˾Z;ozbM *AYмM/o/_̒
n0l"sV:[Yà=Omlت:ss{g̡3?h߶]G8'Z?
SW,iβRDoVoyuNC5ʽfܣMBNpmq@7J9zk'}J 9v'ٽ8/&.EI5r/sZu=1Yo#$gWKU#_RKG?
:-C6]ϩ);Pq䊺0,pb́\*XGt?D+Fpy;<&Tqp_"{93(V(HQYY ,-7{}sQTc`A+h 8OE(p/{@v?_߇M#0X^X?kӟlVl¡-ҡ]}b%lrUw/! DrujAb{o6a_?Bk}\O@P?iM{Pku蚖%GGy\ry6T> X߅euSﷆ@([~$N<=Q$Upr '50x~_zjW8ROg{xݢx&ŎwUomj[,^Jg|G8͔
7A芠e +l群$sȩr6'JA쟇^D5!]xݫ<Ca H-zK~cRPb"O)Q]^pqf
֩Kw7"V7
IGq<9=]+ڷ'Vpp?ݴE[Z?ZCyf]{ >kUu6?*6 ,w [ۅгC|M~@}{AHiQvoEf-@=^?~79:xύ3ھ0{[gG,+b t{|:ȂߨD'9uEA
SoAnVcw+w1 '18{nڮF&e ^ J$QG fOzuCYok]F&Ԟ}c鮽b[mt_A]+Ue%
ïkn n@Lе5~W8~
[¶#IeR
^%N# *um[ 0y彇w/>!s8Q5J|ALj
1Je{0u>M'&rk0$C tJDz dANW"@ 7<@(5T-[]۵~K'p$6pvP6VJQݻl6Ċp:9XlVE jIZNơxCp(ؿs$aw8roS>aݬ̺2wgg0`9!]@pܴ=
R ¨
ANRB3:GܗX+22r O+V)#crՏѾ H'XVmm~`]okDcxYq-/QVvEIq]??vp$XIS__CbPDpGc
`^Z3EeA
Nzt-/zh½N&7b+@qxj2b}-
ۘL%XAH wU+c.P⠦D=eoslNABuPq:Vܳ>XkU`_mhzCnp֊TXIÈg{/VL0@5C@P
}Mpd]
UKQyp旑
?Niu,el^Ze5
Y;D`!&x=qK[r9XV?cI灂F8iLA^bI}K[YC-yCffϬ#R1Lptk@zmge,KOHցjԚ(Vh@g7qg{σ@ĤM0A(L:_UpJ,~K}ɂDu=F"g̻K^y߹ش"8C
nY``ŚUCSV?m;8UYA͠gso[YnIkw&.Q@Y-t*M$r@Ǚ8xθ[MP=jȳշy uۜw30b<ˋoR6a3DQ9o@ى"'}2 y ɳdߡ刄d_Agy%t[oPJXw{|;+8Wpx/gwٓmeاzKYu^?T/,(
2/Qg7d_r2uɽH
p>dc:.qgI{Wѽz-~l)PWT@v2^o"[M[P{vȂc#CzZ^/B`:flf~?_}tksBqtr
lnݿnnIU}A?Av=_]ND "YJܪI˪[LΛs{Ku|w1&?SkYP 檐QYJW˱ĝ3himPր:R7'!5UY֩+kѱKhp,;IDAhTI߲5f^_Y䕜._nCkGvQ]Y' uScg:
E\ "ے\@n3Ds }d&
1|WH'1yc9\2B|Ui,)ޝ)K>zճGx\i&Μ2@y:^I"b=}gG?|eT
Zؾmڎ}/7M.oZWPڷM`Ǘ->@Bvf @#u1 ;%NmDI:)`?&n~K};4ZW@qp^$/[:,@"-8Ae?r4Hc=AIQS7=)B?L`l~9
7pA?"$LڔnUF) K~B餁m(8<PGG8v1V㴸`ˇ1VJsQ)7CBSƃZd%4n8uLT^At@(`ZΒA1"jqpen;&!35C"%>k^=-\C vpbg ckǞ,A̶]"D(<28juRK G5",rD kY-]AU#V;ku{U+ZCz`sxf/Y_5+¾U+SwI_9ZI뜕!9pb {2:<8xԱB{r}ɩ:e(
(%A`vAy(֑){1^]iw+t9tȇ.AK.2#}g<$0:B48Y`AjeI{w]TC=Q+62%uBmqezv͖JpJÿҝ+5ɂ;8dSDYCXi}"g'
( SϜpy8o"_w=sG=7}'\'Qwx}ƁZ%b &b86Q
e˔e\"+تBlr?z`kزU+سkܱ[Tf'Ma'*i&V"ٟmG@$arH^P4x(LIn%3i9~f_O[Vˬ7:`tt¦!!Av=yݖζvɷ; r=ux.=S&-qiߔ_[N7)&WàW|`o/}Zg++n[Nzi72ݖhk%3.^9qduVvy܇6<߷Ⱦh9Ƨupd|
g2*lcqZֶWPwJ1dnUW˂weM, yy,JdJ|lpgXȞu/}gA}YWg-/
ز|lb
Nޅ܆6) ]
br@˩x]RC i9M"35NY
2ٰhY"{ns=Twyδ=d{jǒ%wqA
7c/ftksSu[xu4( :|akvH r1u[ʱ"kJW{qK"wcdՒ:Oe7N\=(#ĻRVO@ם¸dpT=ODXLzYr]B^5;xGj/UYAu15@O=lcHy
7$ĠЕ1C>n2OjeSG[i[ae҄10ɖH2}ZNDz dk|AP3バ)Я&hݳ}ޱ]CD-X;RJ9ǃԌm?23uEYJ?Vd9aнr` ) *;(GV\%˨tgBDA@ h},D=8ޕ,P6ߠ0AXv)6jD
3il
$"DȰ^(P-
ߔ د}Zq2{7H;R`w'䬲||wX1e6?,H#k:d0r$m~mr/'
xFKABvΠG-j)N+%.g;&8l=si99<R;Fh y_0u}k?~K뺆9
㝈Hg}dCM{qD9J[{78yz%re_W"m+X57Z
N-ں/筶oɪ֭xpъ;Vٹd}{ZnV%Ҡ3۶!ْ|IgH6+nYyq+Lus|ЁJ
"\X6DaǸ=_$Yrw My8'V;
u8!XY\ۮi^]o@/ٕj:$'Ou+ۃxPuٕj{dVXRV<c7*bbn,PJyO; 'PKVmyLgThd4eY?|O>StD"tAoq:&>i21P<}c%$fF$ctU+=d<gdJ"3=*̯1d
8Ob`ߪf&OoZؑՎ[u/֮/?zkj#Kmz6l:QX}`y={#ѾA(Y|/٧8Qxγy(M$jT@![n"N?ca8cYѸ~=w?"7V& ,صGEӳcYCE$H2d ~"
rOze}۟~M?*Hֻ^;]a`N^4%W=g=d`sQ;HTau-qA#we=p*&~[Cpd>sJn׃\:G%Y
`'yWϒYsgR$ ή=/sC AA4;
1IQc"</ٵAd~~`ݴM}k;CX͍]?zwujͰ`zm[a<?{`2)ҁ?q ږ쳂S(؈]?@b$h9 @$"mmF=R=su]F^,wRpW#(}U
ּԶ0 !!fHi
=9Oݻ' %]W}yHW1 fZ+(o!־%zY8G@b{ͫر\ľW.mrЏ-ӆVZvn$ލz|x3*4xaLl"-5ʟ_@BLV|qMF5&Zhޛc͡
'
BUqzAzrWP|5]k#$Vݍen`SXC)S'OUq²weBECѲȗp/} Y%S%@]dXJ2Xߙ,i4k5uڑ}ka<0vd=?~mdiךah1,%P精
ͽ+!ȊG9V;n8
b,hPAja$;"{
uQ8_F 4cMTR'Bg cVewt#AJJ'ҹ=%Rc_QA z( b}pue 2 6lNDp"`;/cTzrD68@I7!& shwJmCBY>emv%]g)a
c0OwS"^.8h{mWݟ;R^7p@J ů\_eQz'8j}b,P
M!' @Cۥ"A@'B8u?ίgZѳ0{Ai:S,FfpۚG4OZ܉5
.ƾx_6SUoZ:AêU
l8ZIۢ5k2
D(Uϝ4N-aw1w4ry~=ƷAr1Ar9arkf~{D VK CrZJʿ&ϝY'Cd7TJmSp. i<_?Rk)zMz&
Ξz*C?o$BHD:I,+U=a#6rd7KyiA1M\ !FHC<}{k8p
%z ͳOu;mζSmAN
5dη3q@kpBS}0mt81oo
6prn]0@j,Ne[;+^' !qޅd?!^d_/GNTb㇞]PNhyfM3'2as['/g_O68j%8Jv5mO>5ZQׁ$]""1l~Țg x+("KGkRޓngnYe8^\=|ӼOu
HPz
8ܸl-+5~_&r%(<Wy@oAaH\S`[B]#@d>5ਣRKZljjy RxOrEr$J(߯#nw;aL3r;
>vb]HNx&(',:{P,+h,k_2~}NJ~7rZ.y
𮧽ԱaHڇD=߷QoaEx?/& b-&_'u#G0r`Mz66~s:Vmzyy]×_uBr`*z=qlU}31e" 7,"pCCp0FAh{HN"5[V'qϒ2Qq0CvB8Wk4Wvqʒ]r۴=hrH u;o"~V@@[dG}CLĭ"c莬:=GNUv!:Ԯ
٥Zu h=
u@:5pK܋3 h\k"d}<@.n.tP"-e4N댃 0~*CȏpyED><w~Bl/r({Z^} Z,&tv:5uO3!oIUF%:I$yމ !tq]2z"aMsxXY0A='"De?3YP1D?gC;0kc }P,}j/_~nsK0[>%RQϦMqn
f)8RbQGD0vqD$B
,@:Yoݷ)Gaf5ڣf2dPпf#VYaQd1Pr`#RXAVR{PKe-8K %by_6oA`97XV-0k$X9b:DYP;`3v3Ӆ.
H'!ڞ?g<>jUaEpACZAN[lW 8q /E ;<p*={96JOE)草8?Nd;btDT$hM8
'@
ý+sÉ
T7EHWkڈ,h۳#Gԉu[}ߜm>?ȝ܊Uu\l[¼uZy:#+"xy`:@${1W'{Z qo"S.Pp,+p}";+0g)=GvP-B h{P5jŝc|O:~e4 J>2n I(ɉw`MjɿB'gWax!?pT [1fJZymU6`+Vr`gZբF:&T(,$u3wCqJN$C~.4ITٿz"r6r84 E.R!2f y}[T;Ɍ2${4H~T<*W@)/CY,"D$ɨ/"q_<ڮƺL~1bbub O+&,[xk
4uG4YТmk}}? -XV4e+Vڹfe5s[q#DYͲv~dNY2.Y,+hĠ'*O}ݟweZ<ܳ
"k|?kbЪ'L `'D +;Mx7:GP\mOA;.2/ϐ|6 P"S4H1MA}eKmf_2yn 㑓G vhk3r?A8цJEH} Sv}n";
Tw#'äW}e>XȔGtO-097or6EBzWr5.;3ܠO\ aH_qoiVWвqo&3
,1@ZCL:@d~x%C2,huk6t͟X̞w?jFDwlXE!e3v#dw4va:.\@c2zZubwe
h_h_0ΙGFiKo%-! пS>aq_t^-+Ai(<A9I*p&M "WB ^~d26VŁ])S<gm]6|`n]+
zg½'>DqT&QP :r{[-0I9F~}5o7
>yghMSv(Eؕi==FvS\l+%Wk5lX%22K~uSzP&7ZT ޔz "yF'I="!O{r%U
e\)Q tUQƄ2a(]e<8[3M}W2oBf
I0!jMٵ&'&cڧ|۳'/O7>ܶUY#9#(0t )L
N8G?N_P@-+@)A"
Q]Ȃ@PG*op;(J
BY U*dxf#%0g@XmT.PQ|h= GAe8^j?vOc!-VBx+S
1!)ecF §8eާ2
4Zè2w(pO ωzZ;BpT>rqW 1Qp:258e`;xHЛ576Q.Tp~{F)pp_J!Xw :p. O9w&X5AiU,>U0~dm'ֆWtL؋?g/^دwo-V6,!咎E+e{'VҾ`Y> Xj&rc8Y:f;仉`>Bb+p6$aqz~/ Dj ƥfoO0 EA>C$wx@FYؐ@f<曫uGR", m8]pjnڋ|f
8Mv?ƖvNާ\/:Y>9Kx~\SgP9]0rlKn8쁲0yY
Ğtu ӌ.M7܃6u93ĺMݮM%Bϫ{}k\)<.4h [O!:ؖ">^)upX]؇yq"?8ʹGt;:>Z~7sV se_nzw]k+ɂJP1fv7_;}:G
'w
F-cJ;Wcj)D}z[=MӚdREgd-%@A|(|%!@ї7nZ56,{.8%6wG$) DSD&L7Nf^ELv}ݏZHk|"u%JH%BH$"]eى%"p6Kq$:a
]=bXܵM]7R?eñȏ \} g]Qzn'ʽd*o?'[)d;@.PǃK#٧NS*m>EGƳ_/#M[óawx9W2:>[
<KSsJ|4G^d>D.OM $#@=boCFZ#DŽz/K.Γn5E}l6,+i?N=_g?UhI+zewV=aTM6?K#@w )2Db@]
zOȩXٕIK!w&۶fddJ&ruY#Ϡe!ܿOi !M(Pn,></@Aud@LD?GJK>XrA7F¨k2:JO%3P'_`\Gd^c _"egnk|5ťv$>hCwPn]i(9gtݫRciHF~ʌ]*^U|G)a?ſWRԹdaAUrM(c=ɢtkڮtS_:R;&;
Y
e]b8EF*4s YBW0(h'"w&4GT,N[>}kbeby};>:C;:¹aذE+ [Gҿ@Pzd
2-L˨Y5Ub
4~C$+)U/ J'@6P";Bͬe(p] I.d#NU|MSmWQ , H9/bLPI<sA6b
Ȃh92@!_0rB)(~9
*|]]
RFmĚzK+lru3<8y=u
OQYE1LƲ`pSލ9x~1Il"piFhQ?S<S)N:oBW*c=К>vMe @ν GO_nvlS)çʔs E';*\KNjQS p<7w|9"S!ܿee[ lyף}k1xh
6r*:'G?-./nXU AuZY)
_#/ڋ>AMgY=[>
",kKu<ww{qj8p<طΕܶ14~@D,,q$R~
Tmλ#wJg:12W>u#}c@)q 2o厪DD(*,BvA1bBF6FH)o/c&8d`53V"ApDvŸ;
\H!#z g:K"'c+h-˦~]F8acy
'"PeԧhxH=D<oTp畒:,ޗ|;*Y9L㜏)L^&m3 462MYx@sgElJyg
*(Tzxx8!HqZJC[Kz}`jG2 JF_wwcj:,ڱ\Ntwɞ#t вw-'Ucdt_N5ifׁe"v50ȑށh۳!8Aj55zA)I_MoTm])\A%W6Mvh3@Nuz%@v"D+VНh,]p?v|\*Hwⷷ9)ɂ*m{Yybo}66B,y`=s0Bb 9{E|ݓ!_uK.nKcǾK%;#on Ʊ|;RɢR}>wG:)/ݬ _>Sw8wW ڗyu>/MiWz;z{t;54P6(f{sꙥKDrܞ)Ż3dO""L/O$cD2uw8vGD$FwXz]
8m5{bݳGV5e?Wj_|on[Qs7ZQϔ.X~ۚ[qXМeY~ߑel{5Ee<0} , @a0t58j=t!+(v@OA1BёAIdC
f]Șgw`JϪv -S ^토"
ˣ |,X譊mZ<ceǟY/pdV-ڛ}Ys)et6"/
AuM-Y3v4n{<gM%6$fC&XڞJ8!UY$[TcYwGiJMoJFo&xV:۳XgẦfg/t&:@F7YQρW95A[sY\>*9Э1} 4Z<զ1>KSr
^L,PFL'"_5fA͐f<lVeX#-ݵ={;gS{``
eU=8N<ڴ<E{rtls>uc0@Qe @"d{PyE(PFJ#US PG
^xC<UX>_aX)NLĵ0Pd>ܞb tmWs#vpJH$lZp."b ˰x! hRЊ&oF>ց%KYͼ/YWGT-0-)oDVU* Q|zspC-=ehh=c4DIe^O9F\a>9m"=kiJ]#
õ9GB2 xΧ:
!5]^vawnZY]Ses-!XU+M"DLPKQp "A ""& |