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,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def roman_to_int(roman: str) -> int: """ LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(roman_to_int(key) == value for key, value in tests.items()) True """ vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True """ ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] result = [] for (arabic, roman) in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
def roman_to_int(roman: str) -> int: """ LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(roman_to_int(key) == value for key, value in tests.items()) True """ vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True """ ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] result = [] for (arabic, roman) in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" YouTube Explanation: https://www.youtube.com/watch?v=f2xi3c1S95M Given an integer n, return the minimum steps to 1 AVAILABLE STEPS: * Decrement by 1 * if n is divisible by 2, divide by 2 * if n is divisible by 3, divide by 3 Example 1: n = 10 10 -> 9 -> 3 -> 1 Result: 3 steps Example 2: n = 15 15 -> 5 -> 4 -> 2 -> 1 Result: 4 steps Example 3: n = 6 6 -> 2 -> 1 Result: 2 step """ from __future__ import annotations __author__ = "Alexander Joslin" def min_steps_to_one(number: int) -> int: """ Minimum steps to 1 implemented using tabulation. >>> min_steps_to_one(10) 3 >>> min_steps_to_one(15) 4 >>> min_steps_to_one(6) 2 :param number: :return int: """ if number <= 0: raise ValueError(f"n must be greater than 0. Got n = {number}") table = [number + 1] * (number + 1) # starting position table[1] = 0 for i in range(1, number): table[i + 1] = min(table[i + 1], table[i] + 1) # check if out of bounds if i * 2 <= number: table[i * 2] = min(table[i * 2], table[i] + 1) # check if out of bounds if i * 3 <= number: table[i * 3] = min(table[i * 3], table[i] + 1) return table[number] if __name__ == "__main__": import doctest doctest.testmod()
""" YouTube Explanation: https://www.youtube.com/watch?v=f2xi3c1S95M Given an integer n, return the minimum steps to 1 AVAILABLE STEPS: * Decrement by 1 * if n is divisible by 2, divide by 2 * if n is divisible by 3, divide by 3 Example 1: n = 10 10 -> 9 -> 3 -> 1 Result: 3 steps Example 2: n = 15 15 -> 5 -> 4 -> 2 -> 1 Result: 4 steps Example 3: n = 6 6 -> 2 -> 1 Result: 2 step """ from __future__ import annotations __author__ = "Alexander Joslin" def min_steps_to_one(number: int) -> int: """ Minimum steps to 1 implemented using tabulation. >>> min_steps_to_one(10) 3 >>> min_steps_to_one(15) 4 >>> min_steps_to_one(6) 2 :param number: :return int: """ if number <= 0: raise ValueError(f"n must be greater than 0. Got n = {number}") table = [number + 1] * (number + 1) # starting position table[1] = 0 for i in range(1, number): table[i + 1] = min(table[i + 1], table[i] + 1) # check if out of bounds if i * 2 <= number: table[i * 2] = min(table[i * 2], table[i] + 1) # check if out of bounds if i * 3 <= number: table[i * 3] = min(table[i * 3], table[i] + 1) return table[number] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round((float(moles / volume) * nfactor)) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round((float(moles / volume) * nfactor)) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" One of the several implementations of Lempel–Ziv–Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict, curr_string: str, index: int, last_match_id: int ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
""" One of the several implementations of Lempel–Ziv–Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict, curr_string: str, index: int, last_match_id: int ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# pack-refs with: peeled fully-peeled sorted 8668f5792dc673f085966f6f90c9c896081f22e9 refs/remotes/origin/Fewer-forward-propogations-to-speed-tests c1fd8cb9e667ab59ca4446d0dcf216d1696a010c refs/remotes/origin/Python-3.12-on-Debian-bookworm e093689124ab5f4a0938e4801abad0dbeb5bf881 refs/remotes/origin/cclauss-patch-1 04b896124ac5e76d5d5ed4ded91302557b1bc081 refs/remotes/origin/fix-maclaurin_series-on-Python3.12 672d0b39404444787f1ca3b5a3b6fd29a5a75447 refs/remotes/origin/fuzzy_operations.py-on-Python-3.12 9caf4784aada17dc75348f77cc8c356df503c0f3 refs/remotes/origin/master 01dc64a3a2f397872c759c4cb575ad2be5856d6a refs/remotes/origin/quantum_random.py.disabled
# pack-refs with: peeled fully-peeled sorted 8668f5792dc673f085966f6f90c9c896081f22e9 refs/remotes/origin/Fewer-forward-propogations-to-speed-tests c1fd8cb9e667ab59ca4446d0dcf216d1696a010c refs/remotes/origin/Python-3.12-on-Debian-bookworm e093689124ab5f4a0938e4801abad0dbeb5bf881 refs/remotes/origin/cclauss-patch-1 04b896124ac5e76d5d5ed4ded91302557b1bc081 refs/remotes/origin/fix-maclaurin_series-on-Python3.12 672d0b39404444787f1ca3b5a3b6fd29a5a75447 refs/remotes/origin/fuzzy_operations.py-on-Python-3.12 9caf4784aada17dc75348f77cc8c356df503c0f3 refs/remotes/origin/master 01dc64a3a2f397872c759c4cb575ad2be5856d6a refs/remotes/origin/quantum_random.py.disabled
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for downloading and reading MNIST data (deprecated). This module and all its submodules are deprecated. """ import collections import gzip import os import numpy from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.framework import dtypes from tensorflow.python.framework import random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _Datasets = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder(">") return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D uint8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) return data @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) if one_hot: return _dense_to_one_hot(labels, num_classes) return labels class _DataSet: """Container class for a _DataSet (deprecated). THIS CLASS IS DEPRECATED. """ @deprecated( None, "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models.", ) def __init__( self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, seed=None, ): """Construct a _DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. Seed arg provides for convenient deterministic testing. Args: images: The images labels: The labels fake_data: Ignore inages and labels, use fake data. one_hot: Bool, return the labels as one hot vectors (if True) or ints (if False). dtype: Output image dtype. One of [uint8, float32]. `uint8` output has range [0,255]. float32 output has range [0,1]. reshape: Bool. If True returned images are returned flattened to vectors. seed: The random seed to use. """ seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seed1 if seed is None else seed2) dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape( images.shape[0], images.shape[1] * images.shape[2] ) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(numpy.float32) images = numpy.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 if self.one_hot: fake_label = [1] + [0] * 9 else: fake_label = 0 return ( [fake_image for _ in xrange(batch_size)], [fake_label for _ in xrange(batch_size)], ) start = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: perm0 = numpy.arange(self._num_examples) numpy.random.shuffle(perm0) self._images = self.images[perm0] self._labels = self.labels[perm0] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch rest_num_examples = self._num_examples - start images_rest_part = self._images[start : self._num_examples] labels_rest_part = self._labels[start : self._num_examples] # Shuffle the data if shuffle: perm = numpy.arange(self._num_examples) numpy.random.shuffle(perm) self._images = self.images[perm] self._labels = self.labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size - rest_num_examples end = self._index_in_epoch images_new_part = self._images[start:end] labels_new_part = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part), axis=0), numpy.concatenate((labels_rest_part, labels_new_part), axis=0), ) else: self._index_in_epoch += batch_size end = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not gfile.Exists(filepath): urllib.request.urlretrieve(source_url, filepath) with gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath @deprecated( None, "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def read_data_sets( train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, validation_size=5000, seed=None, source_url=DEFAULT_SOURCE_URL, ): if fake_data: def fake(): return _DataSet( [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed ) train = fake() validation = fake() test = fake() return _Datasets(train=train, validation=validation, test=test) if not source_url: # empty string check source_url = DEFAULT_SOURCE_URL train_images_file = "train-images-idx3-ubyte.gz" train_labels_file = "train-labels-idx1-ubyte.gz" test_images_file = "t10k-images-idx3-ubyte.gz" test_labels_file = "t10k-labels-idx1-ubyte.gz" local_file = _maybe_download( train_images_file, train_dir, source_url + train_images_file ) with gfile.Open(local_file, "rb") as f: train_images = _extract_images(f) local_file = _maybe_download( train_labels_file, train_dir, source_url + train_labels_file ) with gfile.Open(local_file, "rb") as f: train_labels = _extract_labels(f, one_hot=one_hot) local_file = _maybe_download( test_images_file, train_dir, source_url + test_images_file ) with gfile.Open(local_file, "rb") as f: test_images = _extract_images(f) local_file = _maybe_download( test_labels_file, train_dir, source_url + test_labels_file ) with gfile.Open(local_file, "rb") as f: test_labels = _extract_labels(f, one_hot=one_hot) if not 0 <= validation_size <= len(train_images): raise ValueError( f"Validation size should be between 0 and {len(train_images)}. Received: {validation_size}." ) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] options = dict(dtype=dtype, reshape=reshape, seed=seed) train = _DataSet(train_images, train_labels, **options) validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) return _Datasets(train=train, validation=validation, test=test)
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for downloading and reading MNIST data (deprecated). This module and all its submodules are deprecated. """ import collections import gzip import os import numpy from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.framework import dtypes from tensorflow.python.framework import random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _Datasets = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder(">") return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D uint8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) return data @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) if one_hot: return _dense_to_one_hot(labels, num_classes) return labels class _DataSet: """Container class for a _DataSet (deprecated). THIS CLASS IS DEPRECATED. """ @deprecated( None, "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models.", ) def __init__( self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, seed=None, ): """Construct a _DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. Seed arg provides for convenient deterministic testing. Args: images: The images labels: The labels fake_data: Ignore inages and labels, use fake data. one_hot: Bool, return the labels as one hot vectors (if True) or ints (if False). dtype: Output image dtype. One of [uint8, float32]. `uint8` output has range [0,255]. float32 output has range [0,1]. reshape: Bool. If True returned images are returned flattened to vectors. seed: The random seed to use. """ seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seed1 if seed is None else seed2) dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape( images.shape[0], images.shape[1] * images.shape[2] ) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(numpy.float32) images = numpy.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 if self.one_hot: fake_label = [1] + [0] * 9 else: fake_label = 0 return ( [fake_image for _ in xrange(batch_size)], [fake_label for _ in xrange(batch_size)], ) start = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: perm0 = numpy.arange(self._num_examples) numpy.random.shuffle(perm0) self._images = self.images[perm0] self._labels = self.labels[perm0] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch rest_num_examples = self._num_examples - start images_rest_part = self._images[start : self._num_examples] labels_rest_part = self._labels[start : self._num_examples] # Shuffle the data if shuffle: perm = numpy.arange(self._num_examples) numpy.random.shuffle(perm) self._images = self.images[perm] self._labels = self.labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size - rest_num_examples end = self._index_in_epoch images_new_part = self._images[start:end] labels_new_part = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part), axis=0), numpy.concatenate((labels_rest_part, labels_new_part), axis=0), ) else: self._index_in_epoch += batch_size end = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not gfile.Exists(filepath): urllib.request.urlretrieve(source_url, filepath) with gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath @deprecated( None, "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def read_data_sets( train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, validation_size=5000, seed=None, source_url=DEFAULT_SOURCE_URL, ): if fake_data: def fake(): return _DataSet( [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed ) train = fake() validation = fake() test = fake() return _Datasets(train=train, validation=validation, test=test) if not source_url: # empty string check source_url = DEFAULT_SOURCE_URL train_images_file = "train-images-idx3-ubyte.gz" train_labels_file = "train-labels-idx1-ubyte.gz" test_images_file = "t10k-images-idx3-ubyte.gz" test_labels_file = "t10k-labels-idx1-ubyte.gz" local_file = _maybe_download( train_images_file, train_dir, source_url + train_images_file ) with gfile.Open(local_file, "rb") as f: train_images = _extract_images(f) local_file = _maybe_download( train_labels_file, train_dir, source_url + train_labels_file ) with gfile.Open(local_file, "rb") as f: train_labels = _extract_labels(f, one_hot=one_hot) local_file = _maybe_download( test_images_file, train_dir, source_url + test_images_file ) with gfile.Open(local_file, "rb") as f: test_images = _extract_images(f) local_file = _maybe_download( test_labels_file, train_dir, source_url + test_labels_file ) with gfile.Open(local_file, "rb") as f: test_labels = _extract_labels(f, one_hot=one_hot) if not 0 <= validation_size <= len(train_images): raise ValueError( f"Validation size should be between 0 and {len(train_images)}. Received: {validation_size}." ) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] options = dict(dtype=dtype, reshape=reshape, seed=seed) train = _DataSet(train_images, train_labels, **options) validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) return _Datasets(train=train, validation=validation, test=test)
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Picks the random index as the pivot """ import random def partition(A, left_index, right_index): pivot = A[left_index] i = left_index + 1 for j in range(left_index + 1, right_index): if A[j] < pivot: A[j], A[i] = A[i], A[j] i += 1 A[left_index], A[i - 1] = A[i - 1], A[left_index] return i - 1 def quick_sort_random(A, left, right): if left < right: pivot = random.randint(left, right - 1) A[pivot], A[left] = ( A[left], A[pivot], ) # switches the pivot with the left most bound pivot_index = partition(A, left, right) quick_sort_random( A, left, pivot_index ) # recursive quicksort to the left of the pivot point quick_sort_random( A, pivot_index + 1, right ) # recursive quicksort to the right of the pivot point def main(): user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] quick_sort_random(arr, 0, len(arr)) print(arr) if __name__ == "__main__": main()
""" Picks the random index as the pivot """ import random def partition(A, left_index, right_index): pivot = A[left_index] i = left_index + 1 for j in range(left_index + 1, right_index): if A[j] < pivot: A[j], A[i] = A[i], A[j] i += 1 A[left_index], A[i - 1] = A[i - 1], A[left_index] return i - 1 def quick_sort_random(A, left, right): if left < right: pivot = random.randint(left, right - 1) A[pivot], A[left] = ( A[left], A[pivot], ) # switches the pivot with the left most bound pivot_index = partition(A, left, right) quick_sort_random( A, left, pivot_index ) # recursive quicksort to the left of the pivot point quick_sort_random( A, pivot_index + 1, right ) # recursive quicksort to the right of the pivot point def main(): user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] quick_sort_random(arr, 0, len(arr)) print(arr) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def solution(n: int = 1000) -> int: """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for j in str(f): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def solution(n: int = 1000) -> int: """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for j in str(f): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") return "".join(sorted(str(n))) != str(n) and "".join(sorted(str(n)))[::-1] != str(n) def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") return "".join(sorted(str(n))) != str(n) and "".join(sorted(str(n)))[::-1] != str(n) def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ from random import choice from typing import List def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: List[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ from random import choice from typing import List def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: List[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author : Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. """ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(",") print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])] * len(self.array) sum_value = [int(self.array[0])] * len(self.array) for i in range(1, len(self.array)): sum_value[i] = max( int(self.array[i]) + sum_value[i - 1], int(self.array[i]) ) rear[i] = max(sum_value[i], rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() print(("the results is:", re))
""" Author : Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. """ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(",") print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])] * len(self.array) sum_value = [int(self.array[0])] * len(self.array) for i in range(1, len(self.array)): sum_value[i] = max( int(self.array[i]) + sum_value[i - 1], int(self.array[i]) ) rear[i] = max(sum_value[i], rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() print(("the results is:", re))
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Created on Fri Oct 16 09:31:07 2020 @author: Dr. Tobias Schröder @license: MIT-license This file contains the test-suite for the knapsack problem. """ import unittest from knapsack import knapsack as k class Test(unittest.TestCase): def test_base_case(self): """ test for the base case """ cap = 0 val = [0] w = [0] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 0) val = [60] w = [10] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 0) def test_easy_case(self): """ test for the base case """ cap = 3 val = [1, 2, 3] w = [3, 2, 1] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 5) def test_knapsack(self): """ test for the knapsack """ cap = 50 val = [60, 100, 120] w = [10, 20, 30] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 220) if __name__ == "__main__": unittest.main()
""" Created on Fri Oct 16 09:31:07 2020 @author: Dr. Tobias Schröder @license: MIT-license This file contains the test-suite for the knapsack problem. """ import unittest from knapsack import knapsack as k class Test(unittest.TestCase): def test_base_case(self): """ test for the base case """ cap = 0 val = [0] w = [0] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 0) val = [60] w = [10] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 0) def test_easy_case(self): """ test for the base case """ cap = 3 val = [1, 2, 3] w = [3, 2, 1] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 5) def test_knapsack(self): """ test for the knapsack """ cap = 50 val = [60, 100, 120] w = [10, 20, 30] c = len(val) self.assertEqual(k.knapsack(cap, w, val, c), 220) if __name__ == "__main__": unittest.main()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def kthPermutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kthPermutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], [1,2,3,0], [1,3,0,2] >>> kthPermutation(10,4) [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) # Find permutation while factorials: factorial = factorials.pop() number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) permutation.append(elements[0]) return permutation if __name__ == "__main__": import doctest doctest.testmod()
def kthPermutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kthPermutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], [1,2,3,0], [1,3,0,2] >>> kthPermutation(10,4) [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) # Find permutation while factorials: factorial = factorials.pop() number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) permutation.append(elements[0]) return permutation if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from 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,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ i = 1 j = 2 total = 0 while j <= n: if j % 2 == 0: total += j i, j = j, i + j return total if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ i = 1 j = 2 total = 0 while j <= n: if j % 2 == 0: total += j i, j = j, i + j return total if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(X, Y, weights): scores = np.dot(X, weights) return np.sum(Y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, X, y, max_iterations=70000): theta = np.zeros(X.shape[1]) for iterations in range(max_iterations): z = np.dot(X, theta) h = sigmoid_function(z) gradient = np.dot(X.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(X, theta) h = sigmoid_function(z) J = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {J} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() X = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, X, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(X): return sigmoid_function( np.dot(X, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color="b", label="0") plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (X[:, 0].min(), X[:, 0].max()) (x2_min, x2_max) = (X[:, 1].min(), X[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(X, Y, weights): scores = np.dot(X, weights) return np.sum(Y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, X, y, max_iterations=70000): theta = np.zeros(X.shape[1]) for iterations in range(max_iterations): z = np.dot(X, theta) h = sigmoid_function(z) gradient = np.dot(X.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(X, theta) h = sigmoid_function(z) J = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {J} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() X = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, X, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(X): return sigmoid_function( np.dot(X, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color="b", label="0") plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (X[:, 0].min(), X[:, 0].max()) (x2_min, x2_max) = (X[:, 1].min(), X[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Recursive Prorgam to create a Linked List from a sequence and # print a string representation of it. 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 += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List.""" # if elements_list is empty if not elements_list: raise Exception("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
# Recursive Prorgam to create a Linked List from a sequence and # print a string representation of it. 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 += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List.""" # if elements_list is empty if not elements_list: raise Exception("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function """ from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 >>> gaussian(1, 4, 2) 0.06475879783294587 >>> gaussian(1, 5, 3) 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma ** 2) * exp(-((x - mu) ** 2) / (2 * sigma ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function """ from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 >>> gaussian(1, 4, 2) 0.06475879783294587 >>> gaussian(1, 5, 3) 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma ** 2) * exp(-((x - mu) ** 2) / (2 * sigma ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/bin/sh # # Copyright (c) 2006, 2008 Junio C Hamano # # The "pre-rebase" hook is run just before "git rebase" starts doing # its job, and can prevent the command from running by exiting with # non-zero status. # # The hook is called with the following parameters: # # $1 -- the upstream the series was forked from. # $2 -- the branch being rebased (or empty when rebasing the current branch). # # This sample shows how to prevent topic branches that are already # merged to 'next' branch from getting rebased, because allowing it # would result in rebasing already published history. publish=next basebranch="$1" if test "$#" = 2 then topic="refs/heads/$2" else topic=`git symbolic-ref HEAD` || exit 0 ;# we do not interrupt rebasing detached HEAD fi case "$topic" in refs/heads/??/*) ;; *) exit 0 ;# we do not interrupt others. ;; esac # Now we are dealing with a topic branch being rebased # on top of master. Is it OK to rebase it? # Does the topic really exist? git show-ref -q "$topic" || { echo >&2 "No such branch $topic" exit 1 } # Is topic fully merged to master? not_in_master=`git rev-list --pretty=oneline ^master "$topic"` if test -z "$not_in_master" then echo >&2 "$topic is fully merged to master; better remove it." exit 1 ;# we could allow it, but there is no point. fi # Is topic ever merged to next? If so you should not be rebasing it. only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` only_next_2=`git rev-list ^master ${publish} | sort` if test "$only_next_1" = "$only_next_2" then not_in_topic=`git rev-list "^$topic" master` if test -z "$not_in_topic" then echo >&2 "$topic is already up to date with master" exit 1 ;# we could allow it, but there is no point. else exit 0 fi else not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` /usr/bin/perl -e ' my $topic = $ARGV[0]; my $msg = "* $topic has commits already merged to public branch:\n"; my (%not_in_next) = map { /^([0-9a-f]+) /; ($1 => 1); } split(/\n/, $ARGV[1]); for my $elem (map { /^([0-9a-f]+) (.*)$/; [$1 => $2]; } split(/\n/, $ARGV[2])) { if (!exists $not_in_next{$elem->[0]}) { if ($msg) { print STDERR $msg; undef $msg; } print STDERR " $elem->[1]\n"; } } ' "$topic" "$not_in_next" "$not_in_master" exit 1 fi <<\DOC_END This sample hook safeguards topic branches that have been published from being rewound. The workflow assumed here is: * Once a topic branch forks from "master", "master" is never merged into it again (either directly or indirectly). * Once a topic branch is fully cooked and merged into "master", it is deleted. If you need to build on top of it to correct earlier mistakes, a new topic branch is created by forking at the tip of the "master". This is not strictly necessary, but it makes it easier to keep your history simple. * Whenever you need to test or publish your changes to topic branches, merge them into "next" branch. The script, being an example, hardcodes the publish branch name to be "next", but it is trivial to make it configurable via $GIT_DIR/config mechanism. With this workflow, you would want to know: (1) ... if a topic branch has ever been merged to "next". Young topic branches can have stupid mistakes you would rather clean up before publishing, and things that have not been merged into other branches can be easily rebased without affecting other people. But once it is published, you would not want to rewind it. (2) ... if a topic branch has been fully merged to "master". Then you can delete it. More importantly, you should not build on top of it -- other people may already want to change things related to the topic as patches against your "master", so if you need further changes, it is better to fork the topic (perhaps with the same name) afresh from the tip of "master". Let's look at this example: o---o---o---o---o---o---o---o---o---o "next" / / / / / a---a---b A / / / / / / / / c---c---c---c B / / / / \ / / / / b---b C \ / / / / / \ / ---o---o---o---o---o---o---o---o---o---o---o "master" A, B and C are topic branches. * A has one fix since it was merged up to "next". * B has finished. It has been fully merged up to "master" and "next", and is ready to be deleted. * C has not merged to "next" at all. We would want to allow C to be rebased, refuse A, and encourage B to be deleted. To compute (1): git rev-list ^master ^topic next git rev-list ^master next if these match, topic has not merged in next at all. To compute (2): git rev-list master..topic if this is empty, it is fully merged to "master". DOC_END
#!/bin/sh # # Copyright (c) 2006, 2008 Junio C Hamano # # The "pre-rebase" hook is run just before "git rebase" starts doing # its job, and can prevent the command from running by exiting with # non-zero status. # # The hook is called with the following parameters: # # $1 -- the upstream the series was forked from. # $2 -- the branch being rebased (or empty when rebasing the current branch). # # This sample shows how to prevent topic branches that are already # merged to 'next' branch from getting rebased, because allowing it # would result in rebasing already published history. publish=next basebranch="$1" if test "$#" = 2 then topic="refs/heads/$2" else topic=`git symbolic-ref HEAD` || exit 0 ;# we do not interrupt rebasing detached HEAD fi case "$topic" in refs/heads/??/*) ;; *) exit 0 ;# we do not interrupt others. ;; esac # Now we are dealing with a topic branch being rebased # on top of master. Is it OK to rebase it? # Does the topic really exist? git show-ref -q "$topic" || { echo >&2 "No such branch $topic" exit 1 } # Is topic fully merged to master? not_in_master=`git rev-list --pretty=oneline ^master "$topic"` if test -z "$not_in_master" then echo >&2 "$topic is fully merged to master; better remove it." exit 1 ;# we could allow it, but there is no point. fi # Is topic ever merged to next? If so you should not be rebasing it. only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` only_next_2=`git rev-list ^master ${publish} | sort` if test "$only_next_1" = "$only_next_2" then not_in_topic=`git rev-list "^$topic" master` if test -z "$not_in_topic" then echo >&2 "$topic is already up to date with master" exit 1 ;# we could allow it, but there is no point. else exit 0 fi else not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` /usr/bin/perl -e ' my $topic = $ARGV[0]; my $msg = "* $topic has commits already merged to public branch:\n"; my (%not_in_next) = map { /^([0-9a-f]+) /; ($1 => 1); } split(/\n/, $ARGV[1]); for my $elem (map { /^([0-9a-f]+) (.*)$/; [$1 => $2]; } split(/\n/, $ARGV[2])) { if (!exists $not_in_next{$elem->[0]}) { if ($msg) { print STDERR $msg; undef $msg; } print STDERR " $elem->[1]\n"; } } ' "$topic" "$not_in_next" "$not_in_master" exit 1 fi <<\DOC_END This sample hook safeguards topic branches that have been published from being rewound. The workflow assumed here is: * Once a topic branch forks from "master", "master" is never merged into it again (either directly or indirectly). * Once a topic branch is fully cooked and merged into "master", it is deleted. If you need to build on top of it to correct earlier mistakes, a new topic branch is created by forking at the tip of the "master". This is not strictly necessary, but it makes it easier to keep your history simple. * Whenever you need to test or publish your changes to topic branches, merge them into "next" branch. The script, being an example, hardcodes the publish branch name to be "next", but it is trivial to make it configurable via $GIT_DIR/config mechanism. With this workflow, you would want to know: (1) ... if a topic branch has ever been merged to "next". Young topic branches can have stupid mistakes you would rather clean up before publishing, and things that have not been merged into other branches can be easily rebased without affecting other people. But once it is published, you would not want to rewind it. (2) ... if a topic branch has been fully merged to "master". Then you can delete it. More importantly, you should not build on top of it -- other people may already want to change things related to the topic as patches against your "master", so if you need further changes, it is better to fork the topic (perhaps with the same name) afresh from the tip of "master". Let's look at this example: o---o---o---o---o---o---o---o---o---o "next" / / / / / a---a---b A / / / / / / / / c---c---c---c B / / / / \ / / / / b---b C \ / / / / / \ / ---o---o---o---o---o---o---o---o---o---o---o "master" A, B and C are topic branches. * A has one fix since it was merged up to "next". * B has finished. It has been fully merged up to "master" and "next", and is ready to be deleted. * C has not merged to "next" at all. We would want to allow C to be rebased, refuse A, and encourage B to be deleted. To compute (1): git rev-list ^master ^topic next git rev-list ^master next if these match, topic has not merged in next at all. To compute (2): git rev-list master..topic if this is empty, it is fully merged to "master". DOC_END
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
total_user,total_events,days 18231,0.0,1 22621,1.0,2 15675,0.0,3 23583,1.0,4 68351,5.0,5 34338,3.0,6 19238,0.0,0 24192,0.0,1 70349,0.0,2 103510,0.0,3 128355,1.0,4 148484,6.0,5 153489,3.0,6 162667,1.0,0 311430,3.0,1 435663,7.0,2 273526,0.0,3 628588,2.0,4 454989,13.0,5 539040,3.0,6 52974,1.0,0 103451,2.0,1 810020,5.0,2 580982,3.0,3 216515,0.0,4 134694,10.0,5 93563,1.0,6 55432,1.0,0 169634,1.0,1 254908,4.0,2 315285,3.0,3 191764,0.0,4 514284,7.0,5 181214,4.0,6 78459,2.0,0 161620,3.0,1 245610,4.0,2 326722,5.0,3 214578,0.0,4 312365,5.0,5 232454,4.0,6 178368,1.0,0 97152,1.0,1 222813,4.0,2 285852,4.0,3 192149,1.0,4 142241,1.0,5 173011,2.0,6 56488,3.0,0 89572,2.0,1 356082,2.0,2 172799,0.0,3 142300,1.0,4 78432,2.0,5 539023,9.0,6 62389,1.0,0 70247,1.0,1 89229,0.0,2 94583,1.0,3 102455,0.0,4 129270,0.0,5 311409,1.0,6 1837026,0.0,0 361824,0.0,1 111379,2.0,2 76337,2.0,3 96747,0.0,4 92058,0.0,5 81929,2.0,6 143423,0.0,0 82939,0.0,1 74403,1.0,2 68234,0.0,3 94556,1.0,4 80311,0.0,5 75283,3.0,6 77724,0.0,0 49229,2.0,1 65708,2.0,2 273864,1.0,3 1711281,0.0,4 1900253,5.0,5 343071,1.0,6 1551326,0.0,0 56636,1.0,1 272782,2.0,2 1785678,0.0,3 241866,0.0,4 461904,0.0,5 2191901,2.0,6 102925,0.0,0 242778,1.0,1 298608,0.0,2 322458,10.0,3 216027,9.0,4 916052,12.0,5 193278,12.0,6 263207,8.0,0 672948,10.0,1 281909,1.0,2 384562,1.0,3 1027375,2.0,4 828905,9.0,5 624188,22.0,6 392218,8.0,0 292581,10.0,1 299869,12.0,2 769455,20.0,3 316443,8.0,4 1212864,24.0,5 1397338,28.0,6 223249,8.0,0 191264,14.0,1
total_user,total_events,days 18231,0.0,1 22621,1.0,2 15675,0.0,3 23583,1.0,4 68351,5.0,5 34338,3.0,6 19238,0.0,0 24192,0.0,1 70349,0.0,2 103510,0.0,3 128355,1.0,4 148484,6.0,5 153489,3.0,6 162667,1.0,0 311430,3.0,1 435663,7.0,2 273526,0.0,3 628588,2.0,4 454989,13.0,5 539040,3.0,6 52974,1.0,0 103451,2.0,1 810020,5.0,2 580982,3.0,3 216515,0.0,4 134694,10.0,5 93563,1.0,6 55432,1.0,0 169634,1.0,1 254908,4.0,2 315285,3.0,3 191764,0.0,4 514284,7.0,5 181214,4.0,6 78459,2.0,0 161620,3.0,1 245610,4.0,2 326722,5.0,3 214578,0.0,4 312365,5.0,5 232454,4.0,6 178368,1.0,0 97152,1.0,1 222813,4.0,2 285852,4.0,3 192149,1.0,4 142241,1.0,5 173011,2.0,6 56488,3.0,0 89572,2.0,1 356082,2.0,2 172799,0.0,3 142300,1.0,4 78432,2.0,5 539023,9.0,6 62389,1.0,0 70247,1.0,1 89229,0.0,2 94583,1.0,3 102455,0.0,4 129270,0.0,5 311409,1.0,6 1837026,0.0,0 361824,0.0,1 111379,2.0,2 76337,2.0,3 96747,0.0,4 92058,0.0,5 81929,2.0,6 143423,0.0,0 82939,0.0,1 74403,1.0,2 68234,0.0,3 94556,1.0,4 80311,0.0,5 75283,3.0,6 77724,0.0,0 49229,2.0,1 65708,2.0,2 273864,1.0,3 1711281,0.0,4 1900253,5.0,5 343071,1.0,6 1551326,0.0,0 56636,1.0,1 272782,2.0,2 1785678,0.0,3 241866,0.0,4 461904,0.0,5 2191901,2.0,6 102925,0.0,0 242778,1.0,1 298608,0.0,2 322458,10.0,3 216027,9.0,4 916052,12.0,5 193278,12.0,6 263207,8.0,0 672948,10.0,1 281909,1.0,2 384562,1.0,3 1027375,2.0,4 828905,9.0,5 624188,22.0,6 392218,8.0,0 292581,10.0,1 299869,12.0,2 769455,20.0,3 316443,8.0,4 1212864,24.0,5 1397338,28.0,6 223249,8.0,0 191264,14.0,1
-1
TheAlgorithms/Python
4,224
[mypy]Correction of all errors in the sorts directory
### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MatthewG25
"2021-02-22T11:02:18Z"
"2021-02-23T09:02:31Z"
02d9bc66c16a9cc851200f149fabbb07df611525
a4726ca248b3cf0470e5453ac1d9878eded38d27
[mypy]Correction of all errors in the sorts directory. ### **Describe your change:** Completion of all mypy errors apart from a stub error. See #4222 for more detail. The errors were four type annotations, and the last was a return statement error found in the cocktail_shaker_sort algorithm which was fixed. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis from mid-point's Xco-ords. Points sorted based on Yco-ords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. Time complexity: O(n * log n) """ def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis from mid-point's Xco-ords. Points sorted based on Yco-ords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. Time complexity: O(n * log n) """ def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def main(): filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.makeKeyFiles("rsa", 1024) message = input("\nEnter message: ") pubKeyFilename = "rsa_pubkey.txt" print("Encrypting and writing to %s..." % (filename)) encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message) print("\nEncrypted text:") print(encryptedText) elif mode == "decrypt": privKeyFilename = "rsa_privkey.txt" print("Reading from %s and decrypting..." % (filename)) decryptedText = readFromFileAndDecrypt(filename, privKeyFilename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decryptedText) print("\nDecryption:") print(decryptedText) def getBlocksFromText(message: int, blockSize: int = DEFAULT_BLOCK_SIZE) -> [int]: messageBytes = message.encode("ascii") blockInts = [] for blockStart in range(0, len(messageBytes), blockSize): blockInt = 0 for i in range(blockStart, min(blockStart + blockSize, len(messageBytes))): blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize)) blockInts.append(blockInt) return blockInts def getTextFromBlocks( blockInts: [int], messageLength: int, blockSize: int = DEFAULT_BLOCK_SIZE ) -> str: message = [] for blockInt in blockInts: blockMessage = [] for i in range(blockSize - 1, -1, -1): if len(message) + i < messageLength: asciiNumber = blockInt // (BYTE_SIZE ** i) blockInt = blockInt % (BYTE_SIZE ** i) blockMessage.insert(0, chr(asciiNumber)) message.extend(blockMessage) return "".join(message) def encryptMessage( message: str, key: (int, int), blockSize: int = DEFAULT_BLOCK_SIZE ) -> [int]: encryptedBlocks = [] n, e = key for block in getBlocksFromText(message, blockSize): encryptedBlocks.append(pow(block, e, n)) return encryptedBlocks def decryptMessage( encryptedBlocks: [int], messageLength: int, key: (int, int), blockSize: int = DEFAULT_BLOCK_SIZE, ) -> str: decryptedBlocks = [] n, d = key for block in encryptedBlocks: decryptedBlocks.append(pow(block, d, n)) return getTextFromBlocks(decryptedBlocks, messageLength, blockSize) def readKeyFile(keyFilename: str) -> (int, int, int): with open(keyFilename) as fo: content = fo.read() keySize, n, EorD = content.split(",") return (int(keySize), int(n), int(EorD)) def encryptAndWriteToFile( messageFilename: str, keyFilename: str, message: str, blockSize: int = DEFAULT_BLOCK_SIZE, ) -> str: keySize, n, e = readKeyFile(keyFilename) if keySize < blockSize * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (blockSize * 8, keySize) ) encryptedBlocks = encryptMessage(message, (n, e), blockSize) for i in range(len(encryptedBlocks)): encryptedBlocks[i] = str(encryptedBlocks[i]) encryptedContent = ",".join(encryptedBlocks) encryptedContent = "{}_{}_{}".format(len(message), blockSize, encryptedContent) with open(messageFilename, "w") as fo: fo.write(encryptedContent) return encryptedContent def readFromFileAndDecrypt(messageFilename: str, keyFilename: str) -> str: keySize, n, d = readKeyFile(keyFilename) with open(messageFilename) as fo: content = fo.read() messageLength, blockSize, encryptedMessage = content.split("_") messageLength = int(messageLength) blockSize = int(blockSize) if keySize < blockSize * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (blockSize * 8, keySize) ) encryptedBlocks = [] for block in encryptedMessage.split(","): encryptedBlocks.append(int(block)) return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize) if __name__ == "__main__": main()
import os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def main(): filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.makeKeyFiles("rsa", 1024) message = input("\nEnter message: ") pubKeyFilename = "rsa_pubkey.txt" print("Encrypting and writing to %s..." % (filename)) encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message) print("\nEncrypted text:") print(encryptedText) elif mode == "decrypt": privKeyFilename = "rsa_privkey.txt" print("Reading from %s and decrypting..." % (filename)) decryptedText = readFromFileAndDecrypt(filename, privKeyFilename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decryptedText) print("\nDecryption:") print(decryptedText) def getBlocksFromText(message: int, blockSize: int = DEFAULT_BLOCK_SIZE) -> [int]: messageBytes = message.encode("ascii") blockInts = [] for blockStart in range(0, len(messageBytes), blockSize): blockInt = 0 for i in range(blockStart, min(blockStart + blockSize, len(messageBytes))): blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize)) blockInts.append(blockInt) return blockInts def getTextFromBlocks( blockInts: [int], messageLength: int, blockSize: int = DEFAULT_BLOCK_SIZE ) -> str: message = [] for blockInt in blockInts: blockMessage = [] for i in range(blockSize - 1, -1, -1): if len(message) + i < messageLength: asciiNumber = blockInt // (BYTE_SIZE ** i) blockInt = blockInt % (BYTE_SIZE ** i) blockMessage.insert(0, chr(asciiNumber)) message.extend(blockMessage) return "".join(message) def encryptMessage( message: str, key: (int, int), blockSize: int = DEFAULT_BLOCK_SIZE ) -> [int]: encryptedBlocks = [] n, e = key for block in getBlocksFromText(message, blockSize): encryptedBlocks.append(pow(block, e, n)) return encryptedBlocks def decryptMessage( encryptedBlocks: [int], messageLength: int, key: (int, int), blockSize: int = DEFAULT_BLOCK_SIZE, ) -> str: decryptedBlocks = [] n, d = key for block in encryptedBlocks: decryptedBlocks.append(pow(block, d, n)) return getTextFromBlocks(decryptedBlocks, messageLength, blockSize) def readKeyFile(keyFilename: str) -> (int, int, int): with open(keyFilename) as fo: content = fo.read() keySize, n, EorD = content.split(",") return (int(keySize), int(n), int(EorD)) def encryptAndWriteToFile( messageFilename: str, keyFilename: str, message: str, blockSize: int = DEFAULT_BLOCK_SIZE, ) -> str: keySize, n, e = readKeyFile(keyFilename) if keySize < blockSize * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (blockSize * 8, keySize) ) encryptedBlocks = encryptMessage(message, (n, e), blockSize) for i in range(len(encryptedBlocks)): encryptedBlocks[i] = str(encryptedBlocks[i]) encryptedContent = ",".join(encryptedBlocks) encryptedContent = f"{len(message)}_{blockSize}_{encryptedContent}" with open(messageFilename, "w") as fo: fo.write(encryptedContent) return encryptedContent def readFromFileAndDecrypt(messageFilename: str, keyFilename: str) -> str: keySize, n, d = readKeyFile(keyFilename) with open(messageFilename) as fo: content = fo.read() messageLength, blockSize, encryptedMessage = content.split("_") messageLength = int(messageLength) blockSize = int(blockSize) if keySize < blockSize * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (blockSize * 8, keySize) ) encryptedBlocks = [] for block in encryptedMessage.split(","): encryptedBlocks.append(int(block)) return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize) if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import os import random import sys from typing import Tuple from . import cryptomath_module as cryptoMath from . import rabin_miller as rabinMiller def main(): print("Making key files...") makeKeyFiles("rsa", 1024) print("Key files generation successful.") def generateKey(keySize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]: print("Generating prime p...") p = rabinMiller.generateLargePrime(keySize) print("Generating prime q...") q = rabinMiller.generateLargePrime(keySize) n = p * q print("Generating e that is relatively prime to (p - 1) * (q - 1)...") while True: e = random.randrange(2 ** (keySize - 1), 2 ** (keySize)) if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1: break print("Calculating d that is mod inverse of e...") d = cryptoMath.findModInverse(e, (p - 1) * (q - 1)) publicKey = (n, e) privateKey = (n, d) return (publicKey, privateKey) def makeKeyFiles(name: int, keySize: int) -> None: if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( "%s_privkey.txt" % (name) ): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generateKey(keySize) print("\nWriting public key to file %s_pubkey.txt..." % name) with open("%s_pubkey.txt" % name, "w") as out_file: out_file.write("{},{},{}".format(keySize, publicKey[0], publicKey[1])) print("Writing private key to file %s_privkey.txt..." % name) with open("%s_privkey.txt" % name, "w") as out_file: out_file.write("{},{},{}".format(keySize, privateKey[0], privateKey[1])) if __name__ == "__main__": main()
import os import random import sys from typing import Tuple from . import cryptomath_module as cryptoMath from . import rabin_miller as rabinMiller def main(): print("Making key files...") makeKeyFiles("rsa", 1024) print("Key files generation successful.") def generateKey(keySize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]: print("Generating prime p...") p = rabinMiller.generateLargePrime(keySize) print("Generating prime q...") q = rabinMiller.generateLargePrime(keySize) n = p * q print("Generating e that is relatively prime to (p - 1) * (q - 1)...") while True: e = random.randrange(2 ** (keySize - 1), 2 ** (keySize)) if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1: break print("Calculating d that is mod inverse of e...") d = cryptoMath.findModInverse(e, (p - 1) * (q - 1)) publicKey = (n, e) privateKey = (n, d) return (publicKey, privateKey) def makeKeyFiles(name: int, keySize: int) -> None: if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( "%s_privkey.txt" % (name) ): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generateKey(keySize) print("\nWriting public key to file %s_pubkey.txt..." % name) with open("%s_pubkey.txt" % name, "w") as out_file: out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}") print("Writing private key to file %s_privkey.txt..." % name) with open("%s_privkey.txt" % name, "w") as out_file: out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}") if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> dict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation return { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for x in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) bwt_output_msg = "Burrows Wheeler transform for string '{}' results in '{}'" print(bwt_output_msg.format(s, result["bwt_string"])) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) fmt = ( "Reversing Burrows Wheeler transform for entry '{}' we get original" " string '{}'" ) print(fmt.format(result["bwt_string"], original_string))
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> dict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation return { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for x in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A non-recursive Segment Tree implementation with range query and single element update, works virtually with any list of the same type of elements with a "commutative" combiner. Explanation: https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/ https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ >>> SegmentTree([1, 2, 3], lambda a, b: a + b).query(0, 2) 6 >>> SegmentTree([3, 1, 2], min).query(0, 2) 1 >>> SegmentTree([2, 3, 1], max).query(0, 2) 3 >>> st = SegmentTree([1, 5, 7, -1, 6], lambda a, b: a + b) >>> st.update(1, -1) >>> st.update(2, 3) >>> st.query(1, 2) 2 >>> st.query(1, 1) -1 >>> st.update(4, 1) >>> st.query(3, 4) 0 >>> st = SegmentTree([[1, 2, 3], [3, 2, 1], [1, 1, 1]], lambda a, b: [a[i] + b[i] for i ... in range(len(a))]) >>> st.query(0, 1) [4, 4, 4] >>> st.query(1, 2) [4, 3, 2] >>> st.update(1, [-1, -1, -1]) >>> st.query(1, 2) [0, 0, 0] >>> st.query(0, 2) [1, 2, 3] """ from __future__ import annotations from typing import Callable, TypeVar T = TypeVar("T") class SegmentTree: def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: """ Segment Tree constructor, it works just with commutative combiner. :param arr: list of elements for the segment tree :param fnc: commutative function for combine two elements >>> SegmentTree(['a', 'b', 'c'], lambda a, b: '{}{}'.format(a, b)).query(0, 2) 'abc' >>> SegmentTree([(1, 2), (2, 3), (3, 4)], ... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2) (6, 9) """ self.N = len(arr) self.st = [None for _ in range(len(arr))] + arr self.fn = fnc self.build() def build(self) -> None: for p in range(self.N - 1, 0, -1): self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def update(self, p: int, v: T) -> None: """ Update an element in log(N) time :param p: position to be update :param v: new value >>> st = SegmentTree([3, 1, 2, 4], min) >>> st.query(0, 3) 1 >>> st.update(2, -1) >>> st.query(0, 3) -1 """ p += self.N self.st[p] = v while p > 1: p = p // 2 self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def query(self, l: int, r: int) -> T: # noqa: E741 """ Get range query value in log(N) time :param l: left element index :param r: right element index :return: element combined in the range [l, r] >>> st = SegmentTree([1, 2, 3, 4], lambda a, b: a + b) >>> st.query(0, 2) 6 >>> st.query(1, 2) 5 >>> st.query(0, 3) 10 >>> st.query(2, 3) 7 """ l, r = l + self.N, r + self.N # noqa: E741 res = None while l <= r: # noqa: E741 if l % 2 == 1: res = self.st[l] if res is None else self.fn(res, self.st[l]) if r % 2 == 0: res = self.st[r] if res is None else self.fn(res, self.st[r]) l, r = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] test_updates = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } min_segment_tree = SegmentTree(test_array, min) max_segment_tree = SegmentTree(test_array, max) sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b) def test_all_segments(): """ Test all possible segments """ for i in range(len(test_array)): for j in range(i, len(test_array)): min_range = reduce(min, test_array[i : j + 1]) max_range = reduce(max, test_array[i : j + 1]) sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1]) assert min_range == min_segment_tree.query(i, j) assert max_range == max_segment_tree.query(i, j) assert sum_range == sum_segment_tree.query(i, j) test_all_segments() for index, value in test_updates.items(): test_array[index] = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
""" A non-recursive Segment Tree implementation with range query and single element update, works virtually with any list of the same type of elements with a "commutative" combiner. Explanation: https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/ https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ >>> SegmentTree([1, 2, 3], lambda a, b: a + b).query(0, 2) 6 >>> SegmentTree([3, 1, 2], min).query(0, 2) 1 >>> SegmentTree([2, 3, 1], max).query(0, 2) 3 >>> st = SegmentTree([1, 5, 7, -1, 6], lambda a, b: a + b) >>> st.update(1, -1) >>> st.update(2, 3) >>> st.query(1, 2) 2 >>> st.query(1, 1) -1 >>> st.update(4, 1) >>> st.query(3, 4) 0 >>> st = SegmentTree([[1, 2, 3], [3, 2, 1], [1, 1, 1]], lambda a, b: [a[i] + b[i] for i ... in range(len(a))]) >>> st.query(0, 1) [4, 4, 4] >>> st.query(1, 2) [4, 3, 2] >>> st.update(1, [-1, -1, -1]) >>> st.query(1, 2) [0, 0, 0] >>> st.query(0, 2) [1, 2, 3] """ from __future__ import annotations from typing import Callable, TypeVar T = TypeVar("T") class SegmentTree: def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: """ Segment Tree constructor, it works just with commutative combiner. :param arr: list of elements for the segment tree :param fnc: commutative function for combine two elements >>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2) 'abc' >>> SegmentTree([(1, 2), (2, 3), (3, 4)], ... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2) (6, 9) """ self.N = len(arr) self.st = [None for _ in range(len(arr))] + arr self.fn = fnc self.build() def build(self) -> None: for p in range(self.N - 1, 0, -1): self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def update(self, p: int, v: T) -> None: """ Update an element in log(N) time :param p: position to be update :param v: new value >>> st = SegmentTree([3, 1, 2, 4], min) >>> st.query(0, 3) 1 >>> st.update(2, -1) >>> st.query(0, 3) -1 """ p += self.N self.st[p] = v while p > 1: p = p // 2 self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def query(self, l: int, r: int) -> T: # noqa: E741 """ Get range query value in log(N) time :param l: left element index :param r: right element index :return: element combined in the range [l, r] >>> st = SegmentTree([1, 2, 3, 4], lambda a, b: a + b) >>> st.query(0, 2) 6 >>> st.query(1, 2) 5 >>> st.query(0, 3) 10 >>> st.query(2, 3) 7 """ l, r = l + self.N, r + self.N # noqa: E741 res = None while l <= r: # noqa: E741 if l % 2 == 1: res = self.st[l] if res is None else self.fn(res, self.st[l]) if r % 2 == 0: res = self.st[r] if res is None else self.fn(res, self.st[r]) l, r = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] test_updates = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } min_segment_tree = SegmentTree(test_array, min) max_segment_tree = SegmentTree(test_array, max) sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b) def test_all_segments(): """ Test all possible segments """ for i in range(len(test_array)): for j in range(i, len(test_array)): min_range = reduce(min, test_array[i : j + 1]) max_range = reduce(max, test_array[i : j + 1]) sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1]) assert min_range == min_segment_tree.query(i, j) assert max_range == max_segment_tree.query(i, j) assert sum_range == sum_segment_tree.query(i, j) test_all_segments() for index, value in test_updates.items(): test_array[index] = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" python/black : true flake8 : passed """ from typing import Iterator, Optional class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: Optional[int] = None, color: int = 0, parent: Optional["RedBlackTree"] = None, left: Optional["RedBlackTree"] = None, right: Optional["RedBlackTree"] = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> "RedBlackTree": """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() self.left._insert_repair() elif self.is_left(): self.grandparent.rotate_right() self.parent.color = 0 self.parent.right.color = 1 else: self.grandparent.rotate_left() self.parent.color = 0 self.parent.left.color = 1 else: self.parent.color = 0 uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> "RedBlackTree": """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> None: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> "RedBlackTree": """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> "RedBlackTree": """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> "RedBlackTree": """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" return self.parent and self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" return self.parent and self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return "'{} {}'".format(self.label, (self.color and "red") or "blk") return pformat( { "%s %s" % (self.label, (self.color and "red") or "blk"): (self.left, self.right) }, indent=1, ) def __eq__(self, other) -> bool: """Test if two trees are equal.""" if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
""" python/black : true flake8 : passed """ from typing import Iterator, Optional class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: Optional[int] = None, color: int = 0, parent: Optional["RedBlackTree"] = None, left: Optional["RedBlackTree"] = None, right: Optional["RedBlackTree"] = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> "RedBlackTree": """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() self.left._insert_repair() elif self.is_left(): self.grandparent.rotate_right() self.parent.color = 0 self.parent.right.color = 1 else: self.grandparent.rotate_left() self.parent.color = 0 self.parent.left.color = 1 else: self.parent.color = 0 uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> "RedBlackTree": """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> None: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> "RedBlackTree": """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> "RedBlackTree": """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> "RedBlackTree": """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" return self.parent and self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" return self.parent and self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other) -> bool: """Test if two trees are equal.""" if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """ A Private class (to be inherited) """ class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return " Prev -> {}, Next -> {}".format( self._prev is not None, self._next is not None ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """ A Private class (to be inherited) """ class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] 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 """ fmt = "n needs to be positive integer, your input {}" assert isinstance(n, int) and n > 0, fmt.format(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,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author : Syed Faizan (3rd Year Student IIIT Pune) github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set """ from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: """ Args: mask : number which shows mask ( always integer > 0, zero does not have any submasks ) Returns: all_submasks : the list of submasks of mask (mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer >>> list_of_submasks(15) [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> list_of_submasks(13) [13, 12, 9, 8, 5, 4, 1] >>> list_of_submasks(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input -7 >>> list_of_submasks(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input 0 """ fmt = "mask needs to be positive integer, your input {}" assert isinstance(mask, int) and mask > 0, fmt.format(mask) """ first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero ( zero is not included in final submasks list ) """ all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Syed Faizan (3rd Year Student IIIT Pune) github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set """ from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: """ Args: mask : number which shows mask ( always integer > 0, zero does not have any submasks ) Returns: all_submasks : the list of submasks of mask (mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer >>> list_of_submasks(15) [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> list_of_submasks(13) [13, 12, 9, 8, 5, 4, 1] >>> list_of_submasks(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input -7 >>> list_of_submasks(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input 0 """ assert ( isinstance(mask, int) and mask > 0 ), f"mask needs to be positive integer, your input {mask}" """ first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero ( zero is not included in final submasks list ) """ all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier # Load iris file iris = load_iris() iris.keys() print(f"Target names: \n {iris.target_names} ") print(f"\n Features: \n {iris.feature_names}") # Train set e Test set X_train, X_test, y_train, y_test = train_test_split( iris["data"], iris["target"], random_state=4 ) # KNN knn = KNeighborsClassifier(n_neighbors=1) knn.fit(X_train, y_train) # new array to test X_new = [[1, 2, 1, 4], [2, 3, 4, 5]] prediction = knn.predict(X_new) print( "\nNew array: \n {}" "\n\nTarget Names Prediction: \n {}".format(X_new, iris["target_names"][prediction]) )
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier # Load iris file iris = load_iris() iris.keys() print(f"Target names: \n {iris.target_names} ") print(f"\n Features: \n {iris.feature_names}") # Train set e Test set X_train, X_test, y_train, y_test = train_test_split( iris["data"], iris["target"], random_state=4 ) # KNN knn = KNeighborsClassifier(n_neighbors=1) knn.fit(X_train, y_train) # new array to test X_new = [[1, 2, 1, 4], [2, 3, 4, 5]] prediction = knn.predict(X_new) print( f"\nNew array: \n {X_new}\n\nTarget Names Prediction: \n" f" {iris['target_names'][prediction]}" )
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def n31(a: int) -> tuple[list[int], int]: """ Returns the Collatz sequence and its length of any positive integer. >>> n31(4) ([4, 2, 1], 3) """ if not isinstance(a, int): raise TypeError("Must be int, not {}".format(type(a).__name__)) if a < 1: raise ValueError(f"Given integer must be greater than 1, not {a}") path = [a] while a != 1: if a % 2 == 0: a = a // 2 else: a = 3 * a + 1 path += [a] return path, len(path) def test_n31(): """ >>> test_n31() """ assert n31(4) == ([4, 2, 1], 3) assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15) assert n31(31) == ( [ 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, ], 107, ) if __name__ == "__main__": num = 4 path, length = n31(num) print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
from __future__ import annotations def n31(a: int) -> tuple[list[int], int]: """ Returns the Collatz sequence and its length of any positive integer. >>> n31(4) ([4, 2, 1], 3) """ if not isinstance(a, int): raise TypeError(f"Must be int, not {type(a).__name__}") if a < 1: raise ValueError(f"Given integer must be greater than 1, not {a}") path = [a] while a != 1: if a % 2 == 0: a = a // 2 else: a = 3 * a + 1 path += [a] return path, len(path) def test_n31(): """ >>> test_n31() """ assert n31(4) == ([4, 2, 1], 3) assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15) assert n31(31) == ( [ 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, ], 107, ) if __name__ == "__main__": num = 4 path, length = n31(num) print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solutions = quadratic_roots(a=5, b=6, c=1) print("The solutions are: {} and {}".format(*solutions)) if __name__ == "__main__": main()
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a, matrix_b): matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n): return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n): """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n): """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for i in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main(): fmt = ( "{} fibonacci number using matrix exponentiation is {} and using bruteforce " "is {}\n" ) for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print(fmt.format(ordinal, nth_fibonacci_matrix(n), nth_fibonacci_bruteforce(n))) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": main()
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a, matrix_b): matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n): return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n): """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n): """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for i in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main(): for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: raise TypeError( "Unsupported type given for another ({})".format(type(another)) ) def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison print("(a + uv^T)^(-1) is {}".format(ainv.ShermanMorrison(u, v))) def test2(): import doctest doctest.testmod() test2()
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: raise TypeError(f"Unsupported type given for another ({type(another)})") def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") def test2(): import doctest doctest.testmod() test2()
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a Python implementation of the levenshtein distance. Levenshtein distance is a string metric for measuring the difference between two sequences. For doctests run following command: python -m doctest -v levenshtein-distance.py or python3 -m doctest -v levenshtein-distance.py For manual testing run: python levenshtein-distance.py """ def levenshtein_distance(first_word: str, second_word: str) -> int: """Implementation of the levenshtein distance in Python. :param first_word: the first word to measure the difference. :param second_word: the second word to measure the difference. :return: the levenshtein distance between the two words. Examples: >>> levenshtein_distance("planet", "planetary") 3 >>> levenshtein_distance("", "test") 4 >>> levenshtein_distance("book", "back") 2 >>> levenshtein_distance("book", "book") 0 >>> levenshtein_distance("test", "") 4 >>> levenshtein_distance("", "") 0 >>> levenshtein_distance("orchestration", "container") 10 """ # The longer word should come first if len(first_word) < len(second_word): return levenshtein_distance(second_word, first_word) if len(second_word) == 0: return len(first_word) previous_row = range(len(second_word) + 1) for i, c1 in enumerate(first_word): current_row = [i + 1] for j, c2 in enumerate(second_word): # Calculate insertions, deletions and substitutions insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) # Get the minimum to append to the current row current_row.append(min(insertions, deletions, substitutions)) # Store the previous row previous_row = current_row # Returns the last element (distance) return previous_row[-1] if __name__ == "__main__": first_word = input("Enter the first word:\n").strip() second_word = input("Enter the second word:\n").strip() result = levenshtein_distance(first_word, second_word) print( "Levenshtein distance between {} and {} is {}".format( first_word, second_word, result ) )
""" This is a Python implementation of the levenshtein distance. Levenshtein distance is a string metric for measuring the difference between two sequences. For doctests run following command: python -m doctest -v levenshtein-distance.py or python3 -m doctest -v levenshtein-distance.py For manual testing run: python levenshtein-distance.py """ def levenshtein_distance(first_word: str, second_word: str) -> int: """Implementation of the levenshtein distance in Python. :param first_word: the first word to measure the difference. :param second_word: the second word to measure the difference. :return: the levenshtein distance between the two words. Examples: >>> levenshtein_distance("planet", "planetary") 3 >>> levenshtein_distance("", "test") 4 >>> levenshtein_distance("book", "back") 2 >>> levenshtein_distance("book", "book") 0 >>> levenshtein_distance("test", "") 4 >>> levenshtein_distance("", "") 0 >>> levenshtein_distance("orchestration", "container") 10 """ # The longer word should come first if len(first_word) < len(second_word): return levenshtein_distance(second_word, first_word) if len(second_word) == 0: return len(first_word) previous_row = range(len(second_word) + 1) for i, c1 in enumerate(first_word): current_row = [i + 1] for j, c2 in enumerate(second_word): # Calculate insertions, deletions and substitutions insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) # Get the minimum to append to the current row current_row.append(min(insertions, deletions, substitutions)) # Store the previous row previous_row = current_row # Returns the last element (distance) return previous_row[-1] if __name__ == "__main__": first_word = input("Enter the first word:\n").strip() second_word = input("Enter the second word:\n").strip() result = levenshtein_distance(first_word, second_word) print(f"Levenshtein distance between {first_word} and {second_word} is {result}")
1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] 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 quick sort algorithm For doctests run following command: python -m doctest -v radix_sort.py or python3 -m doctest -v radix_sort.py For manual testing run: python radix_sort.py """ from __future__ import annotations from typing import List def radix_sort(list_of_ints: List[int]) -> List[int]: """ Examples: >>> radix_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> radix_sort(list(range(15))) == sorted(range(15)) True >>> radix_sort(list(range(14,-1,-1))) == sorted(range(15)) True >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000]) True """ RADIX = 10 placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets buckets = [list() for _ in range(RADIX)] # split list_of_ints between the buckets for i in list_of_ints: tmp = int((i / placement) % RADIX) buckets[tmp].append(i) # put each buckets' contents into list_of_ints a = 0 for b in range(RADIX): for i in buckets[b]: list_of_ints[a] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
""" This is a pure Python implementation of the quick sort algorithm For doctests run following command: python -m doctest -v radix_sort.py or python3 -m doctest -v radix_sort.py For manual testing run: python radix_sort.py """ from __future__ import annotations from typing import List def radix_sort(list_of_ints: List[int]) -> List[int]: """ Examples: >>> radix_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> radix_sort(list(range(15))) == sorted(range(15)) True >>> radix_sort(list(range(14,-1,-1))) == sorted(range(15)) True >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000]) True """ RADIX = 10 placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets buckets = [list() for _ in range(RADIX)] # split list_of_ints between the buckets for i in list_of_ints: tmp = int((i / placement) % RADIX) buckets[tmp].append(i) # put each buckets' contents into list_of_ints a = 0 for b in range(RADIX): for i in buckets[b]: list_of_ints[a] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Python program to implement Morse Code Translator # Dictionary representing the morse code chart MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", # Exclamation mark is not in ITU-R recommendation "!": "-.-.--", } def encrypt(message: str) -> str: cipher = "" for letter in message: if letter != " ": cipher += MORSE_CODE_DICT[letter] + " " else: cipher += "/ " # Remove trailing space added on line 64 return cipher[:-1] def decrypt(message: str) -> str: decipher = "" letters = message.split(" ") for letter in letters: if letter != "/": decipher += list(MORSE_CODE_DICT.keys())[ list(MORSE_CODE_DICT.values()).index(letter) ] else: decipher += " " return decipher def main(): message = "Morse code here" result = encrypt(message.upper()) print(result) message = result result = decrypt(message) print(result) if __name__ == "__main__": main()
# Python program to implement Morse Code Translator # Dictionary representing the morse code chart MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", # Exclamation mark is not in ITU-R recommendation "!": "-.-.--", } def encrypt(message: str) -> str: cipher = "" for letter in message: if letter != " ": cipher += MORSE_CODE_DICT[letter] + " " else: cipher += "/ " # Remove trailing space added on line 64 return cipher[:-1] def decrypt(message: str) -> str: decipher = "" letters = message.split(" ") for letter in letters: if letter != "/": decipher += list(MORSE_CODE_DICT.keys())[ list(MORSE_CODE_DICT.values()).index(letter) ] else: decipher += " " return decipher def main(): message = "Morse code here" result = encrypt(message.upper()) print(result) message = result result = decrypt(message) print(result) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Kadane's algorithm to get maximum subarray sum https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d https://en.wikipedia.org/wiki/Maximum_subarray_problem """ test_data: tuple = ([-2, -8, -9], [2, 8, 9], [-1, 0, 1], [0, 0], []) def negative_exist(arr: list) -> int: """ >>> negative_exist([-2,-8,-9]) -2 >>> [negative_exist(arr) for arr in test_data] [-2, 0, 0, 0, 0] """ arr = arr or [0] max = arr[0] for i in arr: if i >= 0: return 0 elif max <= i: max = i return max def kadanes(arr: list) -> int: """ If negative_exist() returns 0 than this function will execute else it will return the value return by negative_exist function For example: arr = [2, 3, -9, 8, -2] Initially we set value of max_sum to 0 and max_till_element to 0 than when max_sum is less than max_till particular element it will assign that value to max_sum and when value of max_till_sum is less than 0 it will assign 0 to i and after that whole process, return the max_sum So the output for above arr is 8 >>> kadanes([2, 3, -9, 8, -2]) 8 >>> [kadanes(arr) for arr in test_data] [-2, 19, 1, 0, 0] """ max_sum = negative_exist(arr) if max_sum < 0: return max_sum max_sum = 0 max_till_element = 0 for i in arr: max_till_element += i if max_sum <= max_till_element: max_sum = max_till_element if max_till_element < 0: max_till_element = 0 return max_sum if __name__ == "__main__": try: print("Enter integer values sepatated by spaces") arr = [int(x) for x in input().split()] print(f"Maximum subarray sum of {arr} is {kadanes(arr)}") except ValueError: print("Please enter integer values.")
""" Kadane's algorithm to get maximum subarray sum https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d https://en.wikipedia.org/wiki/Maximum_subarray_problem """ test_data: tuple = ([-2, -8, -9], [2, 8, 9], [-1, 0, 1], [0, 0], []) def negative_exist(arr: list) -> int: """ >>> negative_exist([-2,-8,-9]) -2 >>> [negative_exist(arr) for arr in test_data] [-2, 0, 0, 0, 0] """ arr = arr or [0] max = arr[0] for i in arr: if i >= 0: return 0 elif max <= i: max = i return max def kadanes(arr: list) -> int: """ If negative_exist() returns 0 than this function will execute else it will return the value return by negative_exist function For example: arr = [2, 3, -9, 8, -2] Initially we set value of max_sum to 0 and max_till_element to 0 than when max_sum is less than max_till particular element it will assign that value to max_sum and when value of max_till_sum is less than 0 it will assign 0 to i and after that whole process, return the max_sum So the output for above arr is 8 >>> kadanes([2, 3, -9, 8, -2]) 8 >>> [kadanes(arr) for arr in test_data] [-2, 19, 1, 0, 0] """ max_sum = negative_exist(arr) if max_sum < 0: return max_sum max_sum = 0 max_till_element = 0 for i in arr: max_till_element += i if max_sum <= max_till_element: max_sum = max_till_element if max_till_element < 0: max_till_element = 0 return max_sum if __name__ == "__main__": try: print("Enter integer values sepatated by spaces") arr = [int(x) for x in input().split()] print(f"Maximum subarray sum of {arr} is {kadanes(arr)}") except ValueError: print("Please enter integer values.")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 2.0) * f(a) for i in x_i: # print(i) y += h * f(i) y += (h / 2.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_1(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 2.0) * f(a) for i in x_i: # print(i) y += h * f(i) y += (h / 2.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_1(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def printDist(dist, V): print("\nVertex Distance") for i in range(V): if dist[i] != float("inf"): print(i, "\t", int(dist[i]), end="\t") else: print(i, "\t", "INF", end="\t") print() def minDist(mdist, vset, V): minVal = float("inf") minInd = -1 for i in range(V): if (not vset[i]) and mdist[i] < minVal: minInd = i minVal = mdist[i] return minInd def Dijkstra(graph, V, src): mdist = [float("inf") for i in range(V)] vset = [False for i in range(V)] mdist[src] = 0.0 for i in range(V - 1): u = minDist(mdist, vset, V) vset[u] = True for v in range(V): if ( (not vset[v]) and graph[u][v] != float("inf") and mdist[u] + graph[u][v] < mdist[v] ): mdist[v] = mdist[u] + graph[u][v] printDist(mdist, V) if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph = [[float("inf") for i in range(V)] for j in range(V)] for i in range(V): graph[i][i] = 0.0 for i in range(E): print("\nEdge ", i + 1) src = int(input("Enter source:").strip()) dst = int(input("Enter destination:").strip()) weight = float(input("Enter weight:").strip()) graph[src][dst] = weight gsrc = int(input("\nEnter shortest path source:").strip()) Dijkstra(graph, V, gsrc)
def printDist(dist, V): print("\nVertex Distance") for i in range(V): if dist[i] != float("inf"): print(i, "\t", int(dist[i]), end="\t") else: print(i, "\t", "INF", end="\t") print() def minDist(mdist, vset, V): minVal = float("inf") minInd = -1 for i in range(V): if (not vset[i]) and mdist[i] < minVal: minInd = i minVal = mdist[i] return minInd def Dijkstra(graph, V, src): mdist = [float("inf") for i in range(V)] vset = [False for i in range(V)] mdist[src] = 0.0 for i in range(V - 1): u = minDist(mdist, vset, V) vset[u] = True for v in range(V): if ( (not vset[v]) and graph[u][v] != float("inf") and mdist[u] + graph[u][v] < mdist[v] ): mdist[v] = mdist[u] + graph[u][v] printDist(mdist, V) if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph = [[float("inf") for i in range(V)] for j in range(V)] for i in range(V): graph[i][i] = 0.0 for i in range(E): print("\nEdge ", i + 1) src = int(input("Enter source:").strip()) dst = int(input("Enter destination:").strip()) weight = float(input("Enter weight:").strip()) graph[src][dst] = weight gsrc = int(input("\nEnter shortest path source:").strip()) Dijkstra(graph, V, gsrc)
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_or(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. >>> binary_or(25, 32) '0b111001' >>> binary_or(37, 50) '0b110111' >>> binary_or(21, 30) '0b11111' >>> binary_or(58, 73) '0b1111011' >>> binary_or(0, 255) '0b11111111' >>> binary_or(0, 256) '0b100000000' >>> binary_or(0, -1) Traceback (most recent call last): ... ValueError: the value of both input must be positive >>> binary_or(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_or("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both input must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int("1" in (char_a, char_b))) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_or(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. >>> binary_or(25, 32) '0b111001' >>> binary_or(37, 50) '0b110111' >>> binary_or(21, 30) '0b11111' >>> binary_or(58, 73) '0b1111011' >>> binary_or(0, 255) '0b11111111' >>> binary_or(0, 256) '0b100000000' >>> binary_or(0, -1) Traceback (most recent call last): ... ValueError: the value of both input must be positive >>> binary_or(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_or("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both input must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int("1" in (char_a, char_b))) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(0, kernel_size): for j in range(0, kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gaussKer = get_gauss_kernel(kernel_size, spatial_variance) sizeX, sizeY = img.shape for i in range(kernel_size // 2, sizeX - kernel_size // 2): for j in range(kernel_size // 2, sizeY - kernel_size // 2): imgS = get_slice(img, i, j, kernel_size) imgI = imgS - imgS[kernel_size // 2, kernel_size // 2] imgIG = vec_gaussian(imgI, intensity_variance) weights = np.multiply(gaussKer, imgIG) vals = np.multiply(imgS, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(0, kernel_size): for j in range(0, kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gaussKer = get_gauss_kernel(kernel_size, spatial_variance) sizeX, sizeY = img.shape for i in range(kernel_size // 2, sizeX - kernel_size // 2): for j in range(kernel_size // 2, sizeY - kernel_size // 2): imgS = get_slice(img, i, j, kernel_size) imgI = imgS - imgS[kernel_size // 2, kernel_size // 2] imgIG = vec_gaussian(imgI, intensity_variance) weights = np.multiply(gaussKer, imgIG) vals = np.multiply(imgS, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Get the citation from google scholar using title and year of publication, and volume and pages of journal. """ import requests from bs4 import BeautifulSoup def get_citation(base_url: str, params: dict) -> str: """ Return the citation number. """ soup = BeautifulSoup(requests.get(base_url, params=params).content, "html.parser") div = soup.find("div", attrs={"class": "gs_ri"}) anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") return anchors[2].get_text() if __name__ == "__main__": params = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 30, "pages": "3979-3990", "year": 2018, "hl": "en", } print(get_citation("http://scholar.google.com/scholar_lookup", params=params))
""" Get the citation from google scholar using title and year of publication, and volume and pages of journal. """ import requests from bs4 import BeautifulSoup def get_citation(base_url: str, params: dict) -> str: """ Return the citation number. """ soup = BeautifulSoup(requests.get(base_url, params=params).content, "html.parser") div = soup.find("div", attrs={"class": "gs_ri"}) anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") return anchors[2].get_text() if __name__ == "__main__": params = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 30, "pages": "3979-3990", "year": 2018, "hl": "en", } print(get_citation("http://scholar.google.com/scholar_lookup", params=params))
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Python program for generating diamond pattern in Python 3.7+ # Function to print upper half of diamond (pyramid) def floyd(n): """ Parameters: n : size of pattern """ for i in range(0, n): for j in range(0, n - i - 1): # printing spaces print(" ", end="") for k in range(0, i + 1): # printing stars print("* ", end="") print() # Function to print lower half of diamond (pyramid) def reverse_floyd(n): """ Parameters: n : size of pattern """ for i in range(n, 0, -1): for j in range(i, 0, -1): # printing stars print("* ", end="") print() for k in range(n - i + 1, 0, -1): # printing spaces print(" ", end="") # Function to print complete diamond pattern of "*" def pretty_print(n): """ Parameters: n : size of pattern """ if n <= 0: print(" ... .... nothing printing :(") return floyd(n) # upper half reverse_floyd(n) # lower half if __name__ == "__main__": print(r"| /\ | |- | |- |--| |\ /| |-") print(r"|/ \| |- |_ |_ |__| | \/ | |_") K = 1 while K: user_number = int(input("enter the number and , and see the magic : ")) print() pretty_print(user_number) K = int(input("press 0 to exit... and 1 to continue...")) print("Good Bye...")
# Python program for generating diamond pattern in Python 3.7+ # Function to print upper half of diamond (pyramid) def floyd(n): """ Parameters: n : size of pattern """ for i in range(0, n): for j in range(0, n - i - 1): # printing spaces print(" ", end="") for k in range(0, i + 1): # printing stars print("* ", end="") print() # Function to print lower half of diamond (pyramid) def reverse_floyd(n): """ Parameters: n : size of pattern """ for i in range(n, 0, -1): for j in range(i, 0, -1): # printing stars print("* ", end="") print() for k in range(n - i + 1, 0, -1): # printing spaces print(" ", end="") # Function to print complete diamond pattern of "*" def pretty_print(n): """ Parameters: n : size of pattern """ if n <= 0: print(" ... .... nothing printing :(") return floyd(n) # upper half reverse_floyd(n) # lower half if __name__ == "__main__": print(r"| /\ | |- | |- |--| |\ /| |-") print(r"|/ \| |- |_ |_ |__| | \/ | |_") K = 1 while K: user_number = int(input("enter the number and , and see the magic : ")) print() pretty_print(user_number) K = int(input("press 0 to exit... and 1 to continue...")) print("Good Bye...")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The function below will convert any binary string to the octal equivalent. >>> bin_to_octal("1111") '17' >>> bin_to_octal("101010101010011") '52523' >>> bin_to_octal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_octal("a-1") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ def bin_to_octal(bin_string: str) -> str: if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") if not bin_string: raise ValueError("Empty string was passed to the function") oct_string = "" while len(bin_string) % 3 != 0: bin_string = "0" + bin_string bin_string_in_3_list = [ bin_string[index : index + 3] for index, value in enumerate(bin_string) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: oct_val = 0 for index, val in enumerate(bin_group): oct_val += int(2 ** (2 - index) * int(val)) oct_string += str(oct_val) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
""" The function below will convert any binary string to the octal equivalent. >>> bin_to_octal("1111") '17' >>> bin_to_octal("101010101010011") '52523' >>> bin_to_octal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_octal("a-1") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ def bin_to_octal(bin_string: str) -> str: if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") if not bin_string: raise ValueError("Empty string was passed to the function") oct_string = "" while len(bin_string) % 3 != 0: bin_string = "0" + bin_string bin_string_in_3_list = [ bin_string[index : index + 3] for index, value in enumerate(bin_string) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: oct_val = 0 for index, val in enumerate(bin_group): oct_val += int(2 ** (2 - index) * int(val)) oct_string += str(oct_val) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transpostiion sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transpostiion sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Created on Thu Oct 5 16:44:23 2017 @author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: isPrime(number) sieveEr(N) getPrimeNumbers(N) primeFactorization(number) greatestPrimeFactor(number) smallestPrimeFactor(number) getPrime(n) getPrimesBetween(pNumber1, pNumber2) ---- isEven(number) isOdd(number) gcd(number1, number2) // greatest common divisor kgV(number1, number2) // least common multiple getDivisors(number) // all divisors of 'number' inclusive 1, number isPerfectNumber(number) NEW-FUNCTIONS simplifyFraction(numerator, denominator) factorial (n) // n! fib (n) // calculate the n-th fibonacci term. ----- goldbach(number) // Goldbach's assumption """ from math import sqrt def isPrime(number): """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status # ------------------------------------------ def sieveEr(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N beginList = [x for x in range(2, N + 1)] ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(beginList)): for j in range(i + 1, len(beginList)): if (beginList[i] != 0) and (beginList[j] % beginList[i] == 0): beginList[j] = 0 # filters actual prime numbers. ans = [x for x in beginList if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def getPrimeNumbers(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, N + 1): if isPrime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def primeFactorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): while quotient != 1: if isPrime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def greatestPrimeFactor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = max(primeFactors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallestPrimeFactor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = min(primeFactors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def isEven(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0 # ------------------------ def isOdd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ # precondition assert ( isinstance(number, int) and (number > 2) and isEven(number) ), "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' primeNumbers = getPrimeNumbers(number) lenPN = len(primeNumbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < lenPN and loop: j = i + 1 while j < lenPN and loop: if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) ans.append(primeNumbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def gcd(number1, number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 0) and (number2 >= 0) ), "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1, int) and ( number1 >= 0 ), "'number' must been from type int and positive" return number1 # ---------------------------------------------------- def kgV(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) elif number1 == 1 or number2 == 1: primeFac1 = [] primeFac2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in primeFac1: if n not in done: if n in primeFac2: count1 = primeFac1.count(n) count2 = primeFac2.count(n) for i in range(max(count1, count2)): ans *= n else: count1 = primeFac1.count(n) for i in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in primeFac2: if n not in done: count2 = primeFac2.count(n) for i in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans # ---------------------------------- def getPrime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not isPrime(ans): ans += 1 # precondition assert isinstance(ans, int) and isPrime( ans ), "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- def getPrimesBetween(pNumber1, pNumber2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusive) and 'pNumber2' (exclusive) """ # precondition assert ( isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = pNumber1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not isPrime(number): number += 1 while number < pNumber2: ans.append(number) number += 1 # fetch the next prime number. while not isPrime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != pNumber1 and ans[len(ans) - 1] != pNumber2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def getDivisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def isPerfectNumber(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplifyFraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. """ # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcdOfFraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) and (denominator % gcdOfFraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcdOfFraction, denominator // gcdOfFraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for i in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans
""" Created on Thu Oct 5 16:44:23 2017 @author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: isPrime(number) sieveEr(N) getPrimeNumbers(N) primeFactorization(number) greatestPrimeFactor(number) smallestPrimeFactor(number) getPrime(n) getPrimesBetween(pNumber1, pNumber2) ---- isEven(number) isOdd(number) gcd(number1, number2) // greatest common divisor kgV(number1, number2) // least common multiple getDivisors(number) // all divisors of 'number' inclusive 1, number isPerfectNumber(number) NEW-FUNCTIONS simplifyFraction(numerator, denominator) factorial (n) // n! fib (n) // calculate the n-th fibonacci term. ----- goldbach(number) // Goldbach's assumption """ from math import sqrt def isPrime(number): """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status # ------------------------------------------ def sieveEr(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N beginList = [x for x in range(2, N + 1)] ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(beginList)): for j in range(i + 1, len(beginList)): if (beginList[i] != 0) and (beginList[j] % beginList[i] == 0): beginList[j] = 0 # filters actual prime numbers. ans = [x for x in beginList if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def getPrimeNumbers(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, N + 1): if isPrime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def primeFactorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): while quotient != 1: if isPrime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def greatestPrimeFactor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = max(primeFactors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallestPrimeFactor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = min(primeFactors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def isEven(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0 # ------------------------ def isOdd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ # precondition assert ( isinstance(number, int) and (number > 2) and isEven(number) ), "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' primeNumbers = getPrimeNumbers(number) lenPN = len(primeNumbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < lenPN and loop: j = i + 1 while j < lenPN and loop: if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) ans.append(primeNumbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def gcd(number1, number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 0) and (number2 >= 0) ), "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1, int) and ( number1 >= 0 ), "'number' must been from type int and positive" return number1 # ---------------------------------------------------- def kgV(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) elif number1 == 1 or number2 == 1: primeFac1 = [] primeFac2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in primeFac1: if n not in done: if n in primeFac2: count1 = primeFac1.count(n) count2 = primeFac2.count(n) for i in range(max(count1, count2)): ans *= n else: count1 = primeFac1.count(n) for i in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in primeFac2: if n not in done: count2 = primeFac2.count(n) for i in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans # ---------------------------------- def getPrime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not isPrime(ans): ans += 1 # precondition assert isinstance(ans, int) and isPrime( ans ), "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- def getPrimesBetween(pNumber1, pNumber2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusive) and 'pNumber2' (exclusive) """ # precondition assert ( isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = pNumber1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not isPrime(number): number += 1 while number < pNumber2: ans.append(number) number += 1 # fetch the next prime number. while not isPrime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != pNumber1 and ans[len(ans) - 1] != pNumber2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def getDivisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def isPerfectNumber(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplifyFraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. """ # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcdOfFraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) and (denominator % gcdOfFraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcdOfFraction, denominator // gcdOfFraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for i in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.m.wikipedia.org/wiki/Electric_power from collections import namedtuple def electric_power(voltage: float, current: float, power: float) -> float: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): File "<stdin>", line 15, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): File "<stdin>", line 19, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): File "<stdin>", line 23, in <modulei ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) result(name='power', value=4.84) """ result = namedtuple("result", "name value") if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage", power / current) elif current == 0: return result("current", power / voltage) elif power == 0: return result("power", float(round(abs(voltage * current), 2))) if __name__ == "__main__": import doctest doctest.testmod()
# https://en.m.wikipedia.org/wiki/Electric_power from collections import namedtuple def electric_power(voltage: float, current: float, power: float) -> float: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): File "<stdin>", line 15, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): File "<stdin>", line 19, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): File "<stdin>", line 23, in <modulei ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) result(name='power', value=4.84) """ result = namedtuple("result", "name value") if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage", power / current) elif current == 0: return result("current", power / voltage) elif power == 0: return result("power", float(round(abs(voltage * current), 2))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ import numpy as np def is_hermitian(matrix: np.array) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(A: np.array, v: np.array) -> float: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T return (v_star.dot(A).dot(v)) / (v_star.dot(v)) def tests() -> None: A = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(A), f"{A} is not hermitian." print(rayleigh_quotient(A, v)) A = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(A), f"{A} is not hermitian." assert rayleigh_quotient(A, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ import numpy as np def is_hermitian(matrix: np.array) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(A: np.array, v: np.array) -> float: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T return (v_star.dot(A).dot(v)) / (v_star.dot(v)) def tests() -> None: A = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(A), f"{A} is not hermitian." print(rayleigh_quotient(A, v)) A = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(A), f"{A} is not hermitian." assert rayleigh_quotient(A, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p < len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
""" Implementation of iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p < len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import List def merge(left_half: List, right_half: List) -> List: """Helper function for mergesort. >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [1,2,3] >>> right_half = [4,5,6] >>> merge(left_half, right_half) [1, 2, 3, 4, 5, 6] >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [12, 15] >>> right_half = [13, 14] >>> merge(left_half, right_half) [12, 13, 14, 15] >>> left_half = [] >>> right_half = [] >>> merge(left_half, right_half) [] """ sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half pointer2 = 0 # pointer to current index for the right Half index = 0 # pointer to current index for the sorted array Half while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: List) -> List: """Returns a list of sorted array elements using merge sort. >>> from random import shuffle >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> array = [-200] >>> merge_sort(array) [-200] >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> sorted(array) == merge_sort(array) True >>> array = [-2] >>> merge_sort(array) [-2] >>> array = [] >>> merge_sort(array) [] >>> array = [10000000, 1, -1111111111, 101111111112, 9000002] >>> sorted(array) == merge_sort(array) True """ if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 # this avoids integer overflow in case of large N middle = 0 + (len(array) - 0) // 2 # Split the array into halves till the array length becomes equal to One # merge the arrays of single length returned by mergeSort function and # pass them into the merge arrays function which merges the array left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
from typing import List def merge(left_half: List, right_half: List) -> List: """Helper function for mergesort. >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [1,2,3] >>> right_half = [4,5,6] >>> merge(left_half, right_half) [1, 2, 3, 4, 5, 6] >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [12, 15] >>> right_half = [13, 14] >>> merge(left_half, right_half) [12, 13, 14, 15] >>> left_half = [] >>> right_half = [] >>> merge(left_half, right_half) [] """ sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half pointer2 = 0 # pointer to current index for the right Half index = 0 # pointer to current index for the sorted array Half while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: List) -> List: """Returns a list of sorted array elements using merge sort. >>> from random import shuffle >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> array = [-200] >>> merge_sort(array) [-200] >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> sorted(array) == merge_sort(array) True >>> array = [-2] >>> merge_sort(array) [-2] >>> array = [] >>> merge_sort(array) [] >>> array = [10000000, 1, -1111111111, 101111111112, 9000002] >>> sorted(array) == merge_sort(array) True """ if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 # this avoids integer overflow in case of large N middle = 0 + (len(array) - 0) // 2 # Split the array into halves till the array length becomes equal to One # merge the arrays of single length returned by mergeSort function and # pass them into the merge arrays function which merges the array left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 38: https://projecteuler.net/problem=38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? Solution: Since n>1, the largest candidate for the solution will be a concactenation of a 4-digit number and its double, a 5-digit number. Let a be the 4-digit number. a has 4 digits => 1000 <= a < 10000 2a has 5 digits => 10000 <= 2a < 100000 => 5000 <= a < 10000 The concatenation of a with 2a = a * 10^5 + 2a so our candidate for a given a is 100002 * a. We iterate through the search space 5000 <= a < 10000 in reverse order, calculating the candidates for each a and checking if they are 1-9 pandigital. In case there are no 4-digit numbers that satisfy this property, we check the 3-digit numbers with a similar formula (the example a=192 gives a lower bound on the length of a): a has 3 digits, etc... => 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a = 1002003 * a """ from typing import Union def is_9_pandigital(n: int) -> bool: """ Checks whether n is a 9-digit 1 to 9 pandigital number. >>> is_9_pandigital(12345) False >>> is_9_pandigital(156284973) True >>> is_9_pandigital(1562849733) False """ s = str(n) return len(s) == 9 and set(s) == set("123456789") def solution() -> Union[int, None]: """ Return the largest 1 to 9 pandigital 9-digital number that can be formed as the concatenated product of an integer with (1,2,...,n) where n > 1. """ for base_num in range(9999, 4999, -1): candidate = 100002 * base_num if is_9_pandigital(candidate): return candidate for base_num in range(333, 99, -1): candidate = 1002003 * base_num if is_9_pandigital(candidate): return candidate return None if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 38: https://projecteuler.net/problem=38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? Solution: Since n>1, the largest candidate for the solution will be a concactenation of a 4-digit number and its double, a 5-digit number. Let a be the 4-digit number. a has 4 digits => 1000 <= a < 10000 2a has 5 digits => 10000 <= 2a < 100000 => 5000 <= a < 10000 The concatenation of a with 2a = a * 10^5 + 2a so our candidate for a given a is 100002 * a. We iterate through the search space 5000 <= a < 10000 in reverse order, calculating the candidates for each a and checking if they are 1-9 pandigital. In case there are no 4-digit numbers that satisfy this property, we check the 3-digit numbers with a similar formula (the example a=192 gives a lower bound on the length of a): a has 3 digits, etc... => 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a = 1002003 * a """ from typing import Union def is_9_pandigital(n: int) -> bool: """ Checks whether n is a 9-digit 1 to 9 pandigital number. >>> is_9_pandigital(12345) False >>> is_9_pandigital(156284973) True >>> is_9_pandigital(1562849733) False """ s = str(n) return len(s) == 9 and set(s) == set("123456789") def solution() -> Union[int, None]: """ Return the largest 1 to 9 pandigital 9-digital number that can be formed as the concatenated product of an integer with (1,2,...,n) where n > 1. """ for base_num in range(9999, 4999, -1): candidate = 100002 * base_num if is_9_pandigital(candidate): return candidate for base_num in range(333, 99, -1): candidate = 1002003 * base_num if is_9_pandigital(candidate): return candidate return None if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. """ from typing import List, Union def generate_all_permutations(sequence: List[Union[int, str]]) -> None: create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree( sequence: List[Union[int, str]], current_sequence: List[Union[int, str]], index: int, index_used: List[int], ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: List[Union[int, str]] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: List[Union[int, str]] = ["A", "B", "C"] generate_all_permutations(sequence_2)
""" In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. """ from typing import List, Union def generate_all_permutations(sequence: List[Union[int, str]]) -> None: create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree( sequence: List[Union[int, str]], current_sequence: List[Union[int, str]], index: int, index_used: List[int], ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: List[Union[int, str]] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: List[Union[int, str]] = ["A", "B", "C"] generate_all_permutations(sequence_2)
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def stable_matching(donor_pref: list[int], recipient_pref: list[int]) -> list[int]: """ Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects prefer each other over their partner. The function accepts the preferences of oegan donors and recipients (where both are assigned numbers from 0 to n-1) and returns a list where the index position corresponds to the donor and value at the index is the organ recipient. To better understand the algorithm, see also: https://github.com/akashvshroff/Gale_Shapley_Stable_Matching (README). https://www.youtube.com/watch?v=Qcv1IqHWAzg&t=13s (Numberphile YouTube). >>> donor_pref = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 0, 2, 3], [0, 3, 1, 2]] >>> recipient_pref = [[3, 1, 2, 0], [3, 1, 0, 2], [0, 3, 1, 2], [1, 0, 3, 2]] >>> print(stable_matching(donor_pref, recipient_pref)) [1, 2, 3, 0] """ assert len(donor_pref) == len(recipient_pref) n = len(donor_pref) unmatched_donors = list(range(n)) donor_record = [-1] * n # who the donor has donated to rec_record = [-1] * n # who the recipient has received from num_donations = [0] * n while unmatched_donors: donor = unmatched_donors[0] donor_preference = donor_pref[donor] recipient = donor_preference[num_donations[donor]] num_donations[donor] += 1 rec_preference = recipient_pref[recipient] prev_donor = rec_record[recipient] if prev_donor != -1: if rec_preference.index(prev_donor) > rec_preference.index(donor): rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.append(prev_donor) unmatched_donors.remove(donor) else: rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.remove(donor) return donor_record
from __future__ import annotations def stable_matching(donor_pref: list[int], recipient_pref: list[int]) -> list[int]: """ Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects prefer each other over their partner. The function accepts the preferences of oegan donors and recipients (where both are assigned numbers from 0 to n-1) and returns a list where the index position corresponds to the donor and value at the index is the organ recipient. To better understand the algorithm, see also: https://github.com/akashvshroff/Gale_Shapley_Stable_Matching (README). https://www.youtube.com/watch?v=Qcv1IqHWAzg&t=13s (Numberphile YouTube). >>> donor_pref = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 0, 2, 3], [0, 3, 1, 2]] >>> recipient_pref = [[3, 1, 2, 0], [3, 1, 0, 2], [0, 3, 1, 2], [1, 0, 3, 2]] >>> print(stable_matching(donor_pref, recipient_pref)) [1, 2, 3, 0] """ assert len(donor_pref) == len(recipient_pref) n = len(donor_pref) unmatched_donors = list(range(n)) donor_record = [-1] * n # who the donor has donated to rec_record = [-1] * n # who the recipient has received from num_donations = [0] * n while unmatched_donors: donor = unmatched_donors[0] donor_preference = donor_pref[donor] recipient = donor_preference[num_donations[donor]] num_donations[donor] += 1 rec_preference = recipient_pref[recipient] prev_donor = rec_record[recipient] if prev_donor != -1: if rec_preference.index(prev_donor) > rec_preference.index(donor): rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.append(prev_donor) unmatched_donors.remove(donor) else: rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.remove(donor) return donor_record
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing sub-array in that given array and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] isFound = False i = 1 longest_subseq = [] while not isFound and i < array_length: if array[i] < pivot: isFound = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot] + longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing sub-array in that given array and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] isFound = False i = 1 longest_subseq = [] while not isFound and i < array_length: if array[i] < pivot: isFound = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot] + longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Code contributed by Honey Sharma Source: https://en.wikipedia.org/wiki/Cycle_sort """ def cycle_sort(array: list) -> list: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0.2, -0.1, 1.3] >>> cycle_sort([]) [] """ array_len = len(array) for cycle_start in range(0, array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: continue while item == array[pos]: pos += 1 array[pos], item = item, array[pos] while pos != cycle_start: pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 while item == array[pos]: pos += 1 array[pos], item = item, array[pos] return array if __name__ == "__main__": assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
""" Code contributed by Honey Sharma Source: https://en.wikipedia.org/wiki/Cycle_sort """ def cycle_sort(array: list) -> list: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0.2, -0.1, 1.3] >>> cycle_sort([]) [] """ array_len = len(array) for cycle_start in range(0, array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: continue while item == array[pos]: pos += 1 array[pos], item = item, array[pos] while pos != cycle_start: pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 while item == array[pos]: pos += 1 array[pos], item = item, array[pos] return array if __name__ == "__main__": assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find Volumes of Various Shapes. Wikipedia reference: https://en.wikipedia.org/wiki/Volume """ from math import pi, pow from typing import Union def vol_cube(side_length: Union[int, float]) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 """ return pow(side_length, 3) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 """ return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 """ return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * pi * radius^2 * height >>> vol_right_circ_cone(2, 3) 12.566370614359172 """ return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Prism. Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return V = Bh >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 """ return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: """ Calculate the Volume of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return (4/3) * pi * r^3 >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 """ return 4 / 3 * pi * pow(radius, 3) def vol_circular_cylinder(radius: float, height: float) -> float: """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return pi * radius^2 * height >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 """ return pi * pow(radius, 2) * height def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print("Cube: " + str(vol_cube(2))) # = 8 print("Cuboid: " + str(vol_cuboid(2, 2, 2))) # = 8 print("Cone: " + str(vol_cone(2, 2))) # ~= 1.33 print("Right Circular Cone: " + str(vol_right_circ_cone(2, 2))) # ~= 8.38 print("Prism: " + str(vol_prism(2, 2))) # = 4 print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33 print("Sphere: " + str(vol_sphere(2))) # ~= 33.5 print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1 if __name__ == "__main__": main()
""" Find Volumes of Various Shapes. Wikipedia reference: https://en.wikipedia.org/wiki/Volume """ from math import pi, pow from typing import Union def vol_cube(side_length: Union[int, float]) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 """ return pow(side_length, 3) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 """ return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 """ return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * pi * radius^2 * height >>> vol_right_circ_cone(2, 3) 12.566370614359172 """ return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Prism. Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return V = Bh >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 """ return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: """ Calculate the Volume of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return (4/3) * pi * r^3 >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 """ return 4 / 3 * pi * pow(radius, 3) def vol_circular_cylinder(radius: float, height: float) -> float: """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return pi * radius^2 * height >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 """ return pi * pow(radius, 2) * height def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print("Cube: " + str(vol_cube(2))) # = 8 print("Cuboid: " + str(vol_cuboid(2, 2, 2))) # = 8 print("Cone: " + str(vol_cone(2, 2))) # ~= 1.33 print("Right Circular Cone: " + str(vol_right_circ_cone(2, 2))) # ~= 8.38 print("Prism: " + str(vol_prism(2, 2))) # = 4 print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33 print("Sphere: " + str(vol_sphere(2))) # ~= 33.5 print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1 if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b if __name__ == "__main__": print(f"{solution() = }")
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Iterable, List, Optional class Heap: """A Max Heap Implementation >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() >>> h.build_max_heap(unsorted) >>> print(h) [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> print(h) [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> print(h) [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> print(h) [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] """ def __init__(self) -> None: self.h: List[float] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> Optional[int]: """ return the parent index of given child """ if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> Optional[int]: """ return the left child index if the left child exists. if not, return None. """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> Optional[int]: """ return the right child index if the right child exists. if not, return None. """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: """ correct a single violation of the heap property in a subtree's root. """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[float]) -> None: """ build max heap from an unsorted array""" self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def max(self) -> float: """ return the max in the heap """ if self.heap_size >= 1: return self.h[0] else: raise Exception("Empty heap") def extract_max(self) -> float: """ get and remove max from heap """ if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: float) -> None: """ insert a new value into the max heap """ self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
from typing import Iterable, List, Optional class Heap: """A Max Heap Implementation >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() >>> h.build_max_heap(unsorted) >>> print(h) [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> print(h) [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> print(h) [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> print(h) [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] """ def __init__(self) -> None: self.h: List[float] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> Optional[int]: """ return the parent index of given child """ if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> Optional[int]: """ return the left child index if the left child exists. if not, return None. """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> Optional[int]: """ return the right child index if the right child exists. if not, return None. """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: """ correct a single violation of the heap property in a subtree's root. """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[float]) -> None: """ build max heap from an unsorted array""" self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def max(self) -> float: """ return the max in the heap """ if self.heap_size >= 1: return self.h[0] else: raise Exception("Empty heap") def extract_max(self) -> float: """ get and remove max from heap """ if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: float) -> None: """ insert a new value into the max heap """ self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = """73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450""" def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = """73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450""" def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Recaptcha is a free captcha service offered by Google in order to secure websites and forms. At https://www.google.com/recaptcha/admin/create you can create new recaptcha keys and see the keys that your have already created. * Keep in mind that recaptcha doesn't work with localhost When you create a recaptcha key, your will get two separate keys: ClientKey & SecretKey. ClientKey should be kept in your site's front end SecretKey should be kept in your site's back end # An example HTML login form with recaptcha tag is shown below <form action="" method="post"> <h2 class="text-center">Log in</h2> {% csrf_token %} <div class="form-group"> <input type="text" name="username" required="required"> </div> <div class="form-group"> <input type="password" name="password" required="required"> </div> <div class="form-group"> <button type="submit">Log in</button> </div> <!-- Below is the recaptcha tag of html --> <div class="g-recaptcha" data-sitekey="ClientKey"></div> </form> <!-- Below is the recaptcha script to be kept inside html tag --> <script src="https://www.google.com/recaptcha/api.js" async defer></script> Below a Django function for the views.py file contains a login form for demonstrating recaptcha verification. """ import requests try: from django.contrib.auth import authenticate, login from django.shortcuts import redirect, render except ImportError: authenticate = login = render = redirect = print def login_using_recaptcha(request): # Enter your recaptcha secret key here secret_key = "secretKey" url = "https://www.google.com/recaptcha/api/siteverify" # when method is not POST, direct user to login page if request.method != "POST": return render(request, "login.html") # from the frontend, get username, password, and client_key username = request.POST.get("username") password = request.POST.get("password") client_key = request.POST.get("g-recaptcha-response") # post recaptcha response to Google's recaptcha api response = requests.post(url, data={"secret": secret_key, "response": client_key}) # if the recaptcha api verified our keys if response.json().get("success", False): # authenticate the user user_in_database = authenticate(request, username=username, password=password) if user_in_database: login(request, user_in_database) return redirect("/your-webpage") return render(request, "login.html")
""" Recaptcha is a free captcha service offered by Google in order to secure websites and forms. At https://www.google.com/recaptcha/admin/create you can create new recaptcha keys and see the keys that your have already created. * Keep in mind that recaptcha doesn't work with localhost When you create a recaptcha key, your will get two separate keys: ClientKey & SecretKey. ClientKey should be kept in your site's front end SecretKey should be kept in your site's back end # An example HTML login form with recaptcha tag is shown below <form action="" method="post"> <h2 class="text-center">Log in</h2> {% csrf_token %} <div class="form-group"> <input type="text" name="username" required="required"> </div> <div class="form-group"> <input type="password" name="password" required="required"> </div> <div class="form-group"> <button type="submit">Log in</button> </div> <!-- Below is the recaptcha tag of html --> <div class="g-recaptcha" data-sitekey="ClientKey"></div> </form> <!-- Below is the recaptcha script to be kept inside html tag --> <script src="https://www.google.com/recaptcha/api.js" async defer></script> Below a Django function for the views.py file contains a login form for demonstrating recaptcha verification. """ import requests try: from django.contrib.auth import authenticate, login from django.shortcuts import redirect, render except ImportError: authenticate = login = render = redirect = print def login_using_recaptcha(request): # Enter your recaptcha secret key here secret_key = "secretKey" url = "https://www.google.com/recaptcha/api/siteverify" # when method is not POST, direct user to login page if request.method != "POST": return render(request, "login.html") # from the frontend, get username, password, and client_key username = request.POST.get("username") password = request.POST.get("password") client_key = request.POST.get("g-recaptcha-response") # post recaptcha response to Google's recaptcha api response = requests.post(url, data={"secret": secret_key, "response": client_key}) # if the recaptcha api verified our keys if response.json().get("success", False): # authenticate the user user_in_database = authenticate(request, username=username, password=password) if user_in_database: login(request, user_in_database) return redirect("/your-webpage") return render(request, "login.html")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find the area of various geometric shapes """ from math import pi, sqrt def surface_area_cube(side_length: float) -> float: """ Calculate the Surface Area of a Cube. >>> surface_area_cube(1) 6 >>> surface_area_cube(3) 54 >>> surface_area_cube(-1) Traceback (most recent call last): ... ValueError: surface_area_cube() only accepts non-negative values """ if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values") return 6 * side_length ** 2 def surface_area_sphere(radius: float) -> float: """ Calculate the Surface Area of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere Formula: 4 * pi * r^2 >>> surface_area_sphere(5) 314.1592653589793 >>> surface_area_sphere(1) 12.566370614359172 >>> surface_area_sphere(-1) Traceback (most recent call last): ... ValueError: surface_area_sphere() only accepts non-negative values """ if radius < 0: raise ValueError("surface_area_sphere() only accepts non-negative values") return 4 * pi * radius ** 2 def area_rectangle(length: float, width: float) -> float: """ Calculate the area of a rectangle. >>> area_rectangle(10, 20) 200 >>> area_rectangle(-1, -2) Traceback (most recent call last): ... ValueError: area_rectangle() only accepts non-negative values >>> area_rectangle(1, -2) Traceback (most recent call last): ... ValueError: area_rectangle() only accepts non-negative values >>> area_rectangle(-1, 2) Traceback (most recent call last): ... ValueError: area_rectangle() only accepts non-negative values """ if length < 0 or width < 0: raise ValueError("area_rectangle() only accepts non-negative values") return length * width def area_square(side_length: float) -> float: """ Calculate the area of a square. >>> area_square(10) 100 >>> area_square(-1) Traceback (most recent call last): ... ValueError: area_square() only accepts non-negative values """ if side_length < 0: raise ValueError("area_square() only accepts non-negative values") return side_length ** 2 def area_triangle(base: float, height: float) -> float: """ Calculate the area of a triangle given the base and height. >>> area_triangle(10, 10) 50.0 >>> area_triangle(-1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(-1, 2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values """ if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values") return (base * height) / 2 def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float: """ Calculate area of triangle when the length of 3 sides are known. This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula >>> area_triangle_three_sides(5, 12, 13) 30.0 >>> area_triangle_three_sides(10, 11, 12) 51.521233486786784 >>> area_triangle_three_sides(-1, -2, -1) Traceback (most recent call last): ... ValueError: area_triangle_three_sides() only accepts non-negative values >>> area_triangle_three_sides(1, -2, 1) Traceback (most recent call last): ... ValueError: area_triangle_three_sides() only accepts non-negative values """ if side1 < 0 or side2 < 0 or side3 < 0: raise ValueError("area_triangle_three_sides() only accepts non-negative values") elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1: raise ValueError("Given three sides do not form a triangle") semi_perimeter = (side1 + side2 + side3) / 2 area = sqrt( semi_perimeter * (semi_perimeter - side1) * (semi_perimeter - side2) * (semi_perimeter - side3) ) return area def area_parallelogram(base: float, height: float) -> float: """ Calculate the area of a parallelogram. >>> area_parallelogram(10, 20) 200 >>> area_parallelogram(-1, -2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values >>> area_parallelogram(1, -2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values >>> area_parallelogram(-1, 2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values """ if base < 0 or height < 0: raise ValueError("area_parallelogram() only accepts non-negative values") return base * height def area_trapezium(base1: float, base2: float, height: float) -> float: """ Calculate the area of a trapezium. >>> area_trapezium(10, 20, 30) 450.0 >>> area_trapezium(-1, -2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, 2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, -2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, 2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, -2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, -2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, 2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values """ if base1 < 0 or base2 < 0 or height < 0: raise ValueError("area_trapezium() only accepts non-negative values") return 1 / 2 * (base1 + base2) * height def area_circle(radius: float) -> float: """ Calculate the area of a circle. >>> area_circle(20) 1256.6370614359173 >>> area_circle(-1) Traceback (most recent call last): ... ValueError: area_circle() only accepts non-negative values """ if radius < 0: raise ValueError("area_circle() only accepts non-negative values") return pi * radius ** 2 def area_ellipse(radius_x: float, radius_y: float) -> float: """ Calculate the area of a ellipse. >>> area_ellipse(10, 10) 314.1592653589793 >>> area_ellipse(10, 20) 628.3185307179587 >>> area_ellipse(-10, 20) Traceback (most recent call last): ... ValueError: area_ellipse() only accepts non-negative values >>> area_ellipse(10, -20) Traceback (most recent call last): ... ValueError: area_ellipse() only accepts non-negative values >>> area_ellipse(-10, -20) Traceback (most recent call last): ... ValueError: area_ellipse() only accepts non-negative values """ if radius_x < 0 or radius_y < 0: raise ValueError("area_ellipse() only accepts non-negative values") return pi * radius_x * radius_y def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: """ Calculate the area of a rhombus. >>> area_rhombus(10, 20) 100.0 >>> area_rhombus(-1, -2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values >>> area_rhombus(1, -2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values >>> area_rhombus(-1, 2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values """ if diagonal_1 < 0 or diagonal_2 < 0: raise ValueError("area_rhombus() only accepts non-negative values") return 1 / 2 * diagonal_1 * diagonal_2 if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print("[DEMO] Areas of various geometric shapes: \n") print(f"Rectangle: {area_rectangle(10, 20) = }") print(f"Square: {area_square(10) = }") print(f"Triangle: {area_triangle(10, 10) = }") print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(f"Parallelogram: {area_parallelogram(10, 20) = }") print(f"Trapezium: {area_trapezium(10, 20, 30) = }") print(f"Circle: {area_circle(20) = }") print("\nSurface Areas of various geometric shapes: \n") print(f"Cube: {surface_area_cube(20) = }") print(f"Sphere: {surface_area_sphere(20) = }") print(f"Rhombus: {area_rhombus(10, 20) = }")
""" Find the area of various geometric shapes """ from math import pi, sqrt def surface_area_cube(side_length: float) -> float: """ Calculate the Surface Area of a Cube. >>> surface_area_cube(1) 6 >>> surface_area_cube(3) 54 >>> surface_area_cube(-1) Traceback (most recent call last): ... ValueError: surface_area_cube() only accepts non-negative values """ if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values") return 6 * side_length ** 2 def surface_area_sphere(radius: float) -> float: """ Calculate the Surface Area of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere Formula: 4 * pi * r^2 >>> surface_area_sphere(5) 314.1592653589793 >>> surface_area_sphere(1) 12.566370614359172 >>> surface_area_sphere(-1) Traceback (most recent call last): ... ValueError: surface_area_sphere() only accepts non-negative values """ if radius < 0: raise ValueError("surface_area_sphere() only accepts non-negative values") return 4 * pi * radius ** 2 def area_rectangle(length: float, width: float) -> float: """ Calculate the area of a rectangle. >>> area_rectangle(10, 20) 200 >>> area_rectangle(-1, -2) Traceback (most recent call last): ... ValueError: area_rectangle() only accepts non-negative values >>> area_rectangle(1, -2) Traceback (most recent call last): ... ValueError: area_rectangle() only accepts non-negative values >>> area_rectangle(-1, 2) Traceback (most recent call last): ... ValueError: area_rectangle() only accepts non-negative values """ if length < 0 or width < 0: raise ValueError("area_rectangle() only accepts non-negative values") return length * width def area_square(side_length: float) -> float: """ Calculate the area of a square. >>> area_square(10) 100 >>> area_square(-1) Traceback (most recent call last): ... ValueError: area_square() only accepts non-negative values """ if side_length < 0: raise ValueError("area_square() only accepts non-negative values") return side_length ** 2 def area_triangle(base: float, height: float) -> float: """ Calculate the area of a triangle given the base and height. >>> area_triangle(10, 10) 50.0 >>> area_triangle(-1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(-1, 2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values """ if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values") return (base * height) / 2 def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float: """ Calculate area of triangle when the length of 3 sides are known. This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula >>> area_triangle_three_sides(5, 12, 13) 30.0 >>> area_triangle_three_sides(10, 11, 12) 51.521233486786784 >>> area_triangle_three_sides(-1, -2, -1) Traceback (most recent call last): ... ValueError: area_triangle_three_sides() only accepts non-negative values >>> area_triangle_three_sides(1, -2, 1) Traceback (most recent call last): ... ValueError: area_triangle_three_sides() only accepts non-negative values """ if side1 < 0 or side2 < 0 or side3 < 0: raise ValueError("area_triangle_three_sides() only accepts non-negative values") elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1: raise ValueError("Given three sides do not form a triangle") semi_perimeter = (side1 + side2 + side3) / 2 area = sqrt( semi_perimeter * (semi_perimeter - side1) * (semi_perimeter - side2) * (semi_perimeter - side3) ) return area def area_parallelogram(base: float, height: float) -> float: """ Calculate the area of a parallelogram. >>> area_parallelogram(10, 20) 200 >>> area_parallelogram(-1, -2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values >>> area_parallelogram(1, -2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values >>> area_parallelogram(-1, 2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values """ if base < 0 or height < 0: raise ValueError("area_parallelogram() only accepts non-negative values") return base * height def area_trapezium(base1: float, base2: float, height: float) -> float: """ Calculate the area of a trapezium. >>> area_trapezium(10, 20, 30) 450.0 >>> area_trapezium(-1, -2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, 2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, -2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, 2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, -2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, -2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, 2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values """ if base1 < 0 or base2 < 0 or height < 0: raise ValueError("area_trapezium() only accepts non-negative values") return 1 / 2 * (base1 + base2) * height def area_circle(radius: float) -> float: """ Calculate the area of a circle. >>> area_circle(20) 1256.6370614359173 >>> area_circle(-1) Traceback (most recent call last): ... ValueError: area_circle() only accepts non-negative values """ if radius < 0: raise ValueError("area_circle() only accepts non-negative values") return pi * radius ** 2 def area_ellipse(radius_x: float, radius_y: float) -> float: """ Calculate the area of a ellipse. >>> area_ellipse(10, 10) 314.1592653589793 >>> area_ellipse(10, 20) 628.3185307179587 >>> area_ellipse(-10, 20) Traceback (most recent call last): ... ValueError: area_ellipse() only accepts non-negative values >>> area_ellipse(10, -20) Traceback (most recent call last): ... ValueError: area_ellipse() only accepts non-negative values >>> area_ellipse(-10, -20) Traceback (most recent call last): ... ValueError: area_ellipse() only accepts non-negative values """ if radius_x < 0 or radius_y < 0: raise ValueError("area_ellipse() only accepts non-negative values") return pi * radius_x * radius_y def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: """ Calculate the area of a rhombus. >>> area_rhombus(10, 20) 100.0 >>> area_rhombus(-1, -2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values >>> area_rhombus(1, -2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values >>> area_rhombus(-1, 2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values """ if diagonal_1 < 0 or diagonal_2 < 0: raise ValueError("area_rhombus() only accepts non-negative values") return 1 / 2 * diagonal_1 * diagonal_2 if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print("[DEMO] Areas of various geometric shapes: \n") print(f"Rectangle: {area_rectangle(10, 20) = }") print(f"Square: {area_square(10) = }") print(f"Triangle: {area_triangle(10, 10) = }") print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(f"Parallelogram: {area_parallelogram(10, 20) = }") print(f"Trapezium: {area_trapezium(10, 20, 30) = }") print(f"Circle: {area_circle(20) = }") print("\nSurface Areas of various geometric shapes: \n") print(f"Cube: {surface_area_cube(20) = }") print(f"Sphere: {surface_area_sphere(20) = }") print(f"Rhombus: {area_rhombus(10, 20) = }")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" One of the several implementations of Lempel–Ziv–Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict, curr_string: str, index: int, last_match_id: int ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
""" One of the several implementations of Lempel–Ziv–Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict, curr_string: str, index: int, last_match_id: int ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. """ def calculateSpan(price, S): n = len(price) # Create a stack and push index of fist element to it st = [] st.append(0) # Span value of first element is always 1 S[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[0]] <= price[i]: st.pop() # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack S[i] = i + 1 if len(st) <= 0 else (i - st[0]) # Push this element to stack st.append(i) # A utility function to print elements of array def printArray(arr, n): for i in range(0, n): print(arr[i], end=" ") # Driver program to test above function price = [10, 4, 5, 90, 120, 80] S = [0 for i in range(len(price) + 1)] # Fill the span values in array S[] calculateSpan(price, S) # Print the calculated span values printArray(S, len(price))
""" The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. """ def calculateSpan(price, S): n = len(price) # Create a stack and push index of fist element to it st = [] st.append(0) # Span value of first element is always 1 S[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[0]] <= price[i]: st.pop() # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack S[i] = i + 1 if len(st) <= 0 else (i - st[0]) # Push this element to stack st.append(i) # A utility function to print elements of array def printArray(arr, n): for i in range(0, n): print(arr[i], end=" ") # Driver program to test above function price = [10, 4, 5, 90, 120, 80] S = [0 for i in range(len(price) + 1)] # Fill the span values in array S[] calculateSpan(price, S) # Print the calculated span values printArray(S, len(price))
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" An RSA prime factor algorithm. The program can efficiently factor RSA prime number given the private key d and public key e. Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html large number can take minutes to factor, therefore are not included in doctest. """ from __future__ import annotations import math import random def rsafactor(d: int, e: int, N: int) -> [int]: """ This function returns the factors of N, where p*q=N Return: [p, q] We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair (N, e) is the public key. As its name suggests, it is public and is used to encrypt messages. The pair (N, d) is the secret key or private key and is known only to the recipient of encrypted messages. >>> rsafactor(3, 16971, 25777) [149, 173] >>> rsafactor(7331, 11, 27233) [113, 241] >>> rsafactor(4021, 13, 17711) [89, 199] """ k = d * e - 1 p = 0 q = 0 while p == 0: g = random.randint(2, N - 1) t = k while True: if t % 2 == 0: t = t // 2 x = (g ** t) % N y = math.gcd(x - 1, N) if x > 1 and y > 1: p = y q = N // y break # find the correct factors else: break # t is not divisible by 2, break and choose another g return sorted([p, q]) if __name__ == "__main__": import doctest doctest.testmod()
""" An RSA prime factor algorithm. The program can efficiently factor RSA prime number given the private key d and public key e. Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html large number can take minutes to factor, therefore are not included in doctest. """ from __future__ import annotations import math import random def rsafactor(d: int, e: int, N: int) -> [int]: """ This function returns the factors of N, where p*q=N Return: [p, q] We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair (N, e) is the public key. As its name suggests, it is public and is used to encrypt messages. The pair (N, d) is the secret key or private key and is known only to the recipient of encrypted messages. >>> rsafactor(3, 16971, 25777) [149, 173] >>> rsafactor(7331, 11, 27233) [113, 241] >>> rsafactor(4021, 13, 17711) [89, 199] """ k = d * e - 1 p = 0 q = 0 while p == 0: g = random.randint(2, N - 1) t = k while True: if t % 2 == 0: t = t // 2 x = (g ** t) % N y = math.gcd(x - 1, N) if x > 1 and y > 1: p = y q = N // y break # find the correct factors else: break # t is not divisible by 2, break and choose another g return sorted([p, q]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 39: https://projecteuler.net/problem=39 If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p ≤ 1000, is the number of solutions maximised? """ from __future__ import annotations import typing from collections import Counter def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]: """ Returns a dictionary with keys as the perimeter of a right angled triangle and value as the number of corresponding triplets. >>> pythagorean_triple(15) Counter({12: 1}) >>> pythagorean_triple(40) Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1}) >>> pythagorean_triple(50) Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1, 48: 1}) """ triplets: typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1): for perpendicular in range(base, max_perimeter + 1): hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(hypotenuse): perimeter = int(base + perpendicular + hypotenuse) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def solution(n: int = 1000) -> int: """ Returns perimeter with maximum solutions. >>> solution(100) 90 >>> solution(200) 180 >>> solution(1000) 840 """ triplets = pythagorean_triple(n) return triplets.most_common(1)[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
""" Problem 39: https://projecteuler.net/problem=39 If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p ≤ 1000, is the number of solutions maximised? """ from __future__ import annotations import typing from collections import Counter def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]: """ Returns a dictionary with keys as the perimeter of a right angled triangle and value as the number of corresponding triplets. >>> pythagorean_triple(15) Counter({12: 1}) >>> pythagorean_triple(40) Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1}) >>> pythagorean_triple(50) Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1, 48: 1}) """ triplets: typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1): for perpendicular in range(base, max_perimeter + 1): hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(hypotenuse): perimeter = int(base + perpendicular + hypotenuse) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def solution(n: int = 1000) -> int: """ Returns perimeter with maximum solutions. >>> solution(100) 90 >>> solution(200) 180 >>> solution(1000) 840 """ triplets = pythagorean_triple(n) return triplets.most_common(1)[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Min heap data structure # with decrease key functionality - in O(log(n)) time class Node: def __init__(self, name, val): self.name = name self.val = val def __str__(self): return f"{self.__class__.__name__}({self.name}, {self.val})" def __lt__(self, other): return self.val < other.val class MinHeap: """ >>> r = Node("R", -1) >>> b = Node("B", 6) >>> a = Node("A", 3) >>> x = Node("X", 1) >>> e = Node("E", 4) >>> print(b) Node(B, 6) >>> myMinHeap = MinHeap([r, b, a, x, e]) >>> myMinHeap.decrease_key(b, -17) >>> print(b) Node(B, -17) >>> print(myMinHeap["B"]) -17 """ def __init__(self, array): self.idx_of_element = {} self.heap_dict = {} self.heap = self.build_heap(array) def __getitem__(self, key): return self.get_value(key) def get_parent_idx(self, idx): return (idx - 1) // 2 def get_left_child_idx(self, idx): return idx * 2 + 1 def get_right_child_idx(self, idx): return idx * 2 + 2 def get_value(self, key): return self.heap_dict[key] def build_heap(self, array): lastIdx = len(array) - 1 startFrom = self.get_parent_idx(lastIdx) for idx, i in enumerate(array): self.idx_of_element[i] = idx self.heap_dict[i.name] = i.val for i in range(startFrom, -1, -1): self.sift_down(i, array) return array # this is min-heapify method def sift_down(self, idx, array): while True: l = self.get_left_child_idx(idx) # noqa: E741 r = self.get_right_child_idx(idx) smallest = idx if l < len(array) and array[l] < array[idx]: smallest = l if r < len(array) and array[r] < array[smallest]: smallest = r if smallest != idx: array[idx], array[smallest] = array[smallest], array[idx] ( self.idx_of_element[array[idx]], self.idx_of_element[array[smallest]], ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) idx = smallest else: break def sift_up(self, idx): p = self.get_parent_idx(idx) while p >= 0 and self.heap[p] > self.heap[idx]: self.heap[p], self.heap[idx] = self.heap[idx], self.heap[p] self.idx_of_element[self.heap[p]], self.idx_of_element[self.heap[idx]] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) idx = p p = self.get_parent_idx(idx) def peek(self): return self.heap[0] def remove(self): self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] self.idx_of_element[self.heap[0]], self.idx_of_element[self.heap[-1]] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) x = self.heap.pop() del self.idx_of_element[x] self.sift_down(0, self.heap) return x def insert(self, node): self.heap.append(node) self.idx_of_element[node] = len(self.heap) - 1 self.heap_dict[node.name] = node.val self.sift_up(len(self.heap) - 1) def is_empty(self): return True if len(self.heap) == 0 else False def decrease_key(self, node, newValue): assert ( self.heap[self.idx_of_element[node]].val > newValue ), "newValue must be less that current value" node.val = newValue self.heap_dict[node.name] = newValue self.sift_up(self.idx_of_element[node]) # USAGE r = Node("R", -1) b = Node("B", 6) a = Node("A", 3) x = Node("X", 1) e = Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array myMinHeap = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in myMinHeap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") myMinHeap.decrease_key(b, -17) # After for i in myMinHeap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
# Min heap data structure # with decrease key functionality - in O(log(n)) time class Node: def __init__(self, name, val): self.name = name self.val = val def __str__(self): return f"{self.__class__.__name__}({self.name}, {self.val})" def __lt__(self, other): return self.val < other.val class MinHeap: """ >>> r = Node("R", -1) >>> b = Node("B", 6) >>> a = Node("A", 3) >>> x = Node("X", 1) >>> e = Node("E", 4) >>> print(b) Node(B, 6) >>> myMinHeap = MinHeap([r, b, a, x, e]) >>> myMinHeap.decrease_key(b, -17) >>> print(b) Node(B, -17) >>> print(myMinHeap["B"]) -17 """ def __init__(self, array): self.idx_of_element = {} self.heap_dict = {} self.heap = self.build_heap(array) def __getitem__(self, key): return self.get_value(key) def get_parent_idx(self, idx): return (idx - 1) // 2 def get_left_child_idx(self, idx): return idx * 2 + 1 def get_right_child_idx(self, idx): return idx * 2 + 2 def get_value(self, key): return self.heap_dict[key] def build_heap(self, array): lastIdx = len(array) - 1 startFrom = self.get_parent_idx(lastIdx) for idx, i in enumerate(array): self.idx_of_element[i] = idx self.heap_dict[i.name] = i.val for i in range(startFrom, -1, -1): self.sift_down(i, array) return array # this is min-heapify method def sift_down(self, idx, array): while True: l = self.get_left_child_idx(idx) # noqa: E741 r = self.get_right_child_idx(idx) smallest = idx if l < len(array) and array[l] < array[idx]: smallest = l if r < len(array) and array[r] < array[smallest]: smallest = r if smallest != idx: array[idx], array[smallest] = array[smallest], array[idx] ( self.idx_of_element[array[idx]], self.idx_of_element[array[smallest]], ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) idx = smallest else: break def sift_up(self, idx): p = self.get_parent_idx(idx) while p >= 0 and self.heap[p] > self.heap[idx]: self.heap[p], self.heap[idx] = self.heap[idx], self.heap[p] self.idx_of_element[self.heap[p]], self.idx_of_element[self.heap[idx]] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) idx = p p = self.get_parent_idx(idx) def peek(self): return self.heap[0] def remove(self): self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] self.idx_of_element[self.heap[0]], self.idx_of_element[self.heap[-1]] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) x = self.heap.pop() del self.idx_of_element[x] self.sift_down(0, self.heap) return x def insert(self, node): self.heap.append(node) self.idx_of_element[node] = len(self.heap) - 1 self.heap_dict[node.name] = node.val self.sift_up(len(self.heap) - 1) def is_empty(self): return True if len(self.heap) == 0 else False def decrease_key(self, node, newValue): assert ( self.heap[self.idx_of_element[node]].val > newValue ), "newValue must be less that current value" node.val = newValue self.heap_dict[node.name] = newValue self.sift_up(self.idx_of_element[node]) # USAGE r = Node("R", -1) b = Node("B", 6) a = Node("A", 3) x = Node("X", 1) e = Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array myMinHeap = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in myMinHeap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") myMinHeap.decrease_key(b, -17) # After for i in myMinHeap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A binary search Tree """ class Node: def __init__(self, value, parent): self.value = value self.parent = parent # Added in order to delete a node easier self.left = None self.right = None def __repr__(self): from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1) class BinarySearchTree: def __init__(self, root=None): self.root = root def __str__(self): """ Return a string of all the Nodes using in order traversal """ return str(self.root) def __reassign_nodes(self, node, new_children): if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if self.is_right(node): # If it is the right children node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def is_right(self, node): return node == node.parent.right def empty(self): return self.root is None def __insert(self, value): """ Insert a new node in Binary Search Tree with value label """ new_node = Node(value, None) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root else: # Tree is not empty parent_node = self.root # from root while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: parent_node.left = new_node # We insert the new node in a leaf break else: parent_node = parent_node.left else: if parent_node.right is None: parent_node.right = new_node break else: parent_node = parent_node.right new_node.parent = parent_node def insert(self, *values): for value in values: self.__insert(value) return self def search(self, value): if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") else: node = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node = node.left if value < node.value else node.right return node def get_max(self, node=None): """ We go deep on the right branch """ if node is None: node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node=None): """ We go deep on the left branch """ if node is None: node = self.root if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value): node = self.search(value) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(node, None) elif node.left is None: # Has only right children self.__reassign_nodes(node, node.right) elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: tmp_node = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value) node.value = ( tmp_node.value ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node): if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) def traversal_tree(self, traversal_function=None): """ This function traversal the tree. You can pass a function to traversal the tree as needed by client code """ if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def inorder(self, arr: list, node: Node): """Perform an inorder traversal and append values of the nodes to a list named arr""" if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right) def find_kth_smallest(self, k: int, node: Node) -> int: """Return the kth smallest element in a binary search tree """ arr = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def postorder(curr_node): """ postOrder (left, right, self) """ node_list = list() if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list def binary_search_tree(): r""" Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7) >>> print(" ".join(repr(i.value) for i in t.traversal_tree())) 8 3 1 6 4 7 10 14 13 >>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder))) 1 4 7 6 3 13 14 10 8 >>> BinarySearchTree().search(6) Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. """ testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7) t = BinarySearchTree() for i in testlist: t.insert(i) # Prints all the elements of the list in order traversal print(t) if t.search(6) is not None: print("The value 6 exists") else: print("The value 6 doesn't exist") if t.search(-1) is not None: print("The value -1 exists") else: print("The value -1 doesn't exist") if not t.empty(): print("Max Value: ", t.get_max().value) print("Min Value: ", t.get_min().value) for i in testlist: t.remove(i) print(t) if __name__ == "__main__": import doctest doctest.testmod() # binary_search_tree()
""" A binary search Tree """ class Node: def __init__(self, value, parent): self.value = value self.parent = parent # Added in order to delete a node easier self.left = None self.right = None def __repr__(self): from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1) class BinarySearchTree: def __init__(self, root=None): self.root = root def __str__(self): """ Return a string of all the Nodes using in order traversal """ return str(self.root) def __reassign_nodes(self, node, new_children): if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if self.is_right(node): # If it is the right children node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def is_right(self, node): return node == node.parent.right def empty(self): return self.root is None def __insert(self, value): """ Insert a new node in Binary Search Tree with value label """ new_node = Node(value, None) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root else: # Tree is not empty parent_node = self.root # from root while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: parent_node.left = new_node # We insert the new node in a leaf break else: parent_node = parent_node.left else: if parent_node.right is None: parent_node.right = new_node break else: parent_node = parent_node.right new_node.parent = parent_node def insert(self, *values): for value in values: self.__insert(value) return self def search(self, value): if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") else: node = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node = node.left if value < node.value else node.right return node def get_max(self, node=None): """ We go deep on the right branch """ if node is None: node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node=None): """ We go deep on the left branch """ if node is None: node = self.root if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value): node = self.search(value) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(node, None) elif node.left is None: # Has only right children self.__reassign_nodes(node, node.right) elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: tmp_node = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value) node.value = ( tmp_node.value ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node): if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) def traversal_tree(self, traversal_function=None): """ This function traversal the tree. You can pass a function to traversal the tree as needed by client code """ if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def inorder(self, arr: list, node: Node): """Perform an inorder traversal and append values of the nodes to a list named arr""" if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right) def find_kth_smallest(self, k: int, node: Node) -> int: """Return the kth smallest element in a binary search tree """ arr = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def postorder(curr_node): """ postOrder (left, right, self) """ node_list = list() if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list def binary_search_tree(): r""" Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7) >>> print(" ".join(repr(i.value) for i in t.traversal_tree())) 8 3 1 6 4 7 10 14 13 >>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder))) 1 4 7 6 3 13 14 10 8 >>> BinarySearchTree().search(6) Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. """ testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7) t = BinarySearchTree() for i in testlist: t.insert(i) # Prints all the elements of the list in order traversal print(t) if t.search(6) is not None: print("The value 6 exists") else: print("The value 6 doesn't exist") if t.search(-1) is not None: print("The value -1 exists") else: print("The value -1 doesn't exist") if not t.empty(): print("Max Value: ", t.get_max().value) print("Min Value: ", t.get_min().value) for i in testlist: t.remove(i) print(t) if __name__ == "__main__": import doctest doctest.testmod() # binary_search_tree()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Bead sort only works for sequences of nonegative integers. https://en.wikipedia.org/wiki/Bead_sort """ def bead_sort(sequence: list) -> list: """ >>> bead_sort([6, 11, 12, 4, 1, 5]) [1, 4, 5, 6, 11, 12] >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1]) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bead_sort([5, 0, 4, 3]) [0, 3, 4, 5] >>> bead_sort([8, 2, 1]) [1, 2, 8] >>> bead_sort([1, .9, 0.0, 0, -1, -.9]) Traceback (most recent call last): ... TypeError: Sequence must be list of nonnegative integers >>> bead_sort("Hello world") Traceback (most recent call last): ... TypeError: Sequence must be list of nonnegative integers """ if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of nonnegative integers") for _ in range(len(sequence)): for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
""" Bead sort only works for sequences of nonegative integers. https://en.wikipedia.org/wiki/Bead_sort """ def bead_sort(sequence: list) -> list: """ >>> bead_sort([6, 11, 12, 4, 1, 5]) [1, 4, 5, 6, 11, 12] >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1]) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bead_sort([5, 0, 4, 3]) [0, 3, 4, 5] >>> bead_sort([8, 2, 1]) [1, 2, 8] >>> bead_sort([1, .9, 0.0, 0, -1, -.9]) Traceback (most recent call last): ... TypeError: Sequence must be list of nonnegative integers >>> bead_sort("Hello world") Traceback (most recent call last): ... TypeError: Sequence must be list of nonnegative integers """ if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of nonnegative integers") for _ in range(len(sequence)): for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve # https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm from __future__ import annotations from scipy.special import comb class BezierCurve: """ Bezier curve is a weighted sum of a set of control points. Generate Bezier curves from a given set of control points. This implementation works only for 2d coordinates in the xy plane. """ def __init__(self, list_of_points: list[tuple[float, float]]): """ list_of_points: Control points in the xy plane on which to interpolate. These points control the behavior (shape) of the Bezier curve. """ self.list_of_points = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. self.degree = len(list_of_points) - 1 def basis_function(self, t: float) -> list[float]: """ The basis function determines the weight of each control point at time t. t: time value between 0 and 1 inclusive at which to evaluate the basis of the curve. returns the x, y values of basis function at time t >>> curve = BezierCurve([(1,1), (1,2)]) >>> curve.basis_function(0) [1.0, 0.0] >>> curve.basis_function(1) [0.0, 1.0] """ assert 0 <= t <= 1, "Time t must be between 0 and 1." output_values: list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t ** i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(output_values), 5) == 1 return output_values def bezier_curve_function(self, t: float) -> tuple[float, float]: """ The function to produce the values of the Bezier curve at time t. t: the value of time t at which to evaluate the Bezier function Returns the x, y coordinates of the Bezier curve at time t. The first point in the curve is when t = 0. The last point in the curve is when t = 1. >>> curve = BezierCurve([(1,1), (1,2)]) >>> curve.bezier_curve_function(0) (1.0, 1.0) >>> curve.bezier_curve_function(1) (1.0, 2.0) """ assert 0 <= t <= 1, "Time t must be between 0 and 1." basis_function = self.basis_function(t) x = 0.0 y = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def plot_curve(self, step_size: float = 0.01): """ Plots the Bezier curve using matplotlib plotting capabilities. step_size: defines the step(s) at which to evaluate the Bezier curve. The smaller the step size, the finer the curve produced. """ from matplotlib import pyplot as plt to_plot_x: list[float] = [] # x coordinates of points to plot to_plot_y: list[float] = [] # y coordinates of points to plot t = 0.0 while t <= 1: value = self.bezier_curve_function(t) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size x = [i[0] for i in self.list_of_points] y = [i[1] for i in self.list_of_points] plt.plot( to_plot_x, to_plot_y, color="blue", label="Curve of Degree " + str(self.degree), ) plt.scatter(x, y, color="red", label="Control Points") plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve # https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm from __future__ import annotations from scipy.special import comb class BezierCurve: """ Bezier curve is a weighted sum of a set of control points. Generate Bezier curves from a given set of control points. This implementation works only for 2d coordinates in the xy plane. """ def __init__(self, list_of_points: list[tuple[float, float]]): """ list_of_points: Control points in the xy plane on which to interpolate. These points control the behavior (shape) of the Bezier curve. """ self.list_of_points = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. self.degree = len(list_of_points) - 1 def basis_function(self, t: float) -> list[float]: """ The basis function determines the weight of each control point at time t. t: time value between 0 and 1 inclusive at which to evaluate the basis of the curve. returns the x, y values of basis function at time t >>> curve = BezierCurve([(1,1), (1,2)]) >>> curve.basis_function(0) [1.0, 0.0] >>> curve.basis_function(1) [0.0, 1.0] """ assert 0 <= t <= 1, "Time t must be between 0 and 1." output_values: list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t ** i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(output_values), 5) == 1 return output_values def bezier_curve_function(self, t: float) -> tuple[float, float]: """ The function to produce the values of the Bezier curve at time t. t: the value of time t at which to evaluate the Bezier function Returns the x, y coordinates of the Bezier curve at time t. The first point in the curve is when t = 0. The last point in the curve is when t = 1. >>> curve = BezierCurve([(1,1), (1,2)]) >>> curve.bezier_curve_function(0) (1.0, 1.0) >>> curve.bezier_curve_function(1) (1.0, 2.0) """ assert 0 <= t <= 1, "Time t must be between 0 and 1." basis_function = self.basis_function(t) x = 0.0 y = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def plot_curve(self, step_size: float = 0.01): """ Plots the Bezier curve using matplotlib plotting capabilities. step_size: defines the step(s) at which to evaluate the Bezier curve. The smaller the step size, the finer the curve produced. """ from matplotlib import pyplot as plt to_plot_x: list[float] = [] # x coordinates of points to plot to_plot_y: list[float] = [] # y coordinates of points to plot t = 0.0 while t <= 1: value = self.bezier_curve_function(t) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size x = [i[0] for i in self.list_of_points] y = [i[1] for i in self.list_of_points] plt.plot( to_plot_x, to_plot_y, color="blue", label="Curve of Degree " + str(self.degree), ) plt.scatter(x, y, color="red", label="Control Points") plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ import numpy as np class Decision_Tree: def __init__(self, depth=5, min_leaf_size=5): self.depth = depth self.decision_boundary = 0 self.left = None self.right = None self.min_leaf_size = min_leaf_size self.prediction = None def mean_squared_error(self, labels, prediction): """ mean_squared_error: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: mean_squared_error calculates the error if prediction is used to estimate the labels >>> tester = Decision_Tree() >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) >>> test_prediction = np.float(6) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True >>> test_labels = np.array([1,2,3]) >>> test_prediction = np.float(2) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True """ if labels.ndim != 1: print("Error: Input labels must be one dimensional") return np.mean((labels - prediction) ** 2) def train(self, X, y): """ train: @param X: a one dimensional numpy array @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value """ """ this section is to check that the inputs conform to our dimensionality constraints """ if X.ndim != 1: print("Error: Input data set must be one dimensional") return if len(X) != len(y): print("Error: X and y have different lengths") return if y.ndim != 1: print("Error: Data set labels must be one dimensional") return if len(X) < 2 * self.min_leaf_size: self.prediction = np.mean(y) return if self.depth == 1: self.prediction = np.mean(y) return best_split = 0 min_error = self.mean_squared_error(X, np.mean(y)) * 2 """ loop over all possible splits for the decision tree. find the best split. if no split exists that is less than 2 * error for the entire array then the data set is not split and the average for the entire array is used as the predictor """ for i in range(len(X)): if len(X[:i]) < self.min_leaf_size: continue elif len(X[i:]) < self.min_leaf_size: continue else: error_left = self.mean_squared_error(X[:i], np.mean(y[:i])) error_right = self.mean_squared_error(X[i:], np.mean(y[i:])) error = error_left + error_right if error < min_error: best_split = i min_error = error if best_split != 0: left_X = X[:best_split] left_y = y[:best_split] right_X = X[best_split:] right_y = y[best_split:] self.decision_boundary = X[best_split] self.left = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.right = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.left.train(left_X, left_y) self.right.train(right_X, right_y) else: self.prediction = np.mean(y) return def predict(self, x): """ predict: @param x: a floating point value to predict the label of the prediction function works by recursively calling the predict function of the appropriate subtrees based on the tree's decision boundary """ if self.prediction is not None: return self.prediction elif self.left or self.right is not None: if x >= self.decision_boundary: return self.right.predict(x) else: return self.left.predict(x) else: print("Error: Decision tree not yet trained") return None class Test_Decision_Tree: """Decision Tres test class""" @staticmethod def helper_mean_squared_error_test(labels, prediction): """ helper_mean_squared_error_test: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: helper_mean_squared_error_test calculates the mean squared error """ squared_error_sum = np.float(0) for label in labels: squared_error_sum += (label - prediction) ** 2 return np.float(squared_error_sum / labels.size) def main(): """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed. """ X = np.arange(-1.0, 1.0, 0.005) y = np.sin(X) tree = Decision_Tree(depth=10, min_leaf_size=10) tree.train(X, y) test_cases = (np.random.rand(10) * 2) - 1 predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) print("Test values: " + str(test_cases)) print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error)) if __name__ == "__main__": main() import doctest doctest.testmod(name="mean_squarred_error", verbose=True)
""" Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ import numpy as np class Decision_Tree: def __init__(self, depth=5, min_leaf_size=5): self.depth = depth self.decision_boundary = 0 self.left = None self.right = None self.min_leaf_size = min_leaf_size self.prediction = None def mean_squared_error(self, labels, prediction): """ mean_squared_error: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: mean_squared_error calculates the error if prediction is used to estimate the labels >>> tester = Decision_Tree() >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) >>> test_prediction = np.float(6) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True >>> test_labels = np.array([1,2,3]) >>> test_prediction = np.float(2) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True """ if labels.ndim != 1: print("Error: Input labels must be one dimensional") return np.mean((labels - prediction) ** 2) def train(self, X, y): """ train: @param X: a one dimensional numpy array @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value """ """ this section is to check that the inputs conform to our dimensionality constraints """ if X.ndim != 1: print("Error: Input data set must be one dimensional") return if len(X) != len(y): print("Error: X and y have different lengths") return if y.ndim != 1: print("Error: Data set labels must be one dimensional") return if len(X) < 2 * self.min_leaf_size: self.prediction = np.mean(y) return if self.depth == 1: self.prediction = np.mean(y) return best_split = 0 min_error = self.mean_squared_error(X, np.mean(y)) * 2 """ loop over all possible splits for the decision tree. find the best split. if no split exists that is less than 2 * error for the entire array then the data set is not split and the average for the entire array is used as the predictor """ for i in range(len(X)): if len(X[:i]) < self.min_leaf_size: continue elif len(X[i:]) < self.min_leaf_size: continue else: error_left = self.mean_squared_error(X[:i], np.mean(y[:i])) error_right = self.mean_squared_error(X[i:], np.mean(y[i:])) error = error_left + error_right if error < min_error: best_split = i min_error = error if best_split != 0: left_X = X[:best_split] left_y = y[:best_split] right_X = X[best_split:] right_y = y[best_split:] self.decision_boundary = X[best_split] self.left = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.right = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.left.train(left_X, left_y) self.right.train(right_X, right_y) else: self.prediction = np.mean(y) return def predict(self, x): """ predict: @param x: a floating point value to predict the label of the prediction function works by recursively calling the predict function of the appropriate subtrees based on the tree's decision boundary """ if self.prediction is not None: return self.prediction elif self.left or self.right is not None: if x >= self.decision_boundary: return self.right.predict(x) else: return self.left.predict(x) else: print("Error: Decision tree not yet trained") return None class Test_Decision_Tree: """Decision Tres test class""" @staticmethod def helper_mean_squared_error_test(labels, prediction): """ helper_mean_squared_error_test: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: helper_mean_squared_error_test calculates the mean squared error """ squared_error_sum = np.float(0) for label in labels: squared_error_sum += (label - prediction) ** 2 return np.float(squared_error_sum / labels.size) def main(): """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed. """ X = np.arange(-1.0, 1.0, 0.005) y = np.sin(X) tree = Decision_Tree(depth=10, min_leaf_size=10) tree.train(X, y) test_cases = (np.random.rand(10) * 2) - 1 predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) print("Test values: " + str(test_cases)) print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error)) if __name__ == "__main__": main() import doctest doctest.testmod(name="mean_squarred_error", verbose=True)
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 57: https://projecteuler.net/problem=57 It is possible to show that the square root of two can be expressed as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...))) By expanding this for the first four iterations, we get: 1 + 1 / 2 = 3 / 2 = 1.5 1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666... 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator? """ def solution(n: int = 1000) -> int: """ returns number of fractions containing a numerator with more digits than the denominator in the first n expansions. >>> solution(14) 2 >>> solution(100) 15 >>> solution(10000) 1508 """ prev_numerator, prev_denominator = 1, 1 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 57: https://projecteuler.net/problem=57 It is possible to show that the square root of two can be expressed as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...))) By expanding this for the first four iterations, we get: 1 + 1 / 2 = 3 / 2 = 1.5 1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666... 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator? """ def solution(n: int = 1000) -> int: """ returns number of fractions containing a numerator with more digits than the denominator in the first n expansions. >>> solution(14) 2 >>> solution(100) 15 >>> solution(10000) 1508 """ prev_numerator, prev_denominator = 1, 1 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class Graph: def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex)] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: print(j, end=" ") print(" ") g = Graph(100) g.add_edge(1, 4) g.add_edge(4, 2) g.add_edge(4, 5) g.add_edge(2, 5) g.add_edge(5, 3) g.show()
class Graph: def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex)] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: print(j, end=" ") print(" ") g = Graph(100) g.add_edge(1, 4) g.add_edge(4, 2) g.add_edge(4, 5) g.add_edge(2, 5) g.add_edge(5, 3) g.show()
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] 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 represetation 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 represetation 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,118
Changes occurences of str.format to f-strings
### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CarsonHam
"2021-01-13T04:57:54Z"
"2021-02-23T05:53:49Z"
f680806894d39265f810e7257d50aa0beaf2152e
61f3119467584de53a2f4395e3c03a8e12d67d30
Changes occurences of str.format to f-strings. ### **Describe your change:** fixes: #4117 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 206: https://projecteuler.net/problem=206 Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, where each “_” is a single digit. ----- Instead of computing every single permutation of that number and going through a 10^9 search space, we can narrow it down considerably. If the square ends in a 0, then the square root must also end in a 0. Thus, the last missing digit must be 0 and the square root is a multiple of 10. We can narrow the search space down to the first 8 digits and multiply the result of that by 10 at the end. Now the last digit is a 9, which can only happen if the square root ends in a 3 or 7. From this point, we can try one of two different methods to find the answer: 1. Start at the lowest possible base number whose square would be in the format, and count up. The base we would start at is 101010103, whose square is the closest number to 10203040506070809. Alternate counting up by 4 and 6 so the last digit of the base is always a 3 or 7. 2. Start at the highest possible base number whose square would be in the format, and count down. That base would be 138902663, whose square is the closest number to 1929394959697989. Alternate counting down by 6 and 4 so the last digit of the base is always a 3 or 7. The solution does option 2 because the answer happens to be much closer to the starting point. """ def is_square_form(num: int) -> bool: """ Determines if num is in the form 1_2_3_4_5_6_7_8_9 >>> is_square_form(1) False >>> is_square_form(112233445566778899) True >>> is_square_form(123456789012345678) False """ digit = 9 while num > 0: if num % 10 != digit: return False num //= 100 digit -= 1 return True def solution() -> int: """ Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0 """ num = 138902663 while not is_square_form(num * num): if num % 10 == 3: num -= 6 # (3 - 6) % 10 = 7 else: num -= 4 # (7 - 4) % 10 = 3 return num * 10 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 206: https://projecteuler.net/problem=206 Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, where each “_” is a single digit. ----- Instead of computing every single permutation of that number and going through a 10^9 search space, we can narrow it down considerably. If the square ends in a 0, then the square root must also end in a 0. Thus, the last missing digit must be 0 and the square root is a multiple of 10. We can narrow the search space down to the first 8 digits and multiply the result of that by 10 at the end. Now the last digit is a 9, which can only happen if the square root ends in a 3 or 7. From this point, we can try one of two different methods to find the answer: 1. Start at the lowest possible base number whose square would be in the format, and count up. The base we would start at is 101010103, whose square is the closest number to 10203040506070809. Alternate counting up by 4 and 6 so the last digit of the base is always a 3 or 7. 2. Start at the highest possible base number whose square would be in the format, and count down. That base would be 138902663, whose square is the closest number to 1929394959697989. Alternate counting down by 6 and 4 so the last digit of the base is always a 3 or 7. The solution does option 2 because the answer happens to be much closer to the starting point. """ def is_square_form(num: int) -> bool: """ Determines if num is in the form 1_2_3_4_5_6_7_8_9 >>> is_square_form(1) False >>> is_square_form(112233445566778899) True >>> is_square_form(123456789012345678) False """ digit = 9 while num > 0: if num % 10 != digit: return False num //= 100 digit -= 1 return True def solution() -> int: """ Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0 """ num = 138902663 while not is_square_form(num * num): if num % 10 == 3: num -= 6 # (3 - 6) % 10 = 7 else: num -= 4 # (7 - 4) % 10 = 3 return num * 10 if __name__ == "__main__": print(f"{solution() = }")
-1