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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Convert International System of Units (SI) and Binary prefixes """ from enum import Enum from typing import Union class SI_Unit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class Binary_Unit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: Union[str, SI_Unit], unknown_prefix: Union[str, SI_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SI_Unit.giga, SI_Unit.mega) 1000 >>> convert_si_prefix(1, SI_Unit.mega, SI_Unit.giga) 0.001 >>> convert_si_prefix(1, SI_Unit.kilo, SI_Unit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix = SI_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SI_Unit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: Union[str, Binary_Unit], unknown_prefix: Union[str, Binary_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, Binary_Unit.giga, Binary_Unit.mega) 1024 >>> convert_binary_prefix(1, Binary_Unit.mega, Binary_Unit.giga) 0.0009765625 >>> convert_binary_prefix(1, Binary_Unit.kilo, Binary_Unit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix = Binary_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = Binary_Unit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
""" Convert International System of Units (SI) and Binary prefixes """ from enum import Enum from typing import Union class SI_Unit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class Binary_Unit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: Union[str, SI_Unit], unknown_prefix: Union[str, SI_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SI_Unit.giga, SI_Unit.mega) 1000 >>> convert_si_prefix(1, SI_Unit.mega, SI_Unit.giga) 0.001 >>> convert_si_prefix(1, SI_Unit.kilo, SI_Unit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix = SI_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SI_Unit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: Union[str, Binary_Unit], unknown_prefix: Union[str, Binary_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, Binary_Unit.giga, Binary_Unit.mega) 1024 >>> convert_binary_prefix(1, Binary_Unit.mega, Binary_Unit.giga) 0.0009765625 >>> convert_binary_prefix(1, Binary_Unit.kilo, Binary_Unit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix = Binary_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = Binary_Unit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 code to demonstrate working of # extend(), extendleft(), rotate(), reverse() # importing "collections" for deque operations import collections # initializing deque de = collections.deque([1, 2, 3]) # using extend() to add numbers to right end # adds 4,5,6 to right end de.extend([4, 5, 6]) # printing modified deque print("The deque after extending deque at end is : ") print(de) # using extendleft() to add numbers to left end # adds 7,8,9 to right end de.extendleft([7, 8, 9]) # printing modified deque print("The deque after extending deque at beginning is : ") print(de) # using rotate() to rotate the deque # rotates by 3 to left de.rotate(-3) # printing modified deque print("The deque after rotating deque is : ") print(de) # using reverse() to reverse the deque de.reverse() # printing modified deque print("The deque after reversing deque is : ") print(de) # get right-end value and eliminate startValue = de.pop() print("The deque after popping value at end is : ") print(de) # get left-end value and eliminate endValue = de.popleft() print("The deque after popping value at start is : ") print(de) # eliminate element searched by value de.remove(5) print("The deque after eliminating element searched by value : ") print(de)
# Python code to demonstrate working of # extend(), extendleft(), rotate(), reverse() # importing "collections" for deque operations import collections # initializing deque de = collections.deque([1, 2, 3]) # using extend() to add numbers to right end # adds 4,5,6 to right end de.extend([4, 5, 6]) # printing modified deque print("The deque after extending deque at end is : ") print(de) # using extendleft() to add numbers to left end # adds 7,8,9 to right end de.extendleft([7, 8, 9]) # printing modified deque print("The deque after extending deque at beginning is : ") print(de) # using rotate() to rotate the deque # rotates by 3 to left de.rotate(-3) # printing modified deque print("The deque after rotating deque is : ") print(de) # using reverse() to reverse the deque de.reverse() # printing modified deque print("The deque after reversing deque is : ") print(de) # get right-end value and eliminate startValue = de.pop() print("The deque after popping value at end is : ") print(de) # get left-end value and eliminate endValue = de.popleft() print("The deque after popping value at start is : ") print(de) # eliminate element searched by value de.remove(5) print("The deque after eliminating element searched by value : ") print(de)
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 """ Build a simple bare-minimum quantum circuit that starts with a single qubit (by default, in state 0) and inverts it. Run the experiment 1000 times and print the total count of the states finally observed. Qiskit Docs: https://qiskit.org/documentation/getting_started.html """ import qiskit as q def single_qubit_measure(qubits: int, classical_bits: int) -> q.result.counts.Counts: """ >>> single_qubit_measure(2, 2) {'11': 1000} >>> single_qubit_measure(4, 4) {'0011': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") # Create a Quantum Circuit acting on the q register circuit = q.QuantumCircuit(qubits, classical_bits) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0) circuit.x(1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Execute the circuit on the qasm simulator job = q.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) if __name__ == "__main__": counts = single_qubit_measure(2, 2) print(f"Total count for various states are: {counts}")
#!/usr/bin/env python3 """ Build a simple bare-minimum quantum circuit that starts with a single qubit (by default, in state 0) and inverts it. Run the experiment 1000 times and print the total count of the states finally observed. Qiskit Docs: https://qiskit.org/documentation/getting_started.html """ import qiskit as q def single_qubit_measure(qubits: int, classical_bits: int) -> q.result.counts.Counts: """ >>> single_qubit_measure(2, 2) {'11': 1000} >>> single_qubit_measure(4, 4) {'0011': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") # Create a Quantum Circuit acting on the q register circuit = q.QuantumCircuit(qubits, classical_bits) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0) circuit.x(1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Execute the circuit on the qasm simulator job = q.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) if __name__ == "__main__": counts = single_qubit_measure(2, 2) print(f"Total count for various states are: {counts}")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = [k for k in range(2, 20 + 1)] base = [10 ** k for k in range(ks[-1] + 1)] memo = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10 ** 15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10 ** j return a_n if __name__ == "__main__": print(f"{solution() = }")
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = [k for k in range(2, 20 + 1)] base = [10 ** k for k in range(ks[-1] + 1)] memo = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10 ** 15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10 ** j return a_n if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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/Tree_traversal class Node: """ A Node has data variable and pointers to its left and right nodes. """ def __init__(self, data): self.left = None self.right = None self.data = data def make_tree() -> Node: root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) return root def preorder(root: Node): """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node): """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node): """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node): """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order_1(root: Node): """ Print whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ if not root: return temp = root que = [temp] while len(que) > 0: print(que[0].data, end=" ") temp = que.pop(0) if temp.left: que.append(temp.left) if temp.right: que.append(temp.right) return que def level_order_2(root: Node, level: int): """ Level-wise traversal: Print all nodes present at the given level of the binary tree """ if not root: return root if level == 1: print(root.data, end=" ") elif level > 1: level_order_2(root.left, level - 1) level_order_2(root.right, level - 1) def print_left_to_right(root: Node, level: int): """ Print elements on particular level from left to right direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_left_to_right(root.left, level - 1) print_left_to_right(root.right, level - 1) def print_right_to_left(root: Node, level: int): """ Print elements on particular level from right to left direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_right_to_left(root.right, level - 1) print_right_to_left(root.left, level - 1) def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: print_right_to_left(root, h) flag = 0 def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversal is {postorder(root)}") print(f"Height of Tree is {height(root)}") print("Complete Level Order Traversal is : ") level_order_1(root) print("\nLevel-wise order Traversal is : ") for h in range(1, height(root) + 1): level_order_2(root, h) print("\nZigZag order Traversal is : ") zigzag(root) print() if __name__ == "__main__": import doctest doctest.testmod() main()
# https://en.wikipedia.org/wiki/Tree_traversal class Node: """ A Node has data variable and pointers to its left and right nodes. """ def __init__(self, data): self.left = None self.right = None self.data = data def make_tree() -> Node: root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) return root def preorder(root: Node): """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node): """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node): """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node): """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order_1(root: Node): """ Print whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ if not root: return temp = root que = [temp] while len(que) > 0: print(que[0].data, end=" ") temp = que.pop(0) if temp.left: que.append(temp.left) if temp.right: que.append(temp.right) return que def level_order_2(root: Node, level: int): """ Level-wise traversal: Print all nodes present at the given level of the binary tree """ if not root: return root if level == 1: print(root.data, end=" ") elif level > 1: level_order_2(root.left, level - 1) level_order_2(root.right, level - 1) def print_left_to_right(root: Node, level: int): """ Print elements on particular level from left to right direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_left_to_right(root.left, level - 1) print_left_to_right(root.right, level - 1) def print_right_to_left(root: Node, level: int): """ Print elements on particular level from right to left direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_right_to_left(root.right, level - 1) print_right_to_left(root.left, level - 1) def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: print_right_to_left(root, h) flag = 0 def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversal is {postorder(root)}") print(f"Height of Tree is {height(root)}") print("Complete Level Order Traversal is : ") level_order_1(root) print("\nLevel-wise order Traversal is : ") for h in range(1, height(root) + 1): level_order_2(root, h) print("\nZigZag order Traversal is : ") zigzag(root) print() if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 Stack using a linked list like structure """ from typing import Any class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return f"{self.data}" class LinkedStack: """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top = None def __iter__(self): node = self.top while node: yield node.data node = node.next def __str__(self): """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self): """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: Any) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> Any: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> Any: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
""" A Stack using a linked list like structure """ from typing import Any class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return f"{self.data}" class LinkedStack: """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top = None def __iter__(self): node = self.top while node: yield node.data node = node.next def __str__(self): """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self): """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: Any) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> Any: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> Any: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 import math from typing import List, Union class SegmentTree: def __init__(self, size: int) -> None: self.size = size # approximate the overall size of segment tree with given value self.segment_tree = [0 for i in range(0, 4 * size)] # create array to store lazy update self.lazy = [0 for i in range(0, 4 * size)] self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update def left(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.left(1) 2 >>> segment_tree.left(2) 4 >>> segment_tree.left(12) 24 """ return idx * 2 def right(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.right(1) 3 >>> segment_tree.right(2) 5 >>> segment_tree.right(12) 25 """ return idx * 2 + 1 def build( self, idx: int, left_element: int, right_element: int, A: List[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = A[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, A) self.build(self.right(idx), mid + 1, right_element, A) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: """ update with O(lg n) (Normal segment tree without lazy update will take O(nlg n) for each update) update(1, 1, size, a, b, v) for update val v to [a,b] """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True # query with O(lg n) def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> Union[int, float]: """ query(1, 1, size, a, b) for query max of [a,b] >>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] >>> segment_tree = SegmentTree(15) >>> segment_tree.build(1, 1, 15, A) >>> segment_tree.query(1, 1, 15, 4, 6) 7 >>> segment_tree.query(1, 1, 15, 7, 11) 14 >>> segment_tree.query(1, 1, 15, 7, 12) 15 """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2) def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)]) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] size = 15 segt = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
from __future__ import annotations import math from typing import List, Union class SegmentTree: def __init__(self, size: int) -> None: self.size = size # approximate the overall size of segment tree with given value self.segment_tree = [0 for i in range(0, 4 * size)] # create array to store lazy update self.lazy = [0 for i in range(0, 4 * size)] self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update def left(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.left(1) 2 >>> segment_tree.left(2) 4 >>> segment_tree.left(12) 24 """ return idx * 2 def right(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.right(1) 3 >>> segment_tree.right(2) 5 >>> segment_tree.right(12) 25 """ return idx * 2 + 1 def build( self, idx: int, left_element: int, right_element: int, A: List[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = A[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, A) self.build(self.right(idx), mid + 1, right_element, A) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: """ update with O(lg n) (Normal segment tree without lazy update will take O(nlg n) for each update) update(1, 1, size, a, b, v) for update val v to [a,b] """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True # query with O(lg n) def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> Union[int, float]: """ query(1, 1, size, a, b) for query max of [a,b] >>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] >>> segment_tree = SegmentTree(15) >>> segment_tree.build(1, 1, 15, A) >>> segment_tree.query(1, 1, 15, 4, 6) 7 >>> segment_tree.query(1, 1, 15, 7, 11) 14 >>> segment_tree.query(1, 1, 15, 7, 12) 15 """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2) def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)]) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] size = 15 segt = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# An OOP approach to representing and manipulating matrices class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> print(matrix.rows) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> print(matrix.columns()) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> print(matrix.inverse()) None Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self): return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self): return len(self.rows) @property def num_columns(self): return len(self.rows[0]) @property def order(self): return (self.num_rows, self.num_columns) @property def is_square(self): return self.order[0] == self.order[1] def identity(self): values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self): if not self.is_square: return None if self.order == (0, 0): return 1 if self.order == (1, 1): return self.rows[0][0] if self.order == (2, 2): return (self.rows[0][0] * self.rows[1][1]) - ( self.rows[0][1] * self.rows[1][0] ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self): return bool(self.determinant()) def get_minor(self, row, column): values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row, column): if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self): return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self): return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self): values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self): determinant = self.determinant() return None if not determinant else self.adjugate() * (1 / determinant) def __repr__(self): return str(self.rows) def __str__(self): if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(self.rows[0]) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row, position=None): type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column, position=None): type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other): if not isinstance(other, Matrix): raise TypeError("A Matrix can only be compared with another Matrix") return self.rows == other.rows def __ne__(self, other): return not self == other def __neg__(self): return self * -1 def __add__(self, other): if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other): if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other): if isinstance(other, (int, float)): return Matrix([[element * other for element in row] for row in self.rows]) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other): if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable: return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for i in range(other - 1): result *= self return result @classmethod def dot_product(cls, row, column): return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
# An OOP approach to representing and manipulating matrices class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> print(matrix.rows) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> print(matrix.columns()) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> print(matrix.inverse()) None Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self): return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self): return len(self.rows) @property def num_columns(self): return len(self.rows[0]) @property def order(self): return (self.num_rows, self.num_columns) @property def is_square(self): return self.order[0] == self.order[1] def identity(self): values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self): if not self.is_square: return None if self.order == (0, 0): return 1 if self.order == (1, 1): return self.rows[0][0] if self.order == (2, 2): return (self.rows[0][0] * self.rows[1][1]) - ( self.rows[0][1] * self.rows[1][0] ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self): return bool(self.determinant()) def get_minor(self, row, column): values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row, column): if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self): return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self): return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self): values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self): determinant = self.determinant() return None if not determinant else self.adjugate() * (1 / determinant) def __repr__(self): return str(self.rows) def __str__(self): if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(self.rows[0]) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row, position=None): type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column, position=None): type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other): if not isinstance(other, Matrix): raise TypeError("A Matrix can only be compared with another Matrix") return self.rows == other.rows def __ne__(self, other): return not self == other def __neg__(self): return self * -1 def __add__(self, other): if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other): if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other): if isinstance(other, (int, float)): return Matrix([[element * other for element in row] for row in self.rows]) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other): if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable: return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for i in range(other - 1): result *= self return result @classmethod def dot_product(cls, row, column): return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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: MatteoRaso """ from math import pi, sqrt from random import uniform from statistics import mean from typing import Callable def pi_estimator(iterations: int): """ An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at (0,0). 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. a. Record the number of dots within the circle. 4. After all the dots are placed, divide the dots in the circle by the total. 5. Multiply this value by 4 to get your estimate of pi. 6. Print the estimated and numpy value of pi """ # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x ** 2) + (y ** 2)) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle proportion = mean( int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0))) for _ in range(iterations) ) # The ratio of the area for circle to square is pi/4. pi_estimate = proportion * 4 print(f"The estimated value of pi is {pi_estimate}") print(f"The numpy value of pi is {pi}") print(f"The total error is {abs(pi - pi_estimate)}") def area_under_curve_estimator( iterations: int, function_to_integrate: Callable[[float], float], min_value: float = 0.0, max_value: float = 1.0, ) -> float: """ An implementation of the Monte Carlo method to find area under a single variable non-negative real-valued continuous function, say f(x), where x lies within a continuous bounded interval, say [min_value, max_value], where min_value and max_value are finite numbers 1. Let x be a uniformly distributed random variable between min_value to max_value 2. Expected value of f(x) = (integrate f(x) from min_value to max_value)/(max_value - min_value) 3. Finding expected value of f(x): a. Repeatedly draw x from uniform distribution b. Evaluate f(x) at each of the drawn x values c. Expected value = average of the function evaluations 4. Estimated value of integral = Expected value * (max_value - min_value) 5. Returns estimated value """ return mean( function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations) ) * (max_value - min_value) def area_under_line_estimator_check( iterations: int, min_value: float = 0.0, max_value: float = 1.0 ) -> None: """ Checks estimation error for area_under_curve_estimator function for f(x) = x where x lies within min_value to max_value 1. Calls "area_under_curve_estimator" function 2. Compares with the expected value 3. Prints estimated, expected and error value """ def identity_function(x: float) -> float: """ Represents identity function >>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]] [-2.0, -1.0, 0.0, 1.0, 2.0] """ return x estimated_value = area_under_curve_estimator( iterations, identity_function, min_value, max_value ) expected_value = (max_value * max_value - min_value * min_value) / 2 print("******************") print(f"Estimating area under y=x where x varies from {min_value} to {max_value}") print(f"Estimated value is {estimated_value}") print(f"Expected value is {expected_value}") print(f"Total error is {abs(estimated_value - expected_value)}") print("******************") def pi_estimator_using_area_under_curve(iterations: int) -> None: """ Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi """ def function_to_integrate(x: float) -> float: """ Represents semi-circle with radius 2 >>> [function_to_integrate(x) for x in [-2.0, 0.0, 2.0]] [0.0, 2.0, 0.0] """ return sqrt(4.0 - x * x) estimated_value = area_under_curve_estimator( iterations, function_to_integrate, 0.0, 2.0 ) print("******************") print("Estimating pi using area_under_curve_estimator") print(f"Estimated value is {estimated_value}") print(f"Expected value is {pi}") print(f"Total error is {abs(estimated_value - pi)}") print("******************") if __name__ == "__main__": import doctest doctest.testmod()
""" @author: MatteoRaso """ from math import pi, sqrt from random import uniform from statistics import mean from typing import Callable def pi_estimator(iterations: int): """ An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at (0,0). 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. a. Record the number of dots within the circle. 4. After all the dots are placed, divide the dots in the circle by the total. 5. Multiply this value by 4 to get your estimate of pi. 6. Print the estimated and numpy value of pi """ # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x ** 2) + (y ** 2)) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle proportion = mean( int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0))) for _ in range(iterations) ) # The ratio of the area for circle to square is pi/4. pi_estimate = proportion * 4 print(f"The estimated value of pi is {pi_estimate}") print(f"The numpy value of pi is {pi}") print(f"The total error is {abs(pi - pi_estimate)}") def area_under_curve_estimator( iterations: int, function_to_integrate: Callable[[float], float], min_value: float = 0.0, max_value: float = 1.0, ) -> float: """ An implementation of the Monte Carlo method to find area under a single variable non-negative real-valued continuous function, say f(x), where x lies within a continuous bounded interval, say [min_value, max_value], where min_value and max_value are finite numbers 1. Let x be a uniformly distributed random variable between min_value to max_value 2. Expected value of f(x) = (integrate f(x) from min_value to max_value)/(max_value - min_value) 3. Finding expected value of f(x): a. Repeatedly draw x from uniform distribution b. Evaluate f(x) at each of the drawn x values c. Expected value = average of the function evaluations 4. Estimated value of integral = Expected value * (max_value - min_value) 5. Returns estimated value """ return mean( function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations) ) * (max_value - min_value) def area_under_line_estimator_check( iterations: int, min_value: float = 0.0, max_value: float = 1.0 ) -> None: """ Checks estimation error for area_under_curve_estimator function for f(x) = x where x lies within min_value to max_value 1. Calls "area_under_curve_estimator" function 2. Compares with the expected value 3. Prints estimated, expected and error value """ def identity_function(x: float) -> float: """ Represents identity function >>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]] [-2.0, -1.0, 0.0, 1.0, 2.0] """ return x estimated_value = area_under_curve_estimator( iterations, identity_function, min_value, max_value ) expected_value = (max_value * max_value - min_value * min_value) / 2 print("******************") print(f"Estimating area under y=x where x varies from {min_value} to {max_value}") print(f"Estimated value is {estimated_value}") print(f"Expected value is {expected_value}") print(f"Total error is {abs(estimated_value - expected_value)}") print("******************") def pi_estimator_using_area_under_curve(iterations: int) -> None: """ Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi """ def function_to_integrate(x: float) -> float: """ Represents semi-circle with radius 2 >>> [function_to_integrate(x) for x in [-2.0, 0.0, 2.0]] [0.0, 2.0, 0.0] """ return sqrt(4.0 - x * x) estimated_value = area_under_curve_estimator( iterations, function_to_integrate, 0.0, 2.0 ) print("******************") print("Estimating pi using area_under_curve_estimator") print(f"Estimated value is {estimated_value}") print(f"Expected value is {pi}") print(f"Total error is {abs(estimated_value - pi)}") print("******************") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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: OMKAR PATHAK """ from typing import Set class Graph: def __init__(self) -> None: self.vertices = {} def print_graph(self) -> None: """ prints adjacency list representation of graaph >>> g = Graph() >>> g.print_graph() >>> g.add_edge(0, 1) >>> g.print_graph() 0 : 1 """ for i in self.vertices: print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]])) def add_edge(self, from_vertex: int, to_vertex: int) -> None: """ adding the edge between two vertices >>> g = Graph() >>> g.print_graph() >>> g.add_edge(0, 1) >>> g.print_graph() 0 : 1 """ if from_vertex in self.vertices: self.vertices[from_vertex].append(to_vertex) else: self.vertices[from_vertex] = [to_vertex] def bfs(self, start_vertex: int) -> Set[int]: """ >>> g = Graph() >>> g.add_edge(0, 1) >>> g.add_edge(0, 1) >>> g.add_edge(0, 2) >>> g.add_edge(1, 2) >>> g.add_edge(2, 0) >>> g.add_edge(2, 3) >>> g.add_edge(3, 3) >>> sorted(g.bfs(2)) [0, 1, 2, 3] """ # initialize set for storing already visited vertices visited = set() # create a first in first out queue to store all the vertices for BFS queue = [] # mark the source node as visited and enqueue it visited.add(start_vertex) queue.append(start_vertex) while queue: vertex = queue.pop(0) # loop through all adjacent vertex and enqueue it if not yet visited for adjacent_vertex in self.vertices[vertex]: if adjacent_vertex not in visited: queue.append(adjacent_vertex) visited.add(adjacent_vertex) return visited if __name__ == "__main__": from doctest import testmod testmod(verbose=True) g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() # 0 : 1 -> 2 # 1 : 2 # 2 : 0 -> 3 # 3 : 3 assert sorted(g.bfs(2)) == [0, 1, 2, 3]
#!/usr/bin/python """ Author: OMKAR PATHAK """ from typing import Set class Graph: def __init__(self) -> None: self.vertices = {} def print_graph(self) -> None: """ prints adjacency list representation of graaph >>> g = Graph() >>> g.print_graph() >>> g.add_edge(0, 1) >>> g.print_graph() 0 : 1 """ for i in self.vertices: print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]])) def add_edge(self, from_vertex: int, to_vertex: int) -> None: """ adding the edge between two vertices >>> g = Graph() >>> g.print_graph() >>> g.add_edge(0, 1) >>> g.print_graph() 0 : 1 """ if from_vertex in self.vertices: self.vertices[from_vertex].append(to_vertex) else: self.vertices[from_vertex] = [to_vertex] def bfs(self, start_vertex: int) -> Set[int]: """ >>> g = Graph() >>> g.add_edge(0, 1) >>> g.add_edge(0, 1) >>> g.add_edge(0, 2) >>> g.add_edge(1, 2) >>> g.add_edge(2, 0) >>> g.add_edge(2, 3) >>> g.add_edge(3, 3) >>> sorted(g.bfs(2)) [0, 1, 2, 3] """ # initialize set for storing already visited vertices visited = set() # create a first in first out queue to store all the vertices for BFS queue = [] # mark the source node as visited and enqueue it visited.add(start_vertex) queue.append(start_vertex) while queue: vertex = queue.pop(0) # loop through all adjacent vertex and enqueue it if not yet visited for adjacent_vertex in self.vertices[vertex]: if adjacent_vertex not in visited: queue.append(adjacent_vertex) visited.add(adjacent_vertex) return visited if __name__ == "__main__": from doctest import testmod testmod(verbose=True) g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() # 0 : 1 -> 2 # 1 : 2 # 2 : 0 -> 3 # 3 : 3 assert sorted(g.bfs(2)) == [0, 1, 2, 3]
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ Returns True if the pandigital number passes all the divisibility tests. >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) False >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) False >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) True """ tests = [2, 3, 5, 7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 1] * 100 + num[i + 2] * 10 + num[i + 3]) % test != 0: return False return True def solution(n: int = 10) -> int: """ Returns the sum of all pandigital numbers which pass the divisiility tests. >>> solution(10) 16695334890 """ list_nums = [ int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ] return sum(list_nums) if __name__ == "__main__": print(f"{solution() = }")
""" Problem 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ Returns True if the pandigital number passes all the divisibility tests. >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) False >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) False >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) True """ tests = [2, 3, 5, 7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 1] * 100 + num[i + 2] * 10 + num[i + 3]) % test != 0: return False return True def solution(n: int = 10) -> int: """ Returns the sum of all pandigital numbers which pass the divisiility tests. >>> solution(10) 16695334890 """ list_nums = [ int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ] return sum(list_nums) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 bisect import bisect_left from functools import total_ordering from heapq import merge from typing import List """ A pure Python implementation of the patience sort algorithm For more information: https://en.wikipedia.org/wiki/Patience_sorting This algorithm is based on the card game patience For doctests run following command: python3 -m doctest -v patience_sort.py For manual testing run: python3 patience_sort.py """ @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(collection: list) -> list: """A pure implementation of quick sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> patience_sort([1, 9, 5, 21, 17, 6]) [1, 5, 6, 9, 17, 21] >>> patience_sort([]) [] >>> patience_sort([-3, -17, -48]) [-48, -17, -3] """ stacks: List[Stack] = [] # sort into stacks for element in collection: new_stacks = Stack([element]) i = bisect_left(stacks, new_stacks) if i != len(stacks): stacks[i].append(element) else: stacks.append(new_stacks) # use a heap-based merge to merge stack efficiently collection[:] = merge(*[reversed(stack) for stack in stacks]) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
from bisect import bisect_left from functools import total_ordering from heapq import merge from typing import List """ A pure Python implementation of the patience sort algorithm For more information: https://en.wikipedia.org/wiki/Patience_sorting This algorithm is based on the card game patience For doctests run following command: python3 -m doctest -v patience_sort.py For manual testing run: python3 patience_sort.py """ @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(collection: list) -> list: """A pure implementation of quick sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> patience_sort([1, 9, 5, 21, 17, 6]) [1, 5, 6, 9, 17, 21] >>> patience_sort([]) [] >>> patience_sort([-3, -17, -48]) [-48, -17, -3] """ stacks: List[Stack] = [] # sort into stacks for element in collection: new_stacks = Stack([element]) i = bisect_left(stacks, new_stacks) if i != len(stacks): stacks[i].append(element) else: stacks.append(new_stacks) # use a heap-based merge to merge stack efficiently collection[:] = merge(*[reversed(stack) for stack in stacks]) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 207: https://projecteuler.net/problem=207 Problem Statement: For some positive integers k, there exists an integer partition of the form 4**t = 2**t + k, where 4**t, 2**t, and k are all positive integers and t is a real number. The first two such partitions are 4**1 = 2**1 + 2 and 4**1.5849625... = 2**1.5849625... + 6. Partitions where t is also an integer are called perfect. For any m ≥ 1 let P(m) be the proportion of such partitions that are perfect with k ≤ m. Thus P(6) = 1/2. In the following table are listed some values of P(m) P(5) = 1/1 P(10) = 1/2 P(15) = 2/3 P(20) = 1/2 P(25) = 1/2 P(30) = 2/5 ... P(180) = 1/4 P(185) = 3/13 Find the smallest m for which P(m) < 1/12345 Solution: Equation 4**t = 2**t + k solved for t gives: t = log2(sqrt(4*k+1)/2 + 1/2) For t to be real valued, sqrt(4*k+1) must be an integer which is implemented in function check_t_real(k). For a perfect partition t must be an integer. To speed up significantly the search for partitions, instead of incrementing k by one per iteration, the next valid k is found by k = (i**2 - 1) / 4 with an integer i and k has to be a positive integer. If this is the case a partition is found. The partition is perfect if t os an integer. The integer i is increased with increment 1 until the proportion perfect partitions / total partitions drops under the given value. """ import math def check_partition_perfect(positive_integer: int) -> bool: """ Check if t = f(positive_integer) = log2(sqrt(4*positive_integer+1)/2 + 1/2) is a real number. >>> check_partition_perfect(2) True >>> check_partition_perfect(6) False """ exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent) def solution(max_proportion: float = 1 / 12345) -> int: """ Find m for which the proportion of perfect partitions to total partitions is lower than max_proportion >>> solution(1) > 5 True >>> solution(1/2) > 10 True >>> solution(3 / 13) > 185 True """ total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer ** 2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return partition_candidate integer += 1 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 207: https://projecteuler.net/problem=207 Problem Statement: For some positive integers k, there exists an integer partition of the form 4**t = 2**t + k, where 4**t, 2**t, and k are all positive integers and t is a real number. The first two such partitions are 4**1 = 2**1 + 2 and 4**1.5849625... = 2**1.5849625... + 6. Partitions where t is also an integer are called perfect. For any m ≥ 1 let P(m) be the proportion of such partitions that are perfect with k ≤ m. Thus P(6) = 1/2. In the following table are listed some values of P(m) P(5) = 1/1 P(10) = 1/2 P(15) = 2/3 P(20) = 1/2 P(25) = 1/2 P(30) = 2/5 ... P(180) = 1/4 P(185) = 3/13 Find the smallest m for which P(m) < 1/12345 Solution: Equation 4**t = 2**t + k solved for t gives: t = log2(sqrt(4*k+1)/2 + 1/2) For t to be real valued, sqrt(4*k+1) must be an integer which is implemented in function check_t_real(k). For a perfect partition t must be an integer. To speed up significantly the search for partitions, instead of incrementing k by one per iteration, the next valid k is found by k = (i**2 - 1) / 4 with an integer i and k has to be a positive integer. If this is the case a partition is found. The partition is perfect if t os an integer. The integer i is increased with increment 1 until the proportion perfect partitions / total partitions drops under the given value. """ import math def check_partition_perfect(positive_integer: int) -> bool: """ Check if t = f(positive_integer) = log2(sqrt(4*positive_integer+1)/2 + 1/2) is a real number. >>> check_partition_perfect(2) True >>> check_partition_perfect(6) False """ exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent) def solution(max_proportion: float = 1 / 12345) -> int: """ Find m for which the proportion of perfect partitions to total partitions is lower than max_proportion >>> solution(1) > 5 True >>> solution(1/2) > 10 True >>> solution(3 / 13) > 185 True """ total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer ** 2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return partition_candidate integer += 1 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome_counter("Momo") True >>> can_string_be_rearranged_as_palindrome_counter("Mother") False >>> can_string_be_rearranged_as_palindrome_counter("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ oddChar = 0 for character_count in character_freq_dict.values(): if character_count % 2: oddChar += 1 if oddChar > 1: return False return True def benchmark(input_str: str = "") -> None: """ Benchmark code for comparing above 2 functions """ print("\nFor string = ", input_str, ":") print( "> can_string_be_rearranged_as_palindrome_counter()", "\tans =", can_string_be_rearranged_as_palindrome_counter(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome_counter("Momo") True >>> can_string_be_rearranged_as_palindrome_counter("Mother") False >>> can_string_be_rearranged_as_palindrome_counter("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ oddChar = 0 for character_count in character_freq_dict.values(): if character_count % 2: oddChar += 1 if oddChar > 1: return False return True def benchmark(input_str: str = "") -> None: """ Benchmark code for comparing above 2 functions """ print("\nFor string = ", input_str, ":") print( "> can_string_be_rearranged_as_palindrome_counter()", "\tans =", can_string_be_rearranged_as_palindrome_counter(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
"""Password generator allows you to generate a random password of length N.""" from random import choice, shuffle from string import ascii_letters, digits, punctuation def password_generator(length=8): """ >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = tuple(ascii_letters) + tuple(digits) + tuple(punctuation) return "".join(choice(chars) for x in range(length)) # ALTERNATIVE METHODS # ctbi= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(ctbi, i): # Password generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i = i - len(ctbi) quotient = int(i / 3) remainder = i % 3 # chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( ctbi + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) chars = list(chars) shuffle(chars) return "".join(chars) # random is a generalised function for letters, characters and numbers def random(ctbi, i): return "".join(choice(ctbi) for x in range(i)) def random_number(ctbi, i): pass # Put your code here... def random_letters(ctbi, i): pass # Put your code here... def random_characters(ctbi, i): pass # Put your code here... def main(): length = int(input("Please indicate the max length of your password: ").strip()) ctbi = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(ctbi, length) ) print("[If you are thinking of using this passsword, You better save it.]") if __name__ == "__main__": main()
"""Password generator allows you to generate a random password of length N.""" from random import choice, shuffle from string import ascii_letters, digits, punctuation def password_generator(length=8): """ >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = tuple(ascii_letters) + tuple(digits) + tuple(punctuation) return "".join(choice(chars) for x in range(length)) # ALTERNATIVE METHODS # ctbi= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(ctbi, i): # Password generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i = i - len(ctbi) quotient = int(i / 3) remainder = i % 3 # chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( ctbi + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) chars = list(chars) shuffle(chars) return "".join(chars) # random is a generalised function for letters, characters and numbers def random(ctbi, i): return "".join(choice(ctbi) for x in range(i)) def random_number(ctbi, i): pass # Put your code here... def random_letters(ctbi, i): pass # Put your code here... def random_characters(ctbi, i): pass # Put your code here... def main(): length = int(input("Please indicate the max length of your password: ").strip()) ctbi = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(ctbi, length) ) print("[If you are thinking of using this passsword, You better save it.]") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ from statistics import mean from typing import List def calculate_waiting_times(burst_times: List[int]) -> List[int]: """ Calculate the waiting times of a list of processes that have a specified duration. Return: The waiting time for each process. >>> calculate_waiting_times([10, 5, 8]) [13, 10, 13] >>> calculate_waiting_times([4, 6, 3, 1]) [5, 8, 9, 6] >>> calculate_waiting_times([12, 2, 10]) [12, 2, 12] """ quantum = 2 rem_burst_times = list(burst_times) waiting_times = [0] * len(burst_times) t = 0 while True: done = True for i, burst_time in enumerate(burst_times): if rem_burst_times[i] > 0: done = False if rem_burst_times[i] > quantum: t += quantum rem_burst_times[i] -= quantum else: t += rem_burst_times[i] waiting_times[i] = t - burst_time rem_burst_times[i] = 0 if done is True: return waiting_times def calculate_turn_around_times( burst_times: List[int], waiting_times: List[int] ) -> List[int]: """ >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) [1, 3, 6] >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) [20, 9, 18] """ return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] if __name__ == "__main__": burst_times = [3, 5, 7] waiting_times = calculate_waiting_times(burst_times) turn_around_times = calculate_turn_around_times(burst_times, waiting_times) print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") for i, burst_time in enumerate(burst_times): print( f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " f"{turn_around_times[i]}" ) print(f"\nAverage waiting time = {mean(waiting_times):.5f}") print(f"Average turn around time = {mean(turn_around_times):.5f}")
""" Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ from statistics import mean from typing import List def calculate_waiting_times(burst_times: List[int]) -> List[int]: """ Calculate the waiting times of a list of processes that have a specified duration. Return: The waiting time for each process. >>> calculate_waiting_times([10, 5, 8]) [13, 10, 13] >>> calculate_waiting_times([4, 6, 3, 1]) [5, 8, 9, 6] >>> calculate_waiting_times([12, 2, 10]) [12, 2, 12] """ quantum = 2 rem_burst_times = list(burst_times) waiting_times = [0] * len(burst_times) t = 0 while True: done = True for i, burst_time in enumerate(burst_times): if rem_burst_times[i] > 0: done = False if rem_burst_times[i] > quantum: t += quantum rem_burst_times[i] -= quantum else: t += rem_burst_times[i] waiting_times[i] = t - burst_time rem_burst_times[i] = 0 if done is True: return waiting_times def calculate_turn_around_times( burst_times: List[int], waiting_times: List[int] ) -> List[int]: """ >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) [1, 3, 6] >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) [20, 9, 18] """ return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] if __name__ == "__main__": burst_times = [3, 5, 7] waiting_times = calculate_waiting_times(burst_times) turn_around_times = calculate_turn_around_times(burst_times, waiting_times) print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") for i, burst_time in enumerate(burst_times): print( f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " f"{turn_around_times[i]}" ) print(f"\nAverage waiting time = {mean(waiting_times):.5f}") print(f"Average turn around time = {mean(turn_around_times):.5f}")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# Created by sarathkaul on 12/11/19 import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: # fetching a list of articles in json format bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
# Created by sarathkaul on 12/11/19 import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: # fetching a list of articles in json format bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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/Hill_climbing import math class SearchProblem: """ An interface to define search problems. The interface will be illustrated using the example of mathematical function. """ def __init__(self, x: int, y: int, step_size: int, function_to_optimize): """ The constructor of the search problem. x: the x coordinate of the current search state. y: the y coordinate of the current search state. step_size: size of the step to take when looking for neighbors. function_to_optimize: a function to optimize having the signature f(x, y). """ self.x = x self.y = y self.step_size = step_size self.function = function_to_optimize def score(self) -> int: """ Returns the output of the function called with current x and y coordinates. >>> def test_function(x, y): ... return x + y >>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0 0 >>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12 12 """ return self.function(self.x, self.y) def get_neighbors(self): """ Returns a list of coordinates of neighbors adjacent to the current coordinates. Neighbors: | 0 | 1 | 2 | | 3 | _ | 4 | | 5 | 6 | 7 | """ step_size = self.step_size return [ SearchProblem(x, y, step_size, self.function) for x, y in ( (self.x - step_size, self.y - step_size), (self.x - step_size, self.y), (self.x - step_size, self.y + step_size), (self.x, self.y - step_size), (self.x, self.y + step_size), (self.x + step_size, self.y - step_size), (self.x + step_size, self.y), (self.x + step_size, self.y + step_size), ) ] def __hash__(self): """ hash the string representation of the current search state. """ return hash(str(self)) def __eq__(self, obj): """ Check if the 2 objects are equal. """ if isinstance(obj, SearchProblem): return hash(str(self)) == hash(str(obj)) return False def __str__(self): """ string representation of the current search state. >>> str(SearchProblem(0, 0, 1, None)) 'x: 0 y: 0' >>> str(SearchProblem(2, 5, 1, None)) 'x: 2 y: 5' """ return f"x: {self.x} y: {self.y}" def hill_climbing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, max_iter: int = 10000, ) -> SearchProblem: """ Implementation of the hill climbling algorithm. We start with a given state, find all its neighbors, move towards the neighbor which provides the maximum (or minimum) change. We keep doing this until we are at a state where we do not have any neighbors which can improve the solution. Args: search_prob: The search state at the start. find_max: If True, the algorithm should find the maximum else the minimum. max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. visualization: If True, a matplotlib graph is displayed. max_iter: number of times to run the iteration. Returns a search state having the maximum (or minimum) score. """ current_state = search_prob scores = [] # list to store the current score at each iteration iterations = 0 solution_found = False visited = set() while not solution_found and iterations < max_iter: visited.add(current_state) iterations += 1 current_score = current_state.score() scores.append(current_score) neighbors = current_state.get_neighbors() max_change = -math.inf min_change = math.inf next_state = None # to hold the next best neighbor for neighbor in neighbors: if neighbor in visited: continue # do not want to visit the same state again if ( neighbor.x > max_x or neighbor.x < min_x or neighbor.y > max_y or neighbor.y < min_y ): continue # neighbor outside our bounds change = neighbor.score() - current_score if find_max: # finding max # going to direction with greatest ascent if change > max_change and change > 0: max_change = change next_state = neighbor else: # finding min # to direction with greatest descent if change < min_change and change < 0: min_change = change next_state = neighbor if next_state is not None: # we found at least one neighbor which improved the current state current_state = next_state else: # since we have no neighbor that improves the solution we stop the search solution_found = True if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return current_state if __name__ == "__main__": import doctest doctest.testmod() def test_f1(x, y): return (x ** 2) + (y ** 2) # starting the problem with initial coordinates (3, 4) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=False) print( "The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x ** 2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=True) print( "The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" )
# https://en.wikipedia.org/wiki/Hill_climbing import math class SearchProblem: """ An interface to define search problems. The interface will be illustrated using the example of mathematical function. """ def __init__(self, x: int, y: int, step_size: int, function_to_optimize): """ The constructor of the search problem. x: the x coordinate of the current search state. y: the y coordinate of the current search state. step_size: size of the step to take when looking for neighbors. function_to_optimize: a function to optimize having the signature f(x, y). """ self.x = x self.y = y self.step_size = step_size self.function = function_to_optimize def score(self) -> int: """ Returns the output of the function called with current x and y coordinates. >>> def test_function(x, y): ... return x + y >>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0 0 >>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12 12 """ return self.function(self.x, self.y) def get_neighbors(self): """ Returns a list of coordinates of neighbors adjacent to the current coordinates. Neighbors: | 0 | 1 | 2 | | 3 | _ | 4 | | 5 | 6 | 7 | """ step_size = self.step_size return [ SearchProblem(x, y, step_size, self.function) for x, y in ( (self.x - step_size, self.y - step_size), (self.x - step_size, self.y), (self.x - step_size, self.y + step_size), (self.x, self.y - step_size), (self.x, self.y + step_size), (self.x + step_size, self.y - step_size), (self.x + step_size, self.y), (self.x + step_size, self.y + step_size), ) ] def __hash__(self): """ hash the string representation of the current search state. """ return hash(str(self)) def __eq__(self, obj): """ Check if the 2 objects are equal. """ if isinstance(obj, SearchProblem): return hash(str(self)) == hash(str(obj)) return False def __str__(self): """ string representation of the current search state. >>> str(SearchProblem(0, 0, 1, None)) 'x: 0 y: 0' >>> str(SearchProblem(2, 5, 1, None)) 'x: 2 y: 5' """ return f"x: {self.x} y: {self.y}" def hill_climbing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, max_iter: int = 10000, ) -> SearchProblem: """ Implementation of the hill climbling algorithm. We start with a given state, find all its neighbors, move towards the neighbor which provides the maximum (or minimum) change. We keep doing this until we are at a state where we do not have any neighbors which can improve the solution. Args: search_prob: The search state at the start. find_max: If True, the algorithm should find the maximum else the minimum. max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. visualization: If True, a matplotlib graph is displayed. max_iter: number of times to run the iteration. Returns a search state having the maximum (or minimum) score. """ current_state = search_prob scores = [] # list to store the current score at each iteration iterations = 0 solution_found = False visited = set() while not solution_found and iterations < max_iter: visited.add(current_state) iterations += 1 current_score = current_state.score() scores.append(current_score) neighbors = current_state.get_neighbors() max_change = -math.inf min_change = math.inf next_state = None # to hold the next best neighbor for neighbor in neighbors: if neighbor in visited: continue # do not want to visit the same state again if ( neighbor.x > max_x or neighbor.x < min_x or neighbor.y > max_y or neighbor.y < min_y ): continue # neighbor outside our bounds change = neighbor.score() - current_score if find_max: # finding max # going to direction with greatest ascent if change > max_change and change > 0: max_change = change next_state = neighbor else: # finding min # to direction with greatest descent if change < min_change and change < 0: min_change = change next_state = neighbor if next_state is not None: # we found at least one neighbor which improved the current state current_state = next_state else: # since we have no neighbor that improves the solution we stop the search solution_found = True if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return current_state if __name__ == "__main__": import doctest doctest.testmod() def test_f1(x, y): return (x ** 2) + (y ** 2) # starting the problem with initial coordinates (3, 4) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=False) print( "The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x ** 2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=True) print( "The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" )
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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: OMKAR PATHAK """ class Graph: def __init__(self): self.vertex = {} # for printing the Graph vertices def print_graph(self) -> None: print(self.vertex) for i in self.vertex: print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]])) # for adding the edge between two vertices def add_edge(self, from_vertex: int, to_vertex: int) -> None: # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(to_vertex) else: # else make a new vertex self.vertex[from_vertex] = [to_vertex] def dfs(self) -> None: # visited array for storing already visited nodes visited = [False] * len(self.vertex) # call the recursive helper function for i in range(len(self.vertex)): if not visited[i]: self.dfs_recursive(i, visited) def dfs_recursive(self, start_vertex: int, visited: list) -> None: # mark start vertex as visited visited[start_vertex] = True print(start_vertex, end=" ") # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(i, visited) if __name__ == "__main__": g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("DFS:") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
#!/usr/bin/python """ Author: OMKAR PATHAK """ class Graph: def __init__(self): self.vertex = {} # for printing the Graph vertices def print_graph(self) -> None: print(self.vertex) for i in self.vertex: print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]])) # for adding the edge between two vertices def add_edge(self, from_vertex: int, to_vertex: int) -> None: # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(to_vertex) else: # else make a new vertex self.vertex[from_vertex] = [to_vertex] def dfs(self) -> None: # visited array for storing already visited nodes visited = [False] * len(self.vertex) # call the recursive helper function for i in range(len(self.vertex)): if not visited[i]: self.dfs_recursive(i, visited) def dfs_recursive(self, start_vertex: int, visited: list) -> None: # mark start vertex as visited visited[start_vertex] = True print(start_vertex, end=" ") # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(i, visited) if __name__ == "__main__": g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("DFS:") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 sklearn.neural_network import MLPClassifier X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]] y = [0, 1, 0, 0] clf = MLPClassifier( solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1 ) clf.fit(X, y) test = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]] Y = clf.predict(test) def wrapper(Y): """ >>> wrapper(Y) [0, 0, 1] """ return list(Y) if __name__ == "__main__": import doctest doctest.testmod()
from sklearn.neural_network import MLPClassifier X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]] y = [0, 1, 0, 0] clf = MLPClassifier( solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1 ) clf.fit(X, y) test = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]] Y = clf.predict(test) def wrapper(Y): """ >>> wrapper(Y) [0, 0, 1] """ return list(Y) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 topologicalSort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topologicalSort(graph)
def topologicalSort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topologicalSort(graph)
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 """ result = 0 for i in range(n): if i % 3 == 0: result += i elif i % 5 == 0: result += i return result 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 """ result = 0 for i in range(n): if i % 3 == 0: result += i elif i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Coin sums Problem 31: https://projecteuler.net/problem=31 In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? """ def one_pence() -> int: return 1 def two_pence(x: int) -> int: return 0 if x < 0 else two_pence(x - 2) + one_pence() def five_pence(x: int) -> int: return 0 if x < 0 else five_pence(x - 5) + two_pence(x) def ten_pence(x: int) -> int: return 0 if x < 0 else ten_pence(x - 10) + five_pence(x) def twenty_pence(x: int) -> int: return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x) def fifty_pence(x: int) -> int: return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x) def one_pound(x: int) -> int: return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x) def two_pound(x: int) -> int: return 0 if x < 0 else two_pound(x - 200) + one_pound(x) def solution(n: int = 200) -> int: """Returns the number of different ways can n pence be made using any number of coins? >>> solution(500) 6295434 >>> solution(200) 73682 >>> solution(50) 451 >>> solution(10) 11 """ return two_pound(n) if __name__ == "__main__": print(solution(int(input().strip())))
""" Coin sums Problem 31: https://projecteuler.net/problem=31 In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? """ def one_pence() -> int: return 1 def two_pence(x: int) -> int: return 0 if x < 0 else two_pence(x - 2) + one_pence() def five_pence(x: int) -> int: return 0 if x < 0 else five_pence(x - 5) + two_pence(x) def ten_pence(x: int) -> int: return 0 if x < 0 else ten_pence(x - 10) + five_pence(x) def twenty_pence(x: int) -> int: return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x) def fifty_pence(x: int) -> int: return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x) def one_pound(x: int) -> int: return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x) def two_pound(x: int) -> int: return 0 if x < 0 else two_pound(x - 200) + one_pound(x) def solution(n: int = 200) -> int: """Returns the number of different ways can n pence be made using any number of coins? >>> solution(500) 6295434 >>> solution(200) 73682 >>> solution(50) 451 >>> solution(10) 11 """ return two_pound(n) if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations seive = [True] * 1000001 seive[1] = False i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise, for 1 <= n <= 1000000 >>> is_prime(87) False >>> is_prime(1) False >>> is_prime(25363) False """ return seive[n] def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
""" The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations seive = [True] * 1000001 seive[1] = False i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise, for 1 <= n <= 1000000 >>> is_prime(87) False >>> is_prime(1) False >>> is_prime(25363) False """ return seive[n] def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 188: https://projecteuler.net/problem=188 The hyperexponentiation of a number The hyperexponentiation or tetration of a number a by a positive integer b, denoted by a↑↑b or b^a, is recursively defined by: a↑↑1 = a, a↑↑(k+1) = a(a↑↑k). Thus we have e.g. 3↑↑2 = 3^3 = 27, hence 3↑↑3 = 3^27 = 7625597484987 and 3↑↑4 is roughly 103.6383346400240996*10^12. Find the last 8 digits of 1777↑↑1855. References: - https://en.wikipedia.org/wiki/Tetration """ # small helper function for modular exponentiation def _modexpt(base: int, exponent: int, modulo_value: int) -> int: """ Returns the modular exponentiation, that is the value of `base ** exponent % modulo_value`, without calculating the actual number. >>> _modexpt(2, 4, 10) 6 >>> _modexpt(2, 1024, 100) 16 >>> _modexpt(13, 65535, 7) 6 """ if exponent == 1: return base if exponent % 2 == 0: x = _modexpt(base, exponent / 2, modulo_value) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(base, exponent - 1, modulo_value)) % modulo_value def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: """ Returns the last 8 digits of the hyperexponentiation of base by height, i.e. the number base↑↑height: >>> solution(base=3, height=2) 27 >>> solution(base=3, height=3) 97484987 >>> solution(base=123, height=456, digits=4) 2547 """ # calculate base↑↑height by right-assiciative repeated modular # exponentiation result = base for i in range(1, height): result = _modexpt(base, result, 10 ** digits) return result if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 188: https://projecteuler.net/problem=188 The hyperexponentiation of a number The hyperexponentiation or tetration of a number a by a positive integer b, denoted by a↑↑b or b^a, is recursively defined by: a↑↑1 = a, a↑↑(k+1) = a(a↑↑k). Thus we have e.g. 3↑↑2 = 3^3 = 27, hence 3↑↑3 = 3^27 = 7625597484987 and 3↑↑4 is roughly 103.6383346400240996*10^12. Find the last 8 digits of 1777↑↑1855. References: - https://en.wikipedia.org/wiki/Tetration """ # small helper function for modular exponentiation def _modexpt(base: int, exponent: int, modulo_value: int) -> int: """ Returns the modular exponentiation, that is the value of `base ** exponent % modulo_value`, without calculating the actual number. >>> _modexpt(2, 4, 10) 6 >>> _modexpt(2, 1024, 100) 16 >>> _modexpt(13, 65535, 7) 6 """ if exponent == 1: return base if exponent % 2 == 0: x = _modexpt(base, exponent / 2, modulo_value) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(base, exponent - 1, modulo_value)) % modulo_value def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: """ Returns the last 8 digits of the hyperexponentiation of base by height, i.e. the number base↑↑height: >>> solution(base=3, height=2) 27 >>> solution(base=3, height=3) 97484987 >>> solution(base=123, height=456, digits=4) 2547 """ # calculate base↑↑height by right-assiciative repeated modular # exponentiation result = base for i in range(1, height): result = _modexpt(base, result, 10 ** digits) return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2 ,len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heap_sort(array) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(sort(unsorted))
""" Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2 ,len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heap_sort(array) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(sort(unsorted))
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Chinese Remainder Theorem: GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are two such integers, then n1=n2(mod ab) Algorithm : 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 2. Take n = ra*by + rb*ax """ from typing import Tuple # Extended Euclid def extended_euclid(a: int, b: int) -> Tuple[int, int]: """ >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem(5,1,7,3) 31 Explanation : 31 is the smallest number such that (i) When we divide it by 5, we get remainder 1 (ii) When we divide it by 7, we get remainder 3 >>> chinese_remainder_theorem(6,1,4,3) 14 """ (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: """ >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem2(5,1,7,3) 31 >>> chinese_remainder_theorem2(6,1,4,3) 14 """ x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
""" Chinese Remainder Theorem: GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are two such integers, then n1=n2(mod ab) Algorithm : 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 2. Take n = ra*by + rb*ax """ from typing import Tuple # Extended Euclid def extended_euclid(a: int, b: int) -> Tuple[int, int]: """ >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem(5,1,7,3) 31 Explanation : 31 is the smallest number such that (i) When we divide it by 5, we get remainder 1 (ii) When we divide it by 7, we get remainder 3 >>> chinese_remainder_theorem(6,1,4,3) 14 """ (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: """ >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem2(5,1,7,3) 31 >>> chinese_remainder_theorem2(6,1,4,3) 14 """ x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 dencrypt(s: str, n: int = 13) -> str: """ https://en.wikipedia.org/wiki/ROT13 >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" >>> s = dencrypt(msg) >>> s "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" >>> dencrypt(s) == msg True """ out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2) if __name__ == "__main__": import doctest doctest.testmod() main()
def dencrypt(s: str, n: int = 13) -> str: """ https://en.wikipedia.org/wiki/ROT13 >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" >>> s = dencrypt(msg) >>> s "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" >>> dencrypt(s) == msg True """ out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 max_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
def max_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 tensorflow as tf from random import shuffle from numpy import array def TFKMeansCluster(vectors, noofclusters): """ K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer. """ noofclusters = int(noofclusters) assert noofclusters < len(vectors) # Find out the dimensionality dim = len(vectors[0]) # Will help select random centroids from among the available vectors vector_indices = list(range(len(vectors))) shuffle(vector_indices) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. graph = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION sess = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points centroids = [ tf.Variable(vectors[vector_indices[i]]) for i in range(noofclusters) ] ##These nodes will assign the centroid Variables the appropriate ##values centroid_value = tf.placeholder("float64", [dim]) cent_assigns = [] for centroid in centroids: cent_assigns.append(tf.assign(centroid, centroid_value)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) assignments = [tf.Variable(0) for i in range(len(vectors))] ##These nodes will assign an assignment Variable the appropriate ##value assignment_value = tf.placeholder("int32") cluster_assigns = [] for assignment in assignments: cluster_assigns.append(tf.assign(assignment, assignment_value)) ##Now lets construct the node that will compute the mean # The placeholder for the input mean_input = tf.placeholder("float", [None, dim]) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors mean_op = tf.reduce_mean(mean_input, 0) ##Node for computing Euclidean distances # Placeholders for input v1 = tf.placeholder("float", [dim]) v2 = tf.placeholder("float", [dim]) euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(v1, v2), 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input centroid_distances = tf.placeholder("float", [noofclusters]) cluster_assignment = tf.argmin(centroid_distances, 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. init_op = tf.initialize_all_variables() # Initialize all variables sess.run(init_op) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. noofiterations = 100 for iteration_n in range(noofiterations): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(vectors)): vect = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. distances = [ sess.run(euclid_dist, feed_dict={v1: vect, v2: sess.run(centroid)}) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input assignment = sess.run( cluster_assignment, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(noofclusters): # Collect all the vectors assigned to this cluster assigned_vects = [ vectors[i] for i in range(len(vectors)) if sess.run(assignments[i]) == cluster_n ] # Compute new centroid location new_location = sess.run( mean_op, feed_dict={mean_input: array(assigned_vects)} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments centroids = sess.run(centroids) assignments = sess.run(assignments) return centroids, assignments
import tensorflow as tf from random import shuffle from numpy import array def TFKMeansCluster(vectors, noofclusters): """ K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer. """ noofclusters = int(noofclusters) assert noofclusters < len(vectors) # Find out the dimensionality dim = len(vectors[0]) # Will help select random centroids from among the available vectors vector_indices = list(range(len(vectors))) shuffle(vector_indices) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. graph = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION sess = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points centroids = [ tf.Variable(vectors[vector_indices[i]]) for i in range(noofclusters) ] ##These nodes will assign the centroid Variables the appropriate ##values centroid_value = tf.placeholder("float64", [dim]) cent_assigns = [] for centroid in centroids: cent_assigns.append(tf.assign(centroid, centroid_value)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) assignments = [tf.Variable(0) for i in range(len(vectors))] ##These nodes will assign an assignment Variable the appropriate ##value assignment_value = tf.placeholder("int32") cluster_assigns = [] for assignment in assignments: cluster_assigns.append(tf.assign(assignment, assignment_value)) ##Now lets construct the node that will compute the mean # The placeholder for the input mean_input = tf.placeholder("float", [None, dim]) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors mean_op = tf.reduce_mean(mean_input, 0) ##Node for computing Euclidean distances # Placeholders for input v1 = tf.placeholder("float", [dim]) v2 = tf.placeholder("float", [dim]) euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(v1, v2), 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input centroid_distances = tf.placeholder("float", [noofclusters]) cluster_assignment = tf.argmin(centroid_distances, 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. init_op = tf.initialize_all_variables() # Initialize all variables sess.run(init_op) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. noofiterations = 100 for iteration_n in range(noofiterations): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(vectors)): vect = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. distances = [ sess.run(euclid_dist, feed_dict={v1: vect, v2: sess.run(centroid)}) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input assignment = sess.run( cluster_assignment, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(noofclusters): # Collect all the vectors assigned to this cluster assigned_vects = [ vectors[i] for i in range(len(vectors)) if sess.run(assignments[i]) == cluster_n ] # Compute new centroid location new_location = sess.run( mean_op, feed_dict={mean_input: array(assigned_vects)} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments centroids = sess.run(centroids) assignments = sess.run(assignments) return centroids, assignments
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: n needs to be positive integer, your input -7 """ assert ( isinstance(n, int) and n > 0 ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: n needs to be positive integer, your input -7 """ assert ( isinstance(n, int) and n > 0 ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" developed by: markmelnic original repo: https://github.com/markmelnic/Scoring-Algorithm Analyse data using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation. The basic principle is that all values supplied will be broken down to a range from 0 to 1 and each column's score will be added up to get the total score. ========== Example for data of vehicles price|mileage|registration_year 20k |60k |2012 22k |50k |2011 23k |90k |2015 16k |210k |2010 We want the vehicle with the lowest price, lowest mileage but newest registration year. Thus the weights for each column are as follows: [0, 0, 1] >>> procentual_proximity([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]], [0, 0, 1]) [[20, 60, 2012, 2.0], [23, 90, 2015, 1.0], [22, 50, 2011, 1.3333333333333335]] """ def procentual_proximity(source_data: list, weights: list) -> list: """ weights - int list possible values - 0 / 1 0 if lower values have higher weight in the data set 1 if higher values have higher weight in the data set """ # getting data data_lists = [] for item in source_data: for i in range(len(item)): try: data_lists[i].append(float(item[i])) except IndexError: # generate corresponding number of lists data_lists.append([]) data_lists[i].append(float(item[i])) score_lists = [] # calculating each score for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) # weight not 0 or 1 else: raise ValueError("Invalid weight of %f provided" % (weight)) score_lists.append(score) # initialize final scores final_scores = [0 for i in range(len(score_lists[0]))] # generate final scores for i, slist in enumerate(score_lists): for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele # append scores to source data for i, ele in enumerate(final_scores): source_data[i].append(ele) return source_data
""" developed by: markmelnic original repo: https://github.com/markmelnic/Scoring-Algorithm Analyse data using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation. The basic principle is that all values supplied will be broken down to a range from 0 to 1 and each column's score will be added up to get the total score. ========== Example for data of vehicles price|mileage|registration_year 20k |60k |2012 22k |50k |2011 23k |90k |2015 16k |210k |2010 We want the vehicle with the lowest price, lowest mileage but newest registration year. Thus the weights for each column are as follows: [0, 0, 1] >>> procentual_proximity([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]], [0, 0, 1]) [[20, 60, 2012, 2.0], [23, 90, 2015, 1.0], [22, 50, 2011, 1.3333333333333335]] """ def procentual_proximity(source_data: list, weights: list) -> list: """ weights - int list possible values - 0 / 1 0 if lower values have higher weight in the data set 1 if higher values have higher weight in the data set """ # getting data data_lists = [] for item in source_data: for i in range(len(item)): try: data_lists[i].append(float(item[i])) except IndexError: # generate corresponding number of lists data_lists.append([]) data_lists[i].append(float(item[i])) score_lists = [] # calculating each score for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) # weight not 0 or 1 else: raise ValueError("Invalid weight of %f provided" % (weight)) score_lists.append(score) # initialize final scores final_scores = [0 for i in range(len(score_lists[0]))] # generate final scores for i, slist in enumerate(score_lists): for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele # append scores to source data for i, ele in enumerate(final_scores): source_data[i].append(ele) return source_data
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" == Krishnamurthy Number == It is also known as Peterson Number A Krishnamurthy Number is a number whose sum of the factorial of the digits equals to the original number itself. For example: 145 = 1! + 4! + 5! So, 145 is a Krishnamurthy Number """ def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: """ >>> krishnamurthy(145) True >>> krishnamurthy(240) False >>> krishnamurthy(1) True """ factSum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) factSum += factorial(digit) return factSum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." )
""" == Krishnamurthy Number == It is also known as Peterson Number A Krishnamurthy Number is a number whose sum of the factorial of the digits equals to the original number itself. For example: 145 = 1! + 4! + 5! So, 145 is a Krishnamurthy Number """ def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: """ >>> krishnamurthy(145) True >>> krishnamurthy(240) False >>> krishnamurthy(1) True """ factSum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) factSum += factorial(digit) return factSum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." )
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(graph): visited = [False] * len(graph) color = [-1] * len(graph) def dfs(v, c): visited[v] = True color[v] = c for u in graph[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(graph)): if not visited[i]: dfs(i, 0) for i in range(len(graph)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(graph): visited = [False] * len(graph) color = [-1] * len(graph) def dfs(v, c): visited[v] = True color[v] = c for u in graph[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(graph)): if not visited[i]: dfs(i, 0) for i in range(len(graph)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from typing import Optional def slowsort( sequence: list, start: Optional[int] = None, end: Optional[int] = None ) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from typing import Optional def slowsort( sequence: list, start: Optional[int] = None, end: Optional[int] = None ) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. :param list_data: mutable ordered sequence of elements :param length: length of list data :return: the same list in ascending order >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] >>> bubble_sort([], 0) [] >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": import doctest doctest.testmod()
def bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. :param list_data: mutable ordered sequence of elements :param length: length of list data :return: the same list in ascending order >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] >>> bubble_sort([], 0) [] >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 72 Counting fractions: https://projecteuler.net/problem=72 Description: Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? Solution: Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000 Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve. Time: 3.5 sec """ def solution(limit: int = 1_000_000) -> int: """ Returns an integer, the solution to the problem >>> solution(10) 31 >>> solution(100) 3043 >>> solution(1_000) 304191 """ phi = [i - 1 for i in range(limit + 1)] for i in range(2, limit + 1): for j in range(2 * i, limit + 1, i): phi[j] -= phi[i] return sum(phi[2 : limit + 1]) if __name__ == "__main__": print(solution())
""" Problem 72 Counting fractions: https://projecteuler.net/problem=72 Description: Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? Solution: Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000 Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve. Time: 3.5 sec """ def solution(limit: int = 1_000_000) -> int: """ Returns an integer, the solution to the problem >>> solution(10) 31 >>> solution(100) 3043 >>> solution(1_000) 304191 """ phi = [i - 1 for i in range(limit + 1)] for i in range(2, limit + 1): for j in range(2 * i, limit + 1, i): phi[j] -= phi[i] return sum(phi[2 : limit + 1]) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Create a Long Short Term Memory (LSTM) network model An LSTM is a type of Recurrent Neural Network (RNN) as discussed at: * http://colah.github.io/posts/2015-08-Understanding-LSTMs * https://en.wikipedia.org/wiki/Long_short-term_memory """ import numpy as np import pandas as pd from keras.layers import LSTM, Dense from keras.models import Sequential from sklearn.preprocessing import MinMaxScaler if __name__ == "__main__": """ First part of building a model is to get the data and prepare it for our model. You can use any dataset for stock prediction make sure you set the price column on line number 21. Here we use a dataset which have the price on 3rd column. """ df = pd.read_csv("sample_data.csv", header=None) len_data = df.shape[:1][0] # If you're using some other dataset input the target column actual_data = df.iloc[:, 1:2] actual_data = actual_data.values.reshape(len_data, 1) actual_data = MinMaxScaler().fit_transform(actual_data) look_back = 10 forward_days = 5 periods = 20 division = len_data - periods * look_back train_data = actual_data[:division] test_data = actual_data[division - look_back :] train_x, train_y = [], [] test_x, test_y = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) x_train = np.array(train_x) x_test = np.array(test_x) y_train = np.array([list(i.ravel()) for i in train_y]) y_test = np.array([list(i.ravel()) for i in test_y]) model = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") history = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) pred = model.predict(x_test)
""" Create a Long Short Term Memory (LSTM) network model An LSTM is a type of Recurrent Neural Network (RNN) as discussed at: * http://colah.github.io/posts/2015-08-Understanding-LSTMs * https://en.wikipedia.org/wiki/Long_short-term_memory """ import numpy as np import pandas as pd from keras.layers import LSTM, Dense from keras.models import Sequential from sklearn.preprocessing import MinMaxScaler if __name__ == "__main__": """ First part of building a model is to get the data and prepare it for our model. You can use any dataset for stock prediction make sure you set the price column on line number 21. Here we use a dataset which have the price on 3rd column. """ df = pd.read_csv("sample_data.csv", header=None) len_data = df.shape[:1][0] # If you're using some other dataset input the target column actual_data = df.iloc[:, 1:2] actual_data = actual_data.values.reshape(len_data, 1) actual_data = MinMaxScaler().fit_transform(actual_data) look_back = 10 forward_days = 5 periods = 20 division = len_data - periods * look_back train_data = actual_data[:division] test_data = actual_data[division - look_back :] train_x, train_y = [], [] test_x, test_y = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) x_train = np.array(train_x) x_test = np.array(test_x) y_train = np.array([list(i.ravel()) for i in train_y]) y_test = np.array([list(i.ravel()) for i in test_y]) model = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") history = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) pred = model.predict(x_test)
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
### Computer Vision Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human vision does, and then provide appropriate output. It is like imparting human intelligence and instincts to a computer. Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc. While computer vision comes from modelling image processing using the techniques of machine learning, computer vision applies machine learning to recognize patterns for interpretation of images (much like the process of visual reasoning of human vision).
### Computer Vision Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human vision does, and then provide appropriate output. It is like imparting human intelligence and instincts to a computer. Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc. While computer vision comes from modelling image processing using the techniques of machine learning, computer vision applies machine learning to recognize patterns for interpretation of images (much like the process of visual reasoning of human vision).
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Implements a disjoint set using Lists and some added heuristics for efficiency Union by Rank Heuristic and Path Compression """ class DisjointSet: def __init__(self, set_counts: list) -> None: """ Initialize with a list of the number of items in each set and with rank = 1 for each set """ self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets self.parents = list(range(num_sets)) def merge(self, src: int, dst: int) -> bool: """ Merge two sets together using Union by rank heuristic Return True if successful Merge two disjoint sets >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.merge(0, 2) True >>> A.merge(0, 1) False """ src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] self.set_counts[src_parent] = 0 self.parents[src_parent] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 joined_set_size = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] self.set_counts[dst_parent] = 0 self.parents[dst_parent] = src_parent joined_set_size = self.set_counts[src_parent] self.max_set = max(self.max_set, joined_set_size) return True def get_parent(self, disj_set: int) -> int: """ Find the Parent of a given set >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.get_parent(0) 0 >>> A.get_parent(1) 2 """ if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
""" Implements a disjoint set using Lists and some added heuristics for efficiency Union by Rank Heuristic and Path Compression """ class DisjointSet: def __init__(self, set_counts: list) -> None: """ Initialize with a list of the number of items in each set and with rank = 1 for each set """ self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets self.parents = list(range(num_sets)) def merge(self, src: int, dst: int) -> bool: """ Merge two sets together using Union by rank heuristic Return True if successful Merge two disjoint sets >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.merge(0, 2) True >>> A.merge(0, 1) False """ src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] self.set_counts[src_parent] = 0 self.parents[src_parent] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 joined_set_size = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] self.set_counts[dst_parent] = 0 self.parents[dst_parent] = src_parent joined_set_size = self.set_counts[src_parent] self.max_set = max(self.max_set, joined_set_size) return True def get_parent(self, disj_set: int) -> int: """ Find the Parent of a given set >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.get_parent(0) 0 >>> A.get_parent(1) 2 """ if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: """ >>> two_sum([2, 7, 11, 15], 9) [0, 1] >>> two_sum([15, 2, 11, 7], 13) [1, 2] >>> two_sum([2, 7, 11, 15], 17) [0, 3] >>> two_sum([7, 15, 11, 2], 18) [0, 2] >>> two_sum([2, 7, 11, 15], 26) [2, 3] >>> two_sum([2, 7, 11, 15], 8) [] >>> two_sum([3 * i for i in range(10)], 19) [] """ chk_map = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: return [chk_map[compl], index] chk_map[val] = index return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_sum([2, 7, 11, 15], 9) = }")
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: """ >>> two_sum([2, 7, 11, 15], 9) [0, 1] >>> two_sum([15, 2, 11, 7], 13) [1, 2] >>> two_sum([2, 7, 11, 15], 17) [0, 3] >>> two_sum([7, 15, 11, 2], 18) [0, 2] >>> two_sum([2, 7, 11, 15], 26) [2, 3] >>> two_sum([2, 7, 11, 15], 8) [] >>> two_sum([3 * i for i in range(10)], 19) [] """ chk_map = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: return [chk_map[compl], index] chk_map[val] = index return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_sum([2, 7, 11, 15], 9) = }")
-1
TheAlgorithms/Python
4,317
fix(mypy): type annotations for linear algebra algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-05T11:42:12Z"
"2021-04-05T13:37:38Z"
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
8c2986026bc42d81a6d9386c9fe621fea8ff2d15
fix(mypy): type annotations for linear algebra algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 get_set_bits_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count(25) 3 >>> get_set_bits_count(37) 3 >>> get_set_bits_count(21) 3 >>> get_set_bits_count(58) 4 >>> get_set_bits_count(0) 0 >>> get_set_bits_count(256) 1 >>> get_set_bits_count(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive """ if number < 0: raise ValueError("the value of input must be positive") result = 0 while number: if number % 2 == 1: result += 1 number = number >> 1 return result if __name__ == "__main__": import doctest doctest.testmod()
def get_set_bits_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count(25) 3 >>> get_set_bits_count(37) 3 >>> get_set_bits_count(21) 3 >>> get_set_bits_count(58) 4 >>> get_set_bits_count(0) 0 >>> get_set_bits_count(256) 1 >>> get_set_bits_count(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive """ if number < 0: raise ValueError("the value of input must be positive") result = 0 while number: if number % 2 == 1: result += 1 number = number >> 1 return result if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
name: "build" on: pull_request: schedule: - cron: "0 0 * * *" # Run everyday jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: "3.9" - uses: actions/cache@v2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools six wheel python -m pip install mypy pytest-cov -r requirements.txt # FIXME: #4052 fix mypy errors in the exclude directories and remove them below - run: mypy --ignore-missing-imports --exclude '(conversions|data_structures|digital_image_processing|dynamic_programming|graphs|linear_algebra|maths|matrix|other|project_euler|scripts|searches|strings*)/$' . - name: Run tests run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/ --cov-report=term-missing:skip-covered --cov=. . - if: ${{ success() }} run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
name: "build" on: pull_request: schedule: - cron: "0 0 * * *" # Run everyday jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: "3.9" - uses: actions/cache@v2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools six wheel python -m pip install mypy pytest-cov -r requirements.txt # FIXME: #4052 fix mypy errors in the exclude directories and remove them below - run: mypy --ignore-missing-imports --exclude '(data_structures|digital_image_processing|dynamic_programming|graphs|linear_algebra|maths|matrix|other|project_euler|scripts|searches|strings*)/$' . - name: Run tests run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/ --cov-report=term-missing:skip-covered --cov=. . - if: ${{ success() }} run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 in range(len(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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if type(num) == float: raise TypeError("'float' object cannot be interpreted as an integer") if type(num) == str: raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) if __name__ == "__main__": import doctest doctest.testmod()
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if isinstance(num, float): raise TypeError("'float' object cannot be interpreted as an integer") if isinstance(num, str): raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary: list[int] = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal): """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
"""Convert a Decimal Number to an Octal Number.""" import math # Modified from: # https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js def decimal_to_octal(num: int) -> str: """Convert a Decimal Number to an Octal Number. >>> all(decimal_to_octal(i) == oct(i) for i ... in (0, 2, 8, 64, 65, 216, 255, 256, 512)) True """ octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.pow(10, counter)) counter += 1 num = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"0o{int(octal)}" def main(): """Print octal equivalents of decimal numbers.""" print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") print(decimal_to_octal(8)) # = 10 print("\n65 in octal is:") print(decimal_to_octal(65)) # = 101 print("\n216 in octal is:") print(decimal_to_octal(216)) # = 330 print("\n512 in octal is:") print(decimal_to_octal(512)) # = 1000 print("\n") if __name__ == "__main__": main()
"""Convert a Decimal Number to an Octal Number.""" import math # Modified from: # https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js def decimal_to_octal(num: int) -> str: """Convert a Decimal Number to an Octal Number. >>> all(decimal_to_octal(i) == oct(i) for i ... in (0, 2, 8, 64, 65, 216, 255, 256, 512)) True """ octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.floor(math.pow(10, counter))) counter += 1 num = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"0o{int(octal)}" def main() -> None: """Print octal equivalents of decimal numbers.""" print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") print(decimal_to_octal(8)) # = 10 print("\n65 in octal is:") print(decimal_to_octal(65)) # = 101 print("\n216 in octal is:") print(decimal_to_octal(216)) # = 330 print("\n512 in octal is:") print(decimal_to_octal(512)) # = 1000 print("\n") if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Convert International System of Units (SI) and Binary prefixes """ from enum import Enum from typing import Union class SI_Unit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class Binary_Unit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: Union[str, SI_Unit], unknown_prefix: Union[str, SI_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SI_Unit.giga, SI_Unit.mega) 1000 >>> convert_si_prefix(1, SI_Unit.mega, SI_Unit.giga) 0.001 >>> convert_si_prefix(1, SI_Unit.kilo, SI_Unit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix: SI_Unit = SI_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix: SI_Unit = SI_Unit[unknown_prefix.lower()] unknown_amount = known_amount * (10 ** (known_prefix.value - unknown_prefix.value)) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: Union[str, Binary_Unit], unknown_prefix: Union[str, Binary_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, Binary_Unit.giga, Binary_Unit.mega) 1024 >>> convert_binary_prefix(1, Binary_Unit.mega, Binary_Unit.giga) 0.0009765625 >>> convert_binary_prefix(1, Binary_Unit.kilo, Binary_Unit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix: Binary_Unit = Binary_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix: Binary_Unit = Binary_Unit[unknown_prefix.lower()] unknown_amount = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
""" Convert International System of Units (SI) and Binary prefixes """ from enum import Enum from typing import Union class SI_Unit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class Binary_Unit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: Union[str, SI_Unit], unknown_prefix: Union[str, SI_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SI_Unit.giga, SI_Unit.mega) 1000 >>> convert_si_prefix(1, SI_Unit.mega, SI_Unit.giga) 0.001 >>> convert_si_prefix(1, SI_Unit.kilo, SI_Unit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix = SI_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SI_Unit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: Union[str, Binary_Unit], unknown_prefix: Union[str, Binary_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, Binary_Unit.giga, Binary_Unit.mega) 1024 >>> convert_binary_prefix(1, Binary_Unit.mega, Binary_Unit.giga) 0.0009765625 >>> convert_binary_prefix(1, Binary_Unit.kilo, Binary_Unit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix = Binary_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = Binary_Unit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Conversion of weight units. __author__ = "Anubhav Solanki" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Anubhav Solanki" __email__ = "[email protected]" USAGE : -> Import this file into their respective project. -> Use the function weight_conversion() for conversion of weight units. -> Parameters : -> from_type : From which type you want to convert -> to_type : To which type you want to convert -> value : the value which you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilogram -> Wikipedia reference: https://en.wikipedia.org/wiki/Gram -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre -> Wikipedia reference: https://en.wikipedia.org/wiki/Tonne -> Wikipedia reference: https://en.wikipedia.org/wiki/Long_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Short_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound -> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce -> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat -> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit) """ KILOGRAM_CHART = { "kilogram": 1, "gram": pow(10, 3), "milligram": pow(10, 6), "metric-ton": pow(10, -3), "long-ton": 0.0009842073, "short-ton": 0.0011023122, "pound": 2.2046244202, "ounce": 35.273990723, "carrat": 5000, "atomic-mass-unit": 6.022136652e26, } WEIGHT_TYPE_CHART = { "kilogram": 1, "gram": pow(10, -3), "milligram": pow(10, -6), "metric-ton": pow(10, 3), "long-ton": 1016.04608, "short-ton": 907.184, "pound": 0.453592, "ounce": 0.0283495, "carrat": 0.0002, "atomic-mass-unit": 1.660540199e-27, } def weight_conversion(from_type: str, to_type: str, value: float) -> float: """ Conversion of weight unit with the help of KILOGRAM_CHART "kilogram" : 1, "gram" : pow(10, 3), "milligram" : pow(10, 6), "metric-ton" : pow(10, -3), "long-ton" : 0.0009842073, "short-ton" : 0.0011023122, "pound" : 2.2046244202, "ounce" : 35.273990723, "carrat" : 5000, "atomic-mass-unit" : 6.022136652E+26 >>> weight_conversion("kilogram","kilogram",4) 4 >>> weight_conversion("kilogram","gram",1) 1000 >>> weight_conversion("kilogram","milligram",4) 4000000 >>> weight_conversion("kilogram","metric-ton",4) 0.004 >>> weight_conversion("kilogram","long-ton",3) 0.0029526219 >>> weight_conversion("kilogram","short-ton",1) 0.0011023122 >>> weight_conversion("kilogram","pound",4) 8.8184976808 >>> weight_conversion("kilogram","ounce",4) 141.095962892 >>> weight_conversion("kilogram","carrat",3) 15000 >>> weight_conversion("kilogram","atomic-mass-unit",1) 6.022136652e+26 >>> weight_conversion("gram","kilogram",1) 0.001 >>> weight_conversion("gram","gram",3) 3.0 >>> weight_conversion("gram","milligram",2) 2000.0 >>> weight_conversion("gram","metric-ton",4) 4e-06 >>> weight_conversion("gram","long-ton",3) 2.9526219e-06 >>> weight_conversion("gram","short-ton",3) 3.3069366000000003e-06 >>> weight_conversion("gram","pound",3) 0.0066138732606 >>> weight_conversion("gram","ounce",1) 0.035273990723 >>> weight_conversion("gram","carrat",2) 10.0 >>> weight_conversion("gram","atomic-mass-unit",1) 6.022136652e+23 >>> weight_conversion("milligram","kilogram",1) 1e-06 >>> weight_conversion("milligram","gram",2) 0.002 >>> weight_conversion("milligram","milligram",3) 3.0 >>> weight_conversion("milligram","metric-ton",3) 3e-09 >>> weight_conversion("milligram","long-ton",3) 2.9526219e-09 >>> weight_conversion("milligram","short-ton",1) 1.1023122e-09 >>> weight_conversion("milligram","pound",3) 6.6138732605999995e-06 >>> weight_conversion("milligram","ounce",2) 7.054798144599999e-05 >>> weight_conversion("milligram","carrat",1) 0.005 >>> weight_conversion("milligram","atomic-mass-unit",1) 6.022136652e+20 >>> weight_conversion("metric-ton","kilogram",2) 2000 >>> weight_conversion("metric-ton","gram",2) 2000000 >>> weight_conversion("metric-ton","milligram",3) 3000000000 >>> weight_conversion("metric-ton","metric-ton",2) 2.0 >>> weight_conversion("metric-ton","long-ton",3) 2.9526219 >>> weight_conversion("metric-ton","short-ton",2) 2.2046244 >>> weight_conversion("metric-ton","pound",3) 6613.8732606 >>> weight_conversion("metric-ton","ounce",4) 141095.96289199998 >>> weight_conversion("metric-ton","carrat",4) 20000000 >>> weight_conversion("metric-ton","atomic-mass-unit",1) 6.022136652e+29 >>> weight_conversion("long-ton","kilogram",4) 4064.18432 >>> weight_conversion("long-ton","gram",4) 4064184.32 >>> weight_conversion("long-ton","milligram",3) 3048138240.0 >>> weight_conversion("long-ton","metric-ton",4) 4.06418432 >>> weight_conversion("long-ton","long-ton",3) 2.999999907217152 >>> weight_conversion("long-ton","short-ton",1) 1.119999989746176 >>> weight_conversion("long-ton","pound",3) 6720.000000049448 >>> weight_conversion("long-ton","ounce",1) 35840.000000060514 >>> weight_conversion("long-ton","carrat",4) 20320921.599999998 >>> weight_conversion("long-ton","atomic-mass-unit",4) 2.4475073353955697e+30 >>> weight_conversion("short-ton","kilogram",3) 2721.5519999999997 >>> weight_conversion("short-ton","gram",3) 2721552.0 >>> weight_conversion("short-ton","milligram",1) 907184000.0 >>> weight_conversion("short-ton","metric-ton",4) 3.628736 >>> weight_conversion("short-ton","long-ton",3) 2.6785713457296 >>> weight_conversion("short-ton","short-ton",3) 2.9999999725344 >>> weight_conversion("short-ton","pound",2) 4000.0000000294335 >>> weight_conversion("short-ton","ounce",4) 128000.00000021611 >>> weight_conversion("short-ton","carrat",4) 18143680.0 >>> weight_conversion("short-ton","atomic-mass-unit",1) 5.463186016507968e+29 >>> weight_conversion("pound","kilogram",4) 1.814368 >>> weight_conversion("pound","gram",2) 907.184 >>> weight_conversion("pound","milligram",3) 1360776.0 >>> weight_conversion("pound","metric-ton",3) 0.001360776 >>> weight_conversion("pound","long-ton",2) 0.0008928571152432 >>> weight_conversion("pound","short-ton",1) 0.0004999999954224 >>> weight_conversion("pound","pound",3) 3.0000000000220752 >>> weight_conversion("pound","ounce",1) 16.000000000027015 >>> weight_conversion("pound","carrat",1) 2267.96 >>> weight_conversion("pound","atomic-mass-unit",4) 1.0926372033015936e+27 >>> weight_conversion("ounce","kilogram",3) 0.0850485 >>> weight_conversion("ounce","gram",3) 85.0485 >>> weight_conversion("ounce","milligram",4) 113398.0 >>> weight_conversion("ounce","metric-ton",4) 0.000113398 >>> weight_conversion("ounce","long-ton",4) 0.0001116071394054 >>> weight_conversion("ounce","short-ton",4) 0.0001249999988556 >>> weight_conversion("ounce","pound",1) 0.0625000000004599 >>> weight_conversion("ounce","ounce",2) 2.000000000003377 >>> weight_conversion("ounce","carrat",1) 141.7475 >>> weight_conversion("ounce","atomic-mass-unit",1) 1.70724563015874e+25 >>> weight_conversion("carrat","kilogram",1) 0.0002 >>> weight_conversion("carrat","gram",4) 0.8 >>> weight_conversion("carrat","milligram",2) 400.0 >>> weight_conversion("carrat","metric-ton",2) 4.0000000000000003e-07 >>> weight_conversion("carrat","long-ton",3) 5.9052438e-07 >>> weight_conversion("carrat","short-ton",4) 8.818497600000002e-07 >>> weight_conversion("carrat","pound",1) 0.00044092488404000004 >>> weight_conversion("carrat","ounce",2) 0.0141095962892 >>> weight_conversion("carrat","carrat",4) 4.0 >>> weight_conversion("carrat","atomic-mass-unit",4) 4.8177093216e+23 >>> weight_conversion("atomic-mass-unit","kilogram",4) 6.642160796e-27 >>> weight_conversion("atomic-mass-unit","gram",2) 3.321080398e-24 >>> weight_conversion("atomic-mass-unit","milligram",2) 3.3210803980000002e-21 >>> weight_conversion("atomic-mass-unit","metric-ton",3) 4.9816205970000004e-30 >>> weight_conversion("atomic-mass-unit","long-ton",3) 4.9029473573977584e-30 >>> weight_conversion("atomic-mass-unit","short-ton",1) 1.830433719948128e-30 >>> weight_conversion("atomic-mass-unit","pound",3) 1.0982602420317504e-26 >>> weight_conversion("atomic-mass-unit","ounce",2) 1.1714775914938915e-25 >>> weight_conversion("atomic-mass-unit","carrat",2) 1.660540199e-23 >>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2) 1.999999998903455 """ if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: raise ValueError( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" ) return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] if __name__ == "__main__": import doctest doctest.testmod()
""" Conversion of weight units. __author__ = "Anubhav Solanki" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Anubhav Solanki" __email__ = "[email protected]" USAGE : -> Import this file into their respective project. -> Use the function weight_conversion() for conversion of weight units. -> Parameters : -> from_type : From which type you want to convert -> to_type : To which type you want to convert -> value : the value which you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilogram -> Wikipedia reference: https://en.wikipedia.org/wiki/Gram -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre -> Wikipedia reference: https://en.wikipedia.org/wiki/Tonne -> Wikipedia reference: https://en.wikipedia.org/wiki/Long_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Short_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound -> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce -> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat -> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit) """ KILOGRAM_CHART: dict[str, float] = { "kilogram": 1, "gram": pow(10, 3), "milligram": pow(10, 6), "metric-ton": pow(10, -3), "long-ton": 0.0009842073, "short-ton": 0.0011023122, "pound": 2.2046244202, "ounce": 35.273990723, "carrat": 5000, "atomic-mass-unit": 6.022136652e26, } WEIGHT_TYPE_CHART: dict[str, float] = { "kilogram": 1, "gram": pow(10, -3), "milligram": pow(10, -6), "metric-ton": pow(10, 3), "long-ton": 1016.04608, "short-ton": 907.184, "pound": 0.453592, "ounce": 0.0283495, "carrat": 0.0002, "atomic-mass-unit": 1.660540199e-27, } def weight_conversion(from_type: str, to_type: str, value: float) -> float: """ Conversion of weight unit with the help of KILOGRAM_CHART "kilogram" : 1, "gram" : pow(10, 3), "milligram" : pow(10, 6), "metric-ton" : pow(10, -3), "long-ton" : 0.0009842073, "short-ton" : 0.0011023122, "pound" : 2.2046244202, "ounce" : 35.273990723, "carrat" : 5000, "atomic-mass-unit" : 6.022136652E+26 >>> weight_conversion("kilogram","kilogram",4) 4 >>> weight_conversion("kilogram","gram",1) 1000 >>> weight_conversion("kilogram","milligram",4) 4000000 >>> weight_conversion("kilogram","metric-ton",4) 0.004 >>> weight_conversion("kilogram","long-ton",3) 0.0029526219 >>> weight_conversion("kilogram","short-ton",1) 0.0011023122 >>> weight_conversion("kilogram","pound",4) 8.8184976808 >>> weight_conversion("kilogram","ounce",4) 141.095962892 >>> weight_conversion("kilogram","carrat",3) 15000 >>> weight_conversion("kilogram","atomic-mass-unit",1) 6.022136652e+26 >>> weight_conversion("gram","kilogram",1) 0.001 >>> weight_conversion("gram","gram",3) 3.0 >>> weight_conversion("gram","milligram",2) 2000.0 >>> weight_conversion("gram","metric-ton",4) 4e-06 >>> weight_conversion("gram","long-ton",3) 2.9526219e-06 >>> weight_conversion("gram","short-ton",3) 3.3069366000000003e-06 >>> weight_conversion("gram","pound",3) 0.0066138732606 >>> weight_conversion("gram","ounce",1) 0.035273990723 >>> weight_conversion("gram","carrat",2) 10.0 >>> weight_conversion("gram","atomic-mass-unit",1) 6.022136652e+23 >>> weight_conversion("milligram","kilogram",1) 1e-06 >>> weight_conversion("milligram","gram",2) 0.002 >>> weight_conversion("milligram","milligram",3) 3.0 >>> weight_conversion("milligram","metric-ton",3) 3e-09 >>> weight_conversion("milligram","long-ton",3) 2.9526219e-09 >>> weight_conversion("milligram","short-ton",1) 1.1023122e-09 >>> weight_conversion("milligram","pound",3) 6.6138732605999995e-06 >>> weight_conversion("milligram","ounce",2) 7.054798144599999e-05 >>> weight_conversion("milligram","carrat",1) 0.005 >>> weight_conversion("milligram","atomic-mass-unit",1) 6.022136652e+20 >>> weight_conversion("metric-ton","kilogram",2) 2000 >>> weight_conversion("metric-ton","gram",2) 2000000 >>> weight_conversion("metric-ton","milligram",3) 3000000000 >>> weight_conversion("metric-ton","metric-ton",2) 2.0 >>> weight_conversion("metric-ton","long-ton",3) 2.9526219 >>> weight_conversion("metric-ton","short-ton",2) 2.2046244 >>> weight_conversion("metric-ton","pound",3) 6613.8732606 >>> weight_conversion("metric-ton","ounce",4) 141095.96289199998 >>> weight_conversion("metric-ton","carrat",4) 20000000 >>> weight_conversion("metric-ton","atomic-mass-unit",1) 6.022136652e+29 >>> weight_conversion("long-ton","kilogram",4) 4064.18432 >>> weight_conversion("long-ton","gram",4) 4064184.32 >>> weight_conversion("long-ton","milligram",3) 3048138240.0 >>> weight_conversion("long-ton","metric-ton",4) 4.06418432 >>> weight_conversion("long-ton","long-ton",3) 2.999999907217152 >>> weight_conversion("long-ton","short-ton",1) 1.119999989746176 >>> weight_conversion("long-ton","pound",3) 6720.000000049448 >>> weight_conversion("long-ton","ounce",1) 35840.000000060514 >>> weight_conversion("long-ton","carrat",4) 20320921.599999998 >>> weight_conversion("long-ton","atomic-mass-unit",4) 2.4475073353955697e+30 >>> weight_conversion("short-ton","kilogram",3) 2721.5519999999997 >>> weight_conversion("short-ton","gram",3) 2721552.0 >>> weight_conversion("short-ton","milligram",1) 907184000.0 >>> weight_conversion("short-ton","metric-ton",4) 3.628736 >>> weight_conversion("short-ton","long-ton",3) 2.6785713457296 >>> weight_conversion("short-ton","short-ton",3) 2.9999999725344 >>> weight_conversion("short-ton","pound",2) 4000.0000000294335 >>> weight_conversion("short-ton","ounce",4) 128000.00000021611 >>> weight_conversion("short-ton","carrat",4) 18143680.0 >>> weight_conversion("short-ton","atomic-mass-unit",1) 5.463186016507968e+29 >>> weight_conversion("pound","kilogram",4) 1.814368 >>> weight_conversion("pound","gram",2) 907.184 >>> weight_conversion("pound","milligram",3) 1360776.0 >>> weight_conversion("pound","metric-ton",3) 0.001360776 >>> weight_conversion("pound","long-ton",2) 0.0008928571152432 >>> weight_conversion("pound","short-ton",1) 0.0004999999954224 >>> weight_conversion("pound","pound",3) 3.0000000000220752 >>> weight_conversion("pound","ounce",1) 16.000000000027015 >>> weight_conversion("pound","carrat",1) 2267.96 >>> weight_conversion("pound","atomic-mass-unit",4) 1.0926372033015936e+27 >>> weight_conversion("ounce","kilogram",3) 0.0850485 >>> weight_conversion("ounce","gram",3) 85.0485 >>> weight_conversion("ounce","milligram",4) 113398.0 >>> weight_conversion("ounce","metric-ton",4) 0.000113398 >>> weight_conversion("ounce","long-ton",4) 0.0001116071394054 >>> weight_conversion("ounce","short-ton",4) 0.0001249999988556 >>> weight_conversion("ounce","pound",1) 0.0625000000004599 >>> weight_conversion("ounce","ounce",2) 2.000000000003377 >>> weight_conversion("ounce","carrat",1) 141.7475 >>> weight_conversion("ounce","atomic-mass-unit",1) 1.70724563015874e+25 >>> weight_conversion("carrat","kilogram",1) 0.0002 >>> weight_conversion("carrat","gram",4) 0.8 >>> weight_conversion("carrat","milligram",2) 400.0 >>> weight_conversion("carrat","metric-ton",2) 4.0000000000000003e-07 >>> weight_conversion("carrat","long-ton",3) 5.9052438e-07 >>> weight_conversion("carrat","short-ton",4) 8.818497600000002e-07 >>> weight_conversion("carrat","pound",1) 0.00044092488404000004 >>> weight_conversion("carrat","ounce",2) 0.0141095962892 >>> weight_conversion("carrat","carrat",4) 4.0 >>> weight_conversion("carrat","atomic-mass-unit",4) 4.8177093216e+23 >>> weight_conversion("atomic-mass-unit","kilogram",4) 6.642160796e-27 >>> weight_conversion("atomic-mass-unit","gram",2) 3.321080398e-24 >>> weight_conversion("atomic-mass-unit","milligram",2) 3.3210803980000002e-21 >>> weight_conversion("atomic-mass-unit","metric-ton",3) 4.9816205970000004e-30 >>> weight_conversion("atomic-mass-unit","long-ton",3) 4.9029473573977584e-30 >>> weight_conversion("atomic-mass-unit","short-ton",1) 1.830433719948128e-30 >>> weight_conversion("atomic-mass-unit","pound",3) 1.0982602420317504e-26 >>> weight_conversion("atomic-mass-unit","ounce",2) 1.1714775914938915e-25 >>> weight_conversion("atomic-mass-unit","carrat",2) 1.660540199e-23 >>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2) 1.999999998903455 """ if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: raise ValueError( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" ) return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Test cases: Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Enter the change you want to make: 18745 Following is minimal change for 18745 : 2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5 Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: 0 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: -98 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:5 1 5 100 500 1000 Enter the change you want to make: 456 Following is minimal change for 456 : 100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1 """ def find_minimum_change(denominations: list[int], value: int) -> list[int]: """ Find the minimum change from the given denominations and value >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745) [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987) [500, 100, 100, 100, 100, 50, 20, 10, 5, 2] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0) [] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98) [] >>> find_minimum_change([1, 5, 100, 500, 1000], 456) [100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1] """ total_value = int(value) # Initialize Result answer = [] # Traverse through all denomination for denomination in reversed(denominations): # Find denominations while int(total_value) >= int(denomination): total_value -= int(denomination) answer.append(denomination) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": denominations = list() value = 0 if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): n = int(input("Enter the number of denominations you want to add: ").strip()) for i in range(0, n): denominations.append(int(input(f"Denomination {i}: ").strip())) value = input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000] value = input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f"Following is minimal change for {value}: ") answer = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
""" Test cases: Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Enter the change you want to make: 18745 Following is minimal change for 18745 : 2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5 Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: 0 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: -98 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:5 1 5 100 500 1000 Enter the change you want to make: 456 Following is minimal change for 456 : 100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1 """ def find_minimum_change(denominations: list[int], value: int) -> list[int]: """ Find the minimum change from the given denominations and value >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745) [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987) [500, 100, 100, 100, 100, 50, 20, 10, 5, 2] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0) [] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98) [] >>> find_minimum_change([1, 5, 100, 500, 1000], 456) [100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1] """ total_value = int(value) # Initialize Result answer = [] # Traverse through all denomination for denomination in reversed(denominations): # Find denominations while int(total_value) >= int(denomination): total_value -= int(denomination) answer.append(denomination) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": denominations = list() value = 0 if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): n = int(input("Enter the number of denominations you want to add: ").strip()) for i in range(0, n): denominations.append(int(input(f"Denomination {i}: ").strip())) value = input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000] value = input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f"Following is minimal change for {value}: ") answer = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
from math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(lambda f: os.remove(f), self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(lambda f: os.remove(f), self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a and c(dABCd) -> remove d (ABC) """ def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
""" https://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a and c(dABCd) -> remove d (ABC) """ def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 from typing import Callable, Union def line_length( fnc: Callable[[Union[int, float]], Union[int, float]], x_start: Union[int, float], x_end: Union[int, float], steps: int = 100, ) -> float: """ Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases accuracy :return: a float representing the length of the curve >>> def f(x): ... return x >>> f"{line_length(f, 0, 1, 10):.6f}" '1.414214' >>> def f(x): ... return 1 >>> f"{line_length(f, -5.5, 4.5):.6f}" '10.000000' >>> def f(x): ... return math.sin(5 * x) + math.cos(10 * x) + x * x/10 >>> f"{line_length(f, 0.0, 10.0, 10000):.6f}" '69.534930' """ x1 = x_start fx1 = fnc(x_start) length = 0.0 for i in range(steps): # Approximates curve as a sequence of linear lines and sums their length x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) length += math.hypot(x2 - x1, fx2 - fx1) # Increment step x1 = x2 fx1 = fx2 return length if __name__ == "__main__": def f(x): return math.sin(10 * x) print("f(x) = sin(10 * x)") print("The length of the curve from x = -10 to x = 10 is:") i = 10 while i <= 100000: print(f"With {i} steps: {line_length(f, -10, 10, i)}") i *= 10
import math from typing import Callable, Union def line_length( fnc: Callable[[Union[int, float]], Union[int, float]], x_start: Union[int, float], x_end: Union[int, float], steps: int = 100, ) -> float: """ Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases accuracy :return: a float representing the length of the curve >>> def f(x): ... return x >>> f"{line_length(f, 0, 1, 10):.6f}" '1.414214' >>> def f(x): ... return 1 >>> f"{line_length(f, -5.5, 4.5):.6f}" '10.000000' >>> def f(x): ... return math.sin(5 * x) + math.cos(10 * x) + x * x/10 >>> f"{line_length(f, 0.0, 10.0, 10000):.6f}" '69.534930' """ x1 = x_start fx1 = fnc(x_start) length = 0.0 for i in range(steps): # Approximates curve as a sequence of linear lines and sums their length x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) length += math.hypot(x2 - x1, fx2 - fx1) # Increment step x1 = x2 fx1 = fx2 return length if __name__ == "__main__": def f(x): return math.sin(10 * x) print("f(x) = sin(10 * x)") print("The length of the curve from x = -10 to x = 10 is:") i = 10 while i <= 100000: print(f"With {i} steps: {line_length(f, -10, 10, i)}") i *= 10
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 Any class Node: def __init__(self, data: Any): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() # adding nodes def push(self, new_data: Any): new_node = Node(new_data) new_node.next = self.head self.head = new_node # swapping nodes def swap_nodes(self, node_data_1, node_data_2): if node_data_1 == node_data_2: return else: node_1 = self.head while node_1 is not None and node_1.data != node_data_1: node_1 = node_1.next node_2 = self.head while node_2 is not None and node_2.data != node_data_2: node_2 = node_2.next if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": ll = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("After swapping") ll.print_list()
from typing import Any class Node: def __init__(self, data: Any): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() # adding nodes def push(self, new_data: Any): new_node = Node(new_data) new_node.next = self.head self.head = new_node # swapping nodes def swap_nodes(self, node_data_1, node_data_2): if node_data_1 == node_data_2: return else: node_1 = self.head while node_1 is not None and node_1.data != node_data_1: node_1 = node_1.next node_2 = self.head while node_2 is not None and node_2.data != node_data_2: node_2 = node_2.next if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": ll = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("After swapping") ll.print_list()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 merge sort algorithm For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ def merge_sort(collection: list) -> list: """Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ def merge(left: list, right: list) -> list: """merge left and right :param left: left collection :param right: right collection :return: merge result """ def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0) yield from left yield from right return list(_merge()) if len(collection) <= 1: return collection mid = len(collection) // 2 return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:])) 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(*merge_sort(unsorted), sep=",")
""" This is a pure Python implementation of the merge sort algorithm For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ def merge_sort(collection: list) -> list: """Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ def merge(left: list, right: list) -> list: """merge left and right :param left: left collection :param right: right collection :return: merge result """ def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0) yield from left yield from right return list(_merge()) if len(collection) <= 1: return collection mid = len(collection) // 2 return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:])) 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(*merge_sort(unsorted), sep=",")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from typing import List def prime_sieve(limit: int) -> List[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit ** 0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from typing import List def prime_sieve(limit: int) -> List[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit ** 0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 Mandelbrot set is the set of complex numbers "c" for which the series "z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a complex number "c" is a member of the Mandelbrot set if, when starting with "z_0 = 0" and applying the iteration repeatedly, the absolute value of "z_n" remains bounded for all "n > 0". Complex numbers can be written as "a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i" is the imaginary component, usually drawn on the y-axis. Most visualizations of the Mandelbrot set use a color-coding to indicate after how many steps in the series the numbers outside the set diverge. Images of the Mandelbrot set exhibit an elaborate and infinitely complicated boundary that reveals progressively ever-finer recursive detail at increasing magnifications, making the boundary of the Mandelbrot set a fractal curve. (description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set ) (see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set ) """ import colorsys from PIL import Image # type: ignore def get_distance(x: float, y: float, max_step: int) -> float: """ Return the relative distance (= step/max_step) after which the complex number constituted by this x-y-pair diverges. Members of the Mandelbrot set do not diverge so their distance is 1. >>> get_distance(0, 0, 50) 1.0 >>> get_distance(0.5, 0.5, 50) 0.061224489795918366 >>> get_distance(2, 0, 50) 0.0 """ a = x b = y for step in range(max_step): a_new = a * a - b * b + x b = 2 * a * b + y a = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def get_black_and_white_rgb(distance: float) -> tuple: """ Black&white color-coding that ignores the relative distance. The Mandelbrot set is black, everything else is white. >>> get_black_and_white_rgb(0) (255, 255, 255) >>> get_black_and_white_rgb(0.5) (255, 255, 255) >>> get_black_and_white_rgb(1) (0, 0, 0) """ if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def get_color_coded_rgb(distance: float) -> tuple: """ Color-coding taking the relative distance into account. The Mandelbrot set is black. >>> get_color_coded_rgb(0) (255, 0, 0) >>> get_color_coded_rgb(0.5) (0, 255, 255) >>> get_color_coded_rgb(1) (0, 0, 0) """ if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1)) def get_image( image_width: int = 800, image_height: int = 600, figure_center_x: float = -0.6, figure_center_y: float = 0, figure_width: float = 3.2, max_step: int = 50, use_distance_color_coding: bool = True, ) -> Image.Image: """ Function to generate the image of the Mandelbrot set. Two types of coordinates are used: image-coordinates that refer to the pixels and figure-coordinates that refer to the complex numbers inside and outside the Mandelbrot set. The figure-coordinates in the arguments of this function determine which section of the Mandelbrot set is viewed. The main area of the Mandelbrot set is roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates. >>> get_image().load()[0,0] (255, 0, 0) >>> get_image(use_distance_color_coding = False).load()[0,0] (255, 255, 255) """ img = Image.new("RGB", (image_width, image_height)) pixels = img.load() # loop through the image-coordinates for image_x in range(image_width): for image_y in range(image_height): # determine the figure-coordinates based on the image-coordinates figure_height = figure_width / image_width * image_height figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height distance = get_distance(figure_x, figure_y, max_step) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: pixels[image_x, image_y] = get_color_coded_rgb(distance) else: pixels[image_x, image_y] = get_black_and_white_rgb(distance) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure img = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
""" The Mandelbrot set is the set of complex numbers "c" for which the series "z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a complex number "c" is a member of the Mandelbrot set if, when starting with "z_0 = 0" and applying the iteration repeatedly, the absolute value of "z_n" remains bounded for all "n > 0". Complex numbers can be written as "a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i" is the imaginary component, usually drawn on the y-axis. Most visualizations of the Mandelbrot set use a color-coding to indicate after how many steps in the series the numbers outside the set diverge. Images of the Mandelbrot set exhibit an elaborate and infinitely complicated boundary that reveals progressively ever-finer recursive detail at increasing magnifications, making the boundary of the Mandelbrot set a fractal curve. (description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set ) (see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set ) """ import colorsys from PIL import Image # type: ignore def get_distance(x: float, y: float, max_step: int) -> float: """ Return the relative distance (= step/max_step) after which the complex number constituted by this x-y-pair diverges. Members of the Mandelbrot set do not diverge so their distance is 1. >>> get_distance(0, 0, 50) 1.0 >>> get_distance(0.5, 0.5, 50) 0.061224489795918366 >>> get_distance(2, 0, 50) 0.0 """ a = x b = y for step in range(max_step): a_new = a * a - b * b + x b = 2 * a * b + y a = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def get_black_and_white_rgb(distance: float) -> tuple: """ Black&white color-coding that ignores the relative distance. The Mandelbrot set is black, everything else is white. >>> get_black_and_white_rgb(0) (255, 255, 255) >>> get_black_and_white_rgb(0.5) (255, 255, 255) >>> get_black_and_white_rgb(1) (0, 0, 0) """ if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def get_color_coded_rgb(distance: float) -> tuple: """ Color-coding taking the relative distance into account. The Mandelbrot set is black. >>> get_color_coded_rgb(0) (255, 0, 0) >>> get_color_coded_rgb(0.5) (0, 255, 255) >>> get_color_coded_rgb(1) (0, 0, 0) """ if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1)) def get_image( image_width: int = 800, image_height: int = 600, figure_center_x: float = -0.6, figure_center_y: float = 0, figure_width: float = 3.2, max_step: int = 50, use_distance_color_coding: bool = True, ) -> Image.Image: """ Function to generate the image of the Mandelbrot set. Two types of coordinates are used: image-coordinates that refer to the pixels and figure-coordinates that refer to the complex numbers inside and outside the Mandelbrot set. The figure-coordinates in the arguments of this function determine which section of the Mandelbrot set is viewed. The main area of the Mandelbrot set is roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates. >>> get_image().load()[0,0] (255, 0, 0) >>> get_image(use_distance_color_coding = False).load()[0,0] (255, 255, 255) """ img = Image.new("RGB", (image_width, image_height)) pixels = img.load() # loop through the image-coordinates for image_x in range(image_width): for image_y in range(image_height): # determine the figure-coordinates based on the image-coordinates figure_height = figure_width / image_width * image_height figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height distance = get_distance(figure_x, figure_y, max_step) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: pixels[image_x, image_y] = get_color_coded_rgb(distance) else: pixels[image_x, image_y] = get_black_and_white_rgb(distance) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure img = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: string_rep.append(f"{temp.data}") temp = temp.next return "->".join(string_rep) def make_linked_list(elements_list: List): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List. >>> make_linked_list([]) Traceback (most recent call last): ... Exception: The Elements List is empty >>> make_linked_list([7]) 7 >>> make_linked_list(['abc']) abc >>> make_linked_list([7, 25]) 7->25 """ if not elements_list: raise Exception("The Elements List is empty") current = head = Node(elements_list[0]) for i in range(1, len(elements_list)): current.next = Node(elements_list[i]) current = current.next return head def print_reverse(head_node: Node) -> None: """Prints the elements of the given Linked List in reverse order >>> print_reverse([]) >>> linked_list = make_linked_list([69, 88, 73]) >>> print_reverse(linked_list) 73 88 69 """ if head_node is not None and isinstance(head_node, Node): print_reverse(head_node.next) print(head_node.data) def main(): from doctest import testmod testmod() linked_list = make_linked_list([14, 52, 14, 12, 43]) print("Linked List:") print(linked_list) print("Elements in Reverse:") print_reverse(linked_list) if __name__ == "__main__": main()
from typing import List class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: string_rep.append(f"{temp.data}") temp = temp.next return "->".join(string_rep) def make_linked_list(elements_list: List): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List. >>> make_linked_list([]) Traceback (most recent call last): ... Exception: The Elements List is empty >>> make_linked_list([7]) 7 >>> make_linked_list(['abc']) abc >>> make_linked_list([7, 25]) 7->25 """ if not elements_list: raise Exception("The Elements List is empty") current = head = Node(elements_list[0]) for i in range(1, len(elements_list)): current.next = Node(elements_list[i]) current = current.next return head def print_reverse(head_node: Node) -> None: """Prints the elements of the given Linked List in reverse order >>> print_reverse([]) >>> linked_list = make_linked_list([69, 88, 73]) >>> print_reverse(linked_list) 73 88 69 """ if head_node is not None and isinstance(head_node, Node): print_reverse(head_node.next) print(head_node.data) def main(): from doctest import testmod testmod() linked_list = make_linked_list([14, 52, 14, 12, 43]) print("Linked List:") print(linked_list) print("Elements in Reverse:") print_reverse(linked_list) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
class FlowNetwork: def __init__(self, graph, sources, sinks): self.sourceIndex = None self.sinkIndex = None self.graph = graph self._normalizeGraph(sources, sinks) self.verticesCount = len(graph) self.maximumFlowAlgorithm = None # make only one source and one sink def _normalizeGraph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.sourceIndex = sources[0] self.sinkIndex = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: maxInputFlow = 0 for i in sources: maxInputFlow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = maxInputFlow self.sourceIndex = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = maxInputFlow self.sinkIndex = size - 1 def findMaximumFlow(self): if self.maximumFlowAlgorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.sourceIndex is None or self.sinkIndex is None: return 0 self.maximumFlowAlgorithm.execute() return self.maximumFlowAlgorithm.getMaximumFlow() def setMaximumFlowAlgorithm(self, Algorithm): self.maximumFlowAlgorithm = Algorithm(self) class FlowNetworkAlgorithmExecutor: def __init__(self, flowNetwork): self.flowNetwork = flowNetwork self.verticesCount = flowNetwork.verticesCount self.sourceIndex = flowNetwork.sourceIndex self.sinkIndex = flowNetwork.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flowNetwork.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flowNetwork): super().__init__(flowNetwork) # use this to save your result self.maximumFlow = -1 def getMaximumFlow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximumFlow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flowNetwork): super().__init__(flowNetwork) self.preflow = [[0] * self.verticesCount for i in range(self.verticesCount)] self.heights = [0] * self.verticesCount self.excesses = [0] * self.verticesCount def _algorithm(self): self.heights[self.sourceIndex] = self.verticesCount # push some substance to graph for nextVertexIndex, bandwidth in enumerate(self.graph[self.sourceIndex]): self.preflow[self.sourceIndex][nextVertexIndex] += bandwidth self.preflow[nextVertexIndex][self.sourceIndex] -= bandwidth self.excesses[nextVertexIndex] += bandwidth # Relabel-to-front selection rule verticesList = [ i for i in range(self.verticesCount) if i != self.sourceIndex and i != self.sinkIndex ] # move through list i = 0 while i < len(verticesList): vertexIndex = verticesList[i] previousHeight = self.heights[vertexIndex] self.processVertex(vertexIndex) if self.heights[vertexIndex] > previousHeight: # if it was relabeled, swap elements # and start from 0 index verticesList.insert(0, verticesList.pop(i)) i = 0 else: i += 1 self.maximumFlow = sum(self.preflow[self.sourceIndex]) def processVertex(self, vertexIndex): while self.excesses[vertexIndex] > 0: for neighbourIndex in range(self.verticesCount): # if it's neighbour and current vertex is higher if ( self.graph[vertexIndex][neighbourIndex] - self.preflow[vertexIndex][neighbourIndex] > 0 and self.heights[vertexIndex] > self.heights[neighbourIndex] ): self.push(vertexIndex, neighbourIndex) self.relabel(vertexIndex) def push(self, fromIndex, toIndex): preflowDelta = min( self.excesses[fromIndex], self.graph[fromIndex][toIndex] - self.preflow[fromIndex][toIndex], ) self.preflow[fromIndex][toIndex] += preflowDelta self.preflow[toIndex][fromIndex] -= preflowDelta self.excesses[fromIndex] -= preflowDelta self.excesses[toIndex] += preflowDelta def relabel(self, vertexIndex): minHeight = None for toIndex in range(self.verticesCount): if ( self.graph[vertexIndex][toIndex] - self.preflow[vertexIndex][toIndex] > 0 ): if minHeight is None or self.heights[toIndex] < minHeight: minHeight = self.heights[toIndex] if minHeight is not None: self.heights[vertexIndex] = minHeight + 1 if __name__ == "__main__": entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flowNetwork = FlowNetwork(graph, entrances, exits) # set algorithm flowNetwork.setMaximumFlowAlgorithm(PushRelabelExecutor) # and calculate maximumFlow = flowNetwork.findMaximumFlow() print(f"maximum flow is {maximumFlow}")
class FlowNetwork: def __init__(self, graph, sources, sinks): self.sourceIndex = None self.sinkIndex = None self.graph = graph self._normalizeGraph(sources, sinks) self.verticesCount = len(graph) self.maximumFlowAlgorithm = None # make only one source and one sink def _normalizeGraph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.sourceIndex = sources[0] self.sinkIndex = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: maxInputFlow = 0 for i in sources: maxInputFlow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = maxInputFlow self.sourceIndex = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = maxInputFlow self.sinkIndex = size - 1 def findMaximumFlow(self): if self.maximumFlowAlgorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.sourceIndex is None or self.sinkIndex is None: return 0 self.maximumFlowAlgorithm.execute() return self.maximumFlowAlgorithm.getMaximumFlow() def setMaximumFlowAlgorithm(self, Algorithm): self.maximumFlowAlgorithm = Algorithm(self) class FlowNetworkAlgorithmExecutor: def __init__(self, flowNetwork): self.flowNetwork = flowNetwork self.verticesCount = flowNetwork.verticesCount self.sourceIndex = flowNetwork.sourceIndex self.sinkIndex = flowNetwork.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flowNetwork.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flowNetwork): super().__init__(flowNetwork) # use this to save your result self.maximumFlow = -1 def getMaximumFlow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximumFlow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flowNetwork): super().__init__(flowNetwork) self.preflow = [[0] * self.verticesCount for i in range(self.verticesCount)] self.heights = [0] * self.verticesCount self.excesses = [0] * self.verticesCount def _algorithm(self): self.heights[self.sourceIndex] = self.verticesCount # push some substance to graph for nextVertexIndex, bandwidth in enumerate(self.graph[self.sourceIndex]): self.preflow[self.sourceIndex][nextVertexIndex] += bandwidth self.preflow[nextVertexIndex][self.sourceIndex] -= bandwidth self.excesses[nextVertexIndex] += bandwidth # Relabel-to-front selection rule verticesList = [ i for i in range(self.verticesCount) if i != self.sourceIndex and i != self.sinkIndex ] # move through list i = 0 while i < len(verticesList): vertexIndex = verticesList[i] previousHeight = self.heights[vertexIndex] self.processVertex(vertexIndex) if self.heights[vertexIndex] > previousHeight: # if it was relabeled, swap elements # and start from 0 index verticesList.insert(0, verticesList.pop(i)) i = 0 else: i += 1 self.maximumFlow = sum(self.preflow[self.sourceIndex]) def processVertex(self, vertexIndex): while self.excesses[vertexIndex] > 0: for neighbourIndex in range(self.verticesCount): # if it's neighbour and current vertex is higher if ( self.graph[vertexIndex][neighbourIndex] - self.preflow[vertexIndex][neighbourIndex] > 0 and self.heights[vertexIndex] > self.heights[neighbourIndex] ): self.push(vertexIndex, neighbourIndex) self.relabel(vertexIndex) def push(self, fromIndex, toIndex): preflowDelta = min( self.excesses[fromIndex], self.graph[fromIndex][toIndex] - self.preflow[fromIndex][toIndex], ) self.preflow[fromIndex][toIndex] += preflowDelta self.preflow[toIndex][fromIndex] -= preflowDelta self.excesses[fromIndex] -= preflowDelta self.excesses[toIndex] += preflowDelta def relabel(self, vertexIndex): minHeight = None for toIndex in range(self.verticesCount): if ( self.graph[vertexIndex][toIndex] - self.preflow[vertexIndex][toIndex] > 0 ): if minHeight is None or self.heights[toIndex] < minHeight: minHeight = self.heights[toIndex] if minHeight is not None: self.heights[vertexIndex] = minHeight + 1 if __name__ == "__main__": entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flowNetwork = FlowNetwork(graph, entrances, exits) # set algorithm flowNetwork.setMaximumFlowAlgorithm(PushRelabelExecutor) # and calculate maximumFlow = flowNetwork.findMaximumFlow() print(f"maximum flow is {maximumFlow}")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001/010/100/000/101 b source: http://www.cse.yorku.ca/~oz/hash.html """ def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash = 5381 for x in s: hash = ((hash << 5) + hash) + ord(x) return hash & 0xFFFFFFFF
""" This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001/010/100/000/101 b source: http://www.cse.yorku.ca/~oz/hash.html """ def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash = 5381 for x in s: hash = ((hash << 5) + hash) + ord(x) return hash & 0xFFFFFFFF
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
""" Convert between different units of temperature """ def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
""" Convert between different units of temperature """ def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 """ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ from __future__ import annotations import sys def fibonacci(n: int) -> int: """ return F(n) >>> [fibonacci(i) for i in range(13)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] """ if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] # returns (F(n), F(n-1)) def _fib(n: int) -> tuple[int, int]: if n == 0: # (F(0), F(1)) return (0, 1) # F(2n) = F(n)[2F(n+1) − F(n)] # F(2n+1) = F(n+1)^2+F(n)^2 a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
#!/usr/bin/env python3 """ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ from __future__ import annotations import sys def fibonacci(n: int) -> int: """ return F(n) >>> [fibonacci(i) for i in range(13)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] """ if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] # returns (F(n), F(n-1)) def _fib(n: int) -> tuple[int, int]: if n == 0: # (F(0), F(1)) return (0, 1) # F(2n) = F(n)[2F(n+1) − F(n)] # F(2n+1) = F(n+1)^2+F(n)^2 a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection X = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(X_train, y_train) # to see how good the model fit the data training_score = model.score(X_train, y_train).round(3) test_score = model.score(X_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(X_test) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred)) # Explained variance score: 1 is perfect prediction print("Test Variance score: %.2f" % r2_score(y_test, y_pred)) # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection X = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(X_train, y_train) # to see how good the model fit the data training_score = model.score(X_train, y_train).round(3) test_score = model.score(X_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(X_test) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred)) # Explained variance score: 1 is perfect prediction print("Test Variance score: %.2f" % r2_score(y_test, y_pred)) # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 string from math import log10 """ tf-idf Wikipedia: https://en.wikipedia.org/wiki/Tf%E2%80%93idf tf-idf and other word frequency algorithms are often used as a weighting factor in information retrieval and text mining. 83% of text-based recommender systems use tf-idf for term weighting. In Layman's terms, tf-idf is a statistic intended to reflect how important a word is to a document in a corpus (a collection of documents) Here I've implemented several word frequency algorithms that are commonly used in information retrieval: Term Frequency, Document Frequency, and TF-IDF (Term-Frequency*Inverse-Document-Frequency) are included. Term Frequency is a statistical function that returns a number representing how frequently an expression occurs in a document. This indicates how significant a particular term is in a given document. Document Frequency is a statistical function that returns an integer representing the number of documents in a corpus that a term occurs in (where the max number returned would be the number of documents in the corpus). Inverse Document Frequency is mathematically written as log10(N/df), where N is the number of documents in your corpus and df is the Document Frequency. If df is 0, a ZeroDivisionError will be thrown. Term-Frequency*Inverse-Document-Frequency is a measure of the originality of a term. It is mathematically written as tf*log10(N/df). It compares the number of times a term appears in a document with the number of documents the term appears in. If df is 0, a ZeroDivisionError will be thrown. """ def term_frequency(term: str, document: str) -> int: """ Return the number of times a term occurs within a given document. @params: term, the term to search a document for, and document, the document to search within @returns: an integer representing the number of times a term is found within the document @examples: >>> term_frequency("to", "To be, or not to be") 2 """ # strip all punctuation and newlines and replace it with '' document_without_punctuation = document.translate( str.maketrans("", "", string.punctuation) ).replace("\n", "") tokenize_document = document_without_punctuation.split(" ") # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()]) def document_frequency(term: str, corpus: str) -> tuple[int, int]: """ Calculate the number of documents in a corpus that contain a given term @params : term, the term to search each document for, and corpus, a collection of documents. Each document should be separated by a newline. @returns : the number of documents in the corpus that contain the term you are searching for and the number of documents in the corpus @examples : >>> document_frequency("first", "This is the first document in the corpus.\\nThIs\ is the second document in the corpus.\\nTHIS is \ the third document in the corpus.") (1, 3) """ corpus_without_punctuation = corpus.lower().translate( str.maketrans("", "", string.punctuation) ) # strip all punctuation and replace it with '' docs = corpus_without_punctuation.split("\n") term = term.lower() return (len([doc for doc in docs if term in doc]), len(docs)) def inverse_document_frequency(df: int, N: int, smoothing=False) -> float: """ Return an integer denoting the importance of a word. This measure of importance is calculated by log10(N/df), where N is the number of documents and df is the Document Frequency. @params : df, the Document Frequency, N, the number of documents in the corpus and smoothing, if True return the idf-smooth @returns : log10(N/df) or 1+log10(N/1+df) @examples : >>> inverse_document_frequency(3, 0) Traceback (most recent call last): ... ValueError: log10(0) is undefined. >>> inverse_document_frequency(1, 3) 0.477 >>> inverse_document_frequency(0, 3) Traceback (most recent call last): ... ZeroDivisionError: df must be > 0 >>> inverse_document_frequency(0, 3,True) 1.477 """ if smoothing: if N == 0: raise ValueError("log10(0) is undefined.") return round(1 + log10(N / (1 + df)), 3) if df == 0: raise ZeroDivisionError("df must be > 0") elif N == 0: raise ValueError("log10(0) is undefined.") return round(log10(N / df), 3) def tf_idf(tf: int, idf: int) -> float: """ Combine the term frequency and inverse document frequency functions to calculate the originality of a term. This 'originality' is calculated by multiplying the term frequency and the inverse document frequency : tf-idf = TF * IDF @params : tf, the term frequency, and idf, the inverse document frequency @examples : >>> tf_idf(2, 0.477) 0.954 """ return round(tf * idf, 3)
import string from math import log10 """ tf-idf Wikipedia: https://en.wikipedia.org/wiki/Tf%E2%80%93idf tf-idf and other word frequency algorithms are often used as a weighting factor in information retrieval and text mining. 83% of text-based recommender systems use tf-idf for term weighting. In Layman's terms, tf-idf is a statistic intended to reflect how important a word is to a document in a corpus (a collection of documents) Here I've implemented several word frequency algorithms that are commonly used in information retrieval: Term Frequency, Document Frequency, and TF-IDF (Term-Frequency*Inverse-Document-Frequency) are included. Term Frequency is a statistical function that returns a number representing how frequently an expression occurs in a document. This indicates how significant a particular term is in a given document. Document Frequency is a statistical function that returns an integer representing the number of documents in a corpus that a term occurs in (where the max number returned would be the number of documents in the corpus). Inverse Document Frequency is mathematically written as log10(N/df), where N is the number of documents in your corpus and df is the Document Frequency. If df is 0, a ZeroDivisionError will be thrown. Term-Frequency*Inverse-Document-Frequency is a measure of the originality of a term. It is mathematically written as tf*log10(N/df). It compares the number of times a term appears in a document with the number of documents the term appears in. If df is 0, a ZeroDivisionError will be thrown. """ def term_frequency(term: str, document: str) -> int: """ Return the number of times a term occurs within a given document. @params: term, the term to search a document for, and document, the document to search within @returns: an integer representing the number of times a term is found within the document @examples: >>> term_frequency("to", "To be, or not to be") 2 """ # strip all punctuation and newlines and replace it with '' document_without_punctuation = document.translate( str.maketrans("", "", string.punctuation) ).replace("\n", "") tokenize_document = document_without_punctuation.split(" ") # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()]) def document_frequency(term: str, corpus: str) -> tuple[int, int]: """ Calculate the number of documents in a corpus that contain a given term @params : term, the term to search each document for, and corpus, a collection of documents. Each document should be separated by a newline. @returns : the number of documents in the corpus that contain the term you are searching for and the number of documents in the corpus @examples : >>> document_frequency("first", "This is the first document in the corpus.\\nThIs\ is the second document in the corpus.\\nTHIS is \ the third document in the corpus.") (1, 3) """ corpus_without_punctuation = corpus.lower().translate( str.maketrans("", "", string.punctuation) ) # strip all punctuation and replace it with '' docs = corpus_without_punctuation.split("\n") term = term.lower() return (len([doc for doc in docs if term in doc]), len(docs)) def inverse_document_frequency(df: int, N: int, smoothing=False) -> float: """ Return an integer denoting the importance of a word. This measure of importance is calculated by log10(N/df), where N is the number of documents and df is the Document Frequency. @params : df, the Document Frequency, N, the number of documents in the corpus and smoothing, if True return the idf-smooth @returns : log10(N/df) or 1+log10(N/1+df) @examples : >>> inverse_document_frequency(3, 0) Traceback (most recent call last): ... ValueError: log10(0) is undefined. >>> inverse_document_frequency(1, 3) 0.477 >>> inverse_document_frequency(0, 3) Traceback (most recent call last): ... ZeroDivisionError: df must be > 0 >>> inverse_document_frequency(0, 3,True) 1.477 """ if smoothing: if N == 0: raise ValueError("log10(0) is undefined.") return round(1 + log10(N / (1 + df)), 3) if df == 0: raise ZeroDivisionError("df must be > 0") elif N == 0: raise ValueError("log10(0) is undefined.") return round(log10(N / df), 3) def tf_idf(tf: int, idf: int) -> float: """ Combine the term frequency and inverse document frequency functions to calculate the originality of a term. This 'originality' is calculated by multiplying the term frequency and the inverse document frequency : tf-idf = TF * IDF @params : tf, the term frequency, and idf, the inverse document frequency @examples : >>> tf_idf(2, 0.477) 0.954 """ return round(tf * idf, 3)
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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 gcd(a: int, b: int) -> int: while a != 0: a, b = b % a, a return b def find_mod_inverse(a: int, m: int) -> int: if gcd(a, m) != 1: raise ValueError(f"mod inverse of {a!r} and {m!r} does not exist") u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % m
def gcd(a: int, b: int) -> int: while a != 0: a, b = b % a, a return b def find_mod_inverse(a: int, m: int) -> int: if gcd(a, m) != 1: raise ValueError(f"mod inverse of {a!r} and {m!r} does not exist") u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % m
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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}`.
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome_counter("Momo") True >>> can_string_be_rearranged_as_palindrome_counter("Mother") False >>> can_string_be_rearranged_as_palindrome_counter("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ oddChar = 0 for character_count in character_freq_dict.values(): if character_count % 2: oddChar += 1 if oddChar > 1: return False return True def benchmark(input_str: str = "") -> None: """ Benchmark code for comparing above 2 functions """ print("\nFor string = ", input_str, ":") print( "> can_string_be_rearranged_as_palindrome_counter()", "\tans =", can_string_be_rearranged_as_palindrome_counter(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome_counter("Momo") True >>> can_string_be_rearranged_as_palindrome_counter("Mother") False >>> can_string_be_rearranged_as_palindrome_counter("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ oddChar = 0 for character_count in character_freq_dict.values(): if character_count % 2: oddChar += 1 if oddChar > 1: return False return True def benchmark(input_str: str = "") -> None: """ Benchmark code for comparing above 2 functions """ print("\nFor string = ", input_str, ":") print( "> can_string_be_rearranged_as_palindrome_counter()", "\tans =", can_string_be_rearranged_as_palindrome_counter(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
-1
TheAlgorithms/Python
4,314
fix(mypy): type annotations for conversions algorithms
### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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-04-04T13:03:20Z"
"2021-04-04T13:25:49Z"
536fb4bca48f69cb66cfbd03aeb02550def07977
20c7518028efbb6e8ae46a42b28c3f2e27acb2a2
fix(mypy): type annotations for conversions algorithms. ### **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. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside 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