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,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 Tuple def diophantine(a: int, b: int, c: int) -> Tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
from typing import Tuple def diophantine(a: int, b: int, c: int) -> Tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", 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 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,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 pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
-1
TheAlgorithms/Python
4,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 UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n" def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} with open(path[0] + "/dictionary.txt") as dictionaryFile: for word in dictionaryFile.read().split("\n"): englishWords[word] = None return englishWords ENGLISH_WORDS = loadDictionary() def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() if possibleWords == []: return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(possibleWords) def removeNonLetters(message): lettersOnly = [] for symbol in message: if symbol in LETTERS_AND_SPACE: lettersOnly.append(symbol) return "".join(lettersOnly) def isEnglish(message, wordPercentage=20, letterPercentage=85): """ >>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False """ wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = (float(numLetters) / len(message)) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch if __name__ == "__main__": import doctest doctest.testmod()
import os UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n" def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} with open(path[0] + "/dictionary.txt") as dictionaryFile: for word in dictionaryFile.read().split("\n"): englishWords[word] = None return englishWords ENGLISH_WORDS = loadDictionary() def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() if possibleWords == []: return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(possibleWords) def removeNonLetters(message): lettersOnly = [] for symbol in message: if symbol in LETTERS_AND_SPACE: lettersOnly.append(symbol) return "".join(lettersOnly) def isEnglish(message, wordPercentage=20, letterPercentage=85): """ >>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False """ wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = (float(numLetters) / len(message)) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch 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}`.
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch # Author: Shubham Malik # References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm import math import sys # For storing the vertex set to retrieve node with the lowest distance class PriorityQueue: # Based on Min Heap def __init__(self): self.cur_size = 0 self.array = [] self.pos = {} # To store the pos of node in array def isEmpty(self): return self.cur_size == 0 def min_heapify(self, idx): lc = self.left(idx) rc = self.right(idx) if lc < self.cur_size and self.array(lc)[0] < self.array(idx)[0]: smallest = lc else: smallest = idx if rc < self.cur_size and self.array(rc)[0] < self.array(smallest)[0]: smallest = rc if smallest != idx: self.swap(idx, smallest) self.min_heapify(smallest) def insert(self, tup): # Inserts a node into the Priority Queue self.pos[tup[1]] = self.cur_size self.cur_size += 1 self.array.append((sys.maxsize, tup[1])) self.decrease_key((sys.maxsize, tup[1]), tup[0]) def extract_min(self): # Removes and returns the min element at top of priority queue min_node = self.array[0][1] self.array[0] = self.array[self.cur_size - 1] self.cur_size -= 1 self.min_heapify(1) del self.pos[min_node] return min_node def left(self, i): # returns the index of left child return 2 * i + 1 def right(self, i): # returns the index of right child return 2 * i + 2 def par(self, i): # returns the index of parent return math.floor(i / 2) def swap(self, i, j): # swaps array elements at indices i and j # update the pos{} self.pos[self.array[i][1]] = j self.pos[self.array[j][1]] = i temp = self.array[i] self.array[i] = self.array[j] self.array[j] = temp def decrease_key(self, tup, new_d): idx = self.pos[tup[1]] # assuming the new_d is atmost old_d self.array[idx] = (new_d, tup[1]) while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]: self.swap(idx, self.par(idx)) idx = self.par(idx) class Graph: def __init__(self, num): self.adjList = {} # To store graph: u -> (v,w) self.num_nodes = num # Number of nodes in graph # To store the distance from source vertex self.dist = [0] * self.num_nodes self.par = [-1] * self.num_nodes # To store the path def add_edge(self, u, v, w): # Edge going from node u to v and v to u with weight w # u (w)-> v, v (w) -> u # Check if u already in graph if u in self.adjList.keys(): self.adjList[u].append((v, w)) else: self.adjList[u] = [(v, w)] # Assuming undirected graph if v in self.adjList.keys(): self.adjList[v].append((u, w)) else: self.adjList[v] = [(u, w)] def show_graph(self): # u -> v(w) for u in self.adjList: print(u, "->", " -> ".join(str(f"{v}({w})") for v, w in self.adjList[u])) def dijkstra(self, src): # Flush old junk values in par[] self.par = [-1] * self.num_nodes # src is the source node self.dist[src] = 0 Q = PriorityQueue() Q.insert((0, src)) # (dist from src, node) for u in self.adjList.keys(): if u != src: self.dist[u] = sys.maxsize # Infinity self.par[u] = -1 while not Q.isEmpty(): u = Q.extract_min() # Returns node with the min dist from source # Update the distance of all the neighbours of u and # if their prev dist was INFINITY then push them in Q for v, w in self.adjList[u]: new_dist = self.dist[u] + w if self.dist[v] > new_dist: if self.dist[v] == sys.maxsize: Q.insert((new_dist, v)) else: Q.decrease_key((self.dist[v], v), new_dist) self.dist[v] = new_dist self.par[v] = u # Show the shortest distances from src self.show_distances(src) def show_distances(self, src): print(f"Distance from node: {src}") for u in range(self.num_nodes): print(f"Node {u} has distance: {self.dist[u]}") def show_path(self, src, dest): # To show the shortest path from src to dest # WARNING: Use it *after* calling dijkstra path = [] cost = 0 temp = dest # Backtracking from dest to src while self.par[temp] != -1: path.append(temp) if temp != src: for v, w in self.adjList[temp]: if v == self.par[temp]: cost += w break temp = self.par[temp] path.append(src) path.reverse() print(f"----Path to reach {dest} from {src}----") for u in path: print(f"{u}", end=" ") if u != dest: print("-> ", end="") print("\nTotal cost of path: ", cost) if __name__ == "__main__": graph = Graph(9) graph.add_edge(0, 1, 4) graph.add_edge(0, 7, 8) graph.add_edge(1, 2, 8) graph.add_edge(1, 7, 11) graph.add_edge(2, 3, 7) graph.add_edge(2, 8, 2) graph.add_edge(2, 5, 4) graph.add_edge(3, 4, 9) graph.add_edge(3, 5, 14) graph.add_edge(4, 5, 10) graph.add_edge(5, 6, 2) graph.add_edge(6, 7, 1) graph.add_edge(6, 8, 6) graph.add_edge(7, 8, 7) graph.show_graph() graph.dijkstra(0) graph.show_path(0, 4) # OUTPUT # 0 -> 1(4) -> 7(8) # 1 -> 0(4) -> 2(8) -> 7(11) # 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7) # 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4) # 3 -> 2(7) -> 4(9) -> 5(14) # 8 -> 2(2) -> 6(6) -> 7(7) # 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2) # 4 -> 3(9) -> 5(10) # 6 -> 5(2) -> 7(1) -> 8(6) # Distance from node: 0 # Node 0 has distance: 0 # Node 1 has distance: 4 # Node 2 has distance: 12 # Node 3 has distance: 19 # Node 4 has distance: 21 # Node 5 has distance: 11 # Node 6 has distance: 9 # Node 7 has distance: 8 # Node 8 has distance: 14 # ----Path to reach 4 from 0---- # 0 -> 7 -> 6 -> 5 -> 4 # Total cost of path: 21
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch # Author: Shubham Malik # References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm import math import sys # For storing the vertex set to retrieve node with the lowest distance class PriorityQueue: # Based on Min Heap def __init__(self): self.cur_size = 0 self.array = [] self.pos = {} # To store the pos of node in array def isEmpty(self): return self.cur_size == 0 def min_heapify(self, idx): lc = self.left(idx) rc = self.right(idx) if lc < self.cur_size and self.array(lc)[0] < self.array(idx)[0]: smallest = lc else: smallest = idx if rc < self.cur_size and self.array(rc)[0] < self.array(smallest)[0]: smallest = rc if smallest != idx: self.swap(idx, smallest) self.min_heapify(smallest) def insert(self, tup): # Inserts a node into the Priority Queue self.pos[tup[1]] = self.cur_size self.cur_size += 1 self.array.append((sys.maxsize, tup[1])) self.decrease_key((sys.maxsize, tup[1]), tup[0]) def extract_min(self): # Removes and returns the min element at top of priority queue min_node = self.array[0][1] self.array[0] = self.array[self.cur_size - 1] self.cur_size -= 1 self.min_heapify(1) del self.pos[min_node] return min_node def left(self, i): # returns the index of left child return 2 * i + 1 def right(self, i): # returns the index of right child return 2 * i + 2 def par(self, i): # returns the index of parent return math.floor(i / 2) def swap(self, i, j): # swaps array elements at indices i and j # update the pos{} self.pos[self.array[i][1]] = j self.pos[self.array[j][1]] = i temp = self.array[i] self.array[i] = self.array[j] self.array[j] = temp def decrease_key(self, tup, new_d): idx = self.pos[tup[1]] # assuming the new_d is atmost old_d self.array[idx] = (new_d, tup[1]) while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]: self.swap(idx, self.par(idx)) idx = self.par(idx) class Graph: def __init__(self, num): self.adjList = {} # To store graph: u -> (v,w) self.num_nodes = num # Number of nodes in graph # To store the distance from source vertex self.dist = [0] * self.num_nodes self.par = [-1] * self.num_nodes # To store the path def add_edge(self, u, v, w): # Edge going from node u to v and v to u with weight w # u (w)-> v, v (w) -> u # Check if u already in graph if u in self.adjList.keys(): self.adjList[u].append((v, w)) else: self.adjList[u] = [(v, w)] # Assuming undirected graph if v in self.adjList.keys(): self.adjList[v].append((u, w)) else: self.adjList[v] = [(u, w)] def show_graph(self): # u -> v(w) for u in self.adjList: print(u, "->", " -> ".join(str(f"{v}({w})") for v, w in self.adjList[u])) def dijkstra(self, src): # Flush old junk values in par[] self.par = [-1] * self.num_nodes # src is the source node self.dist[src] = 0 Q = PriorityQueue() Q.insert((0, src)) # (dist from src, node) for u in self.adjList.keys(): if u != src: self.dist[u] = sys.maxsize # Infinity self.par[u] = -1 while not Q.isEmpty(): u = Q.extract_min() # Returns node with the min dist from source # Update the distance of all the neighbours of u and # if their prev dist was INFINITY then push them in Q for v, w in self.adjList[u]: new_dist = self.dist[u] + w if self.dist[v] > new_dist: if self.dist[v] == sys.maxsize: Q.insert((new_dist, v)) else: Q.decrease_key((self.dist[v], v), new_dist) self.dist[v] = new_dist self.par[v] = u # Show the shortest distances from src self.show_distances(src) def show_distances(self, src): print(f"Distance from node: {src}") for u in range(self.num_nodes): print(f"Node {u} has distance: {self.dist[u]}") def show_path(self, src, dest): # To show the shortest path from src to dest # WARNING: Use it *after* calling dijkstra path = [] cost = 0 temp = dest # Backtracking from dest to src while self.par[temp] != -1: path.append(temp) if temp != src: for v, w in self.adjList[temp]: if v == self.par[temp]: cost += w break temp = self.par[temp] path.append(src) path.reverse() print(f"----Path to reach {dest} from {src}----") for u in path: print(f"{u}", end=" ") if u != dest: print("-> ", end="") print("\nTotal cost of path: ", cost) if __name__ == "__main__": graph = Graph(9) graph.add_edge(0, 1, 4) graph.add_edge(0, 7, 8) graph.add_edge(1, 2, 8) graph.add_edge(1, 7, 11) graph.add_edge(2, 3, 7) graph.add_edge(2, 8, 2) graph.add_edge(2, 5, 4) graph.add_edge(3, 4, 9) graph.add_edge(3, 5, 14) graph.add_edge(4, 5, 10) graph.add_edge(5, 6, 2) graph.add_edge(6, 7, 1) graph.add_edge(6, 8, 6) graph.add_edge(7, 8, 7) graph.show_graph() graph.dijkstra(0) graph.show_path(0, 4) # OUTPUT # 0 -> 1(4) -> 7(8) # 1 -> 0(4) -> 2(8) -> 7(11) # 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7) # 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4) # 3 -> 2(7) -> 4(9) -> 5(14) # 8 -> 2(2) -> 6(6) -> 7(7) # 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2) # 4 -> 3(9) -> 5(10) # 6 -> 5(2) -> 7(1) -> 8(6) # Distance from node: 0 # Node 0 has distance: 0 # Node 1 has distance: 4 # Node 2 has distance: 12 # Node 3 has distance: 19 # Node 4 has distance: 21 # Node 5 has distance: 11 # Node 6 has distance: 9 # Node 7 has distance: 8 # Node 8 has distance: 14 # ----Path to reach 4 from 0---- # 0 -> 7 -> 6 -> 5 -> 4 # Total cost of path: 21
-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 script demonstrates the implementation of the Sigmoid function. The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)). After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Sigmoid_function """ import numpy as np def sigmoid(vector: np.array) -> np.array: """ Implements the sigmoid function Parameters: vector (np.array): A numpy array of shape (1,n) consisting of real values Returns: sigmoid_vec (np.array): The input numpy array, after applying sigmoid. Examples: >>> sigmoid(np.array([-1.0, 1.0, 2.0])) array([0.26894142, 0.73105858, 0.88079708]) >>> sigmoid(np.array([0.0])) array([0.5]) """ return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest doctest.testmod()
""" This script demonstrates the implementation of the Sigmoid function. The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)). After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Sigmoid_function """ import numpy as np def sigmoid(vector: np.array) -> np.array: """ Implements the sigmoid function Parameters: vector (np.array): A numpy array of shape (1,n) consisting of real values Returns: sigmoid_vec (np.array): The input numpy array, after applying sigmoid. Examples: >>> sigmoid(np.array([-1.0, 1.0, 2.0])) array([0.26894142, 0.73105858, 0.88079708]) >>> sigmoid(np.array([0.0])) array([0.5]) """ return 1 / (1 + np.exp(-vector)) 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 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2 ** power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2 ** power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
-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 Newton Raphson method in Python # Author: Syed Haseeb Shah (github.com/QuantumNovice) # The Newton-Raphson method (also known as Newton's method) is a way to # quickly find a good approximation for the root of a real-valued function from decimal import Decimal from math import * # noqa: F401, F403 from typing import Union from sympy import diff def newton_raphson( func: str, a: Union[float, Decimal], precision: float = 10 ** -10 ) -> float: """Finds root from the point 'a' onwards by Newton-Raphson method >>> newton_raphson("sin(x)", 2) 3.1415926536808043 >>> newton_raphson("x**2 - 5*x +2", 0.4) 0.4384471871911695 >>> newton_raphson("x**2 - 5", 0.1) 2.23606797749979 >>> newton_raphson("log(x)- 1", 2) 2.718281828458938 """ x = a while True: x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func))))) # This number dictates the accuracy of the answer if abs(eval(func)) < precision: return float(x) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(f"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(f"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
# Implementing Newton Raphson method in Python # Author: Syed Haseeb Shah (github.com/QuantumNovice) # The Newton-Raphson method (also known as Newton's method) is a way to # quickly find a good approximation for the root of a real-valued function from decimal import Decimal from math import * # noqa: F401, F403 from typing import Union from sympy import diff def newton_raphson( func: str, a: Union[float, Decimal], precision: float = 10 ** -10 ) -> float: """Finds root from the point 'a' onwards by Newton-Raphson method >>> newton_raphson("sin(x)", 2) 3.1415926536808043 >>> newton_raphson("x**2 - 5*x +2", 0.4) 0.4384471871911695 >>> newton_raphson("x**2 - 5", 0.1) 2.23606797749979 >>> newton_raphson("log(x)- 1", 2) 2.718281828458938 """ x = a while True: x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func))))) # This number dictates the accuracy of the answer if abs(eval(func)) < precision: return float(x) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(f"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(f"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
-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}`.
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from typing import List def peak(lst: List[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from typing import List def peak(lst: List[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) 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/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from .balanced_parentheses import balanced_parentheses from .stack import Stack def precedence(char: str) -> int: """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) def infix_to_postfix(expression_str: str) -> str: """ >>> infix_to_postfix("(1*(2+3)+4))") Traceback (most recent call last): ... ValueError: Mismatched parentheses >>> infix_to_postfix("") '' >>> infix_to_postfix("3+2") '3 2 +' >>> infix_to_postfix("(3+4)*5-6") '3 4 + 5 * 6 -' >>> infix_to_postfix("(1+2)*3/4-5") '1 2 + 3 * 4 / 5 -' >>> infix_to_postfix("a+b*c+(d*e+f)*g") 'a b c * + d e * f + g * +' >>> infix_to_postfix("x^y/(5*z)+2") 'x y ^ 5 z * / 2 +' """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while not stack.is_empty() and precedence(char) <= precedence(stack.peek()): postfix.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
""" https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from .balanced_parentheses import balanced_parentheses from .stack import Stack def precedence(char: str) -> int: """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) def infix_to_postfix(expression_str: str) -> str: """ >>> infix_to_postfix("(1*(2+3)+4))") Traceback (most recent call last): ... ValueError: Mismatched parentheses >>> infix_to_postfix("") '' >>> infix_to_postfix("3+2") '3 2 +' >>> infix_to_postfix("(3+4)*5-6") '3 4 + 5 * 6 -' >>> infix_to_postfix("(1+2)*3/4-5") '1 2 + 3 * 4 / 5 -' >>> infix_to_postfix("a+b*c+(d*e+f)*g") 'a b c * + d e * f + g * +' >>> infix_to_postfix("x^y/(5*z)+2") 'x y ^ 5 z * / 2 +' """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while not stack.is_empty() and precedence(char) <= precedence(stack.peek()): postfix.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
-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 oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("19") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function """ oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number if __name__ == "__main__": from doctest import testmod testmod()
def oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("19") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function """ oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number 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}`.
""" Problem 123: https://projecteuler.net/problem=123 Name: Prime square remainders Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn−1)^n + (pn+1)^n is divided by pn^2. For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25. The least value of n for which the remainder first exceeds 10^9 is 7037. Find the least value of n for which the remainder first exceeds 10^10. Solution: n=1: (p-1) + (p+1) = 2p n=2: (p-1)^2 + (p+1)^2 = p^2 + 1 - 2p + p^2 + 1 + 2p (Using (p+b)^2 = (p^2 + b^2 + 2pb), (p-b)^2 = (p^2 + b^2 - 2pb) and b = 1) = 2p^2 + 2 n=3: (p-1)^3 + (p+1)^3 (Similarly using (p+b)^3 & (p-b)^3 formula and so on) = 2p^3 + 6p n=4: 2p^4 + 12p^2 + 2 n=5: 2p^5 + 20p^3 + 10p As you could see, when the expression is divided by p^2. Except for the last term, the rest will result in the remainder 0. n=1: 2p n=2: 2 n=3: 6p n=4: 2 n=5: 10p So it could be simplified as, r = 2pn when n is odd r = 2 when n is even. """ from typing import Dict, Generator def sieve() -> Generator[int, None, None]: """ Returns a prime number generator using sieve method. >>> type(sieve()) <class 'generator'> >>> primes = sieve() >>> next(primes) 2 >>> next(primes) 3 >>> next(primes) 5 >>> next(primes) 7 >>> next(primes) 11 >>> next(primes) 13 """ factor_map: Dict[int, int] = {} prime = 2 while True: factor = factor_map.pop(prime, None) if factor: x = factor + prime while x in factor_map: x += factor factor_map[x] = factor else: factor_map[prime * prime] = prime yield prime prime += 1 def solution(limit: float = 1e10) -> int: """ Returns the least value of n for which the remainder first exceeds 10^10. >>> solution(1e8) 2371 >>> solution(1e9) 7037 """ primes = sieve() n = 1 while True: prime = next(primes) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(primes) n += 2 if __name__ == "__main__": print(solution())
""" Problem 123: https://projecteuler.net/problem=123 Name: Prime square remainders Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn−1)^n + (pn+1)^n is divided by pn^2. For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25. The least value of n for which the remainder first exceeds 10^9 is 7037. Find the least value of n for which the remainder first exceeds 10^10. Solution: n=1: (p-1) + (p+1) = 2p n=2: (p-1)^2 + (p+1)^2 = p^2 + 1 - 2p + p^2 + 1 + 2p (Using (p+b)^2 = (p^2 + b^2 + 2pb), (p-b)^2 = (p^2 + b^2 - 2pb) and b = 1) = 2p^2 + 2 n=3: (p-1)^3 + (p+1)^3 (Similarly using (p+b)^3 & (p-b)^3 formula and so on) = 2p^3 + 6p n=4: 2p^4 + 12p^2 + 2 n=5: 2p^5 + 20p^3 + 10p As you could see, when the expression is divided by p^2. Except for the last term, the rest will result in the remainder 0. n=1: 2p n=2: 2 n=3: 6p n=4: 2 n=5: 10p So it could be simplified as, r = 2pn when n is odd r = 2 when n is even. """ from typing import Dict, Generator def sieve() -> Generator[int, None, None]: """ Returns a prime number generator using sieve method. >>> type(sieve()) <class 'generator'> >>> primes = sieve() >>> next(primes) 2 >>> next(primes) 3 >>> next(primes) 5 >>> next(primes) 7 >>> next(primes) 11 >>> next(primes) 13 """ factor_map: Dict[int, int] = {} prime = 2 while True: factor = factor_map.pop(prime, None) if factor: x = factor + prime while x in factor_map: x += factor factor_map[x] = factor else: factor_map[prime * prime] = prime yield prime prime += 1 def solution(limit: float = 1e10) -> int: """ Returns the least value of n for which the remainder first exceeds 10^10. >>> solution(1e8) 2371 >>> solution(1e9) 7037 """ primes = sieve() n = 1 while True: prime = next(primes) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(primes) n += 2 if __name__ == "__main__": print(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}`.
""" Functions for 2D matrix operations """ from __future__ import annotations def add(*matrix_s: list[list]) -> list[list]: """ >>> add([[1,2],[3,4]],[[2,3],[4,5]]) [[3, 5], [7, 9]] >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]]) [[3.2, 5.4], [7, 9]] >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]]) [[7, 14], [12, 16]] """ if all(_check_not_integer(m) for m in matrix_s): for i in matrix_s[1:]: _verify_matrix_sizes(matrix_s[0], i) return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]: """ >>> subtract([[1,2],[3,4]],[[2,3],[4,5]]) [[-1, -1], [-1, -1]] >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]]) [[-1, -0.5], [-1, -1.5]] """ if ( _check_not_integer(matrix_a) and _check_not_integer(matrix_b) and _verify_matrix_sizes(matrix_a, matrix_b) ): return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] def scalar_multiply(matrix: list[list], n: int) -> list[list]: """ >>> scalar_multiply([[1,2],[3,4]],5) [[5, 10], [15, 20]] >>> scalar_multiply([[1.4,2.3],[3,4]],5) [[7.0, 11.5], [15, 20]] """ return [[x * n for x in row] for row in matrix] def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]: """ >>> multiply([[1,2],[3,4]],[[5,5],[7,5]]) [[19, 15], [43, 35]] >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]]) [[22.5, 17.5], [46.5, 37.5]] >>> multiply([[1, 2, 3]], [[2], [3], [4]]) [[20]] """ if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) if cols[0] != rows[1]: raise ValueError( f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) " f"and ({rows[1]},{cols[1]})" ) return [ [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a ] def identity(n: int) -> list[list]: """ :param n: dimension for nxn matrix :type n: int :return: Identity matrix of shape [n, n] >>> identity(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] """ n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] def transpose(matrix: list[list], return_map: bool = True) -> list[list]: """ >>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS <map object at ... >>> transpose([[1,2],[3,4]], return_map=False) [[1, 3], [2, 4]] """ if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) else: return list(map(list, zip(*matrix))) def minor(matrix: list[list], row: int, column: int) -> list[list]: """ >>> minor([[1, 2], [3, 4]], 1, 1) [[1]] """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor] def determinant(matrix: list[list]) -> int: """ >>> determinant([[1, 2], [3, 4]]) -2 >>> determinant([[1.5, 2.5], [3, 4]]) -1.5 """ if len(matrix) == 1: return matrix[0][0] return sum( x * determinant(minor(matrix, 0, i)) * (-1) ** i for i, x in enumerate(matrix[0]) ) def inverse(matrix: list[list]) -> list[list]: """ >>> inverse([[1, 2], [3, 4]]) [[-2.0, 1.0], [1.5, -0.5]] >>> inverse([[1, 1], [1, 1]]) """ # https://stackoverflow.com/questions/20047519/python-doctests-test-for-none det = determinant(matrix) if det == 0: return None matrix_minor = [ [determinant(minor(matrix, i, j)) for j in range(len(matrix))] for i in range(len(matrix)) ] cofactors = [ [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix)) ] adjugate = transpose(cofactors) return scalar_multiply(adjugate, 1 / det) def _check_not_integer(matrix: list[list]) -> bool: if not isinstance(matrix, int) and not isinstance(matrix[0], int): return True raise TypeError("Expected a matrix, got int/list instead") def _shape(matrix: list[list]) -> list: return len(matrix), len(matrix[0]) def _verify_matrix_sizes(matrix_a: list[list], matrix_b: list[list]) -> tuple[list]: shape = _shape(matrix_a) + _shape(matrix_b) if shape[0] != shape[3] or shape[1] != shape[2]: raise ValueError( f"operands could not be broadcast together with shape " f"({shape[0], shape[1]}), ({shape[2], shape[3]})" ) return (shape[0], shape[2]), (shape[1], shape[3]) def main(): matrix_a = [[12, 10], [3, 9]] matrix_b = [[3, 4], [7, 4]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print(f"Add Operation, {add(matrix_a, matrix_b) = } \n") print( f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n", ) print(f"Identity: {identity(5)}\n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n") print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n") if __name__ == "__main__": import doctest doctest.testmod() main()
""" Functions for 2D matrix operations """ from __future__ import annotations def add(*matrix_s: list[list]) -> list[list]: """ >>> add([[1,2],[3,4]],[[2,3],[4,5]]) [[3, 5], [7, 9]] >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]]) [[3.2, 5.4], [7, 9]] >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]]) [[7, 14], [12, 16]] """ if all(_check_not_integer(m) for m in matrix_s): for i in matrix_s[1:]: _verify_matrix_sizes(matrix_s[0], i) return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]: """ >>> subtract([[1,2],[3,4]],[[2,3],[4,5]]) [[-1, -1], [-1, -1]] >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]]) [[-1, -0.5], [-1, -1.5]] """ if ( _check_not_integer(matrix_a) and _check_not_integer(matrix_b) and _verify_matrix_sizes(matrix_a, matrix_b) ): return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] def scalar_multiply(matrix: list[list], n: int) -> list[list]: """ >>> scalar_multiply([[1,2],[3,4]],5) [[5, 10], [15, 20]] >>> scalar_multiply([[1.4,2.3],[3,4]],5) [[7.0, 11.5], [15, 20]] """ return [[x * n for x in row] for row in matrix] def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]: """ >>> multiply([[1,2],[3,4]],[[5,5],[7,5]]) [[19, 15], [43, 35]] >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]]) [[22.5, 17.5], [46.5, 37.5]] >>> multiply([[1, 2, 3]], [[2], [3], [4]]) [[20]] """ if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) if cols[0] != rows[1]: raise ValueError( f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) " f"and ({rows[1]},{cols[1]})" ) return [ [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a ] def identity(n: int) -> list[list]: """ :param n: dimension for nxn matrix :type n: int :return: Identity matrix of shape [n, n] >>> identity(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] """ n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] def transpose(matrix: list[list], return_map: bool = True) -> list[list]: """ >>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS <map object at ... >>> transpose([[1,2],[3,4]], return_map=False) [[1, 3], [2, 4]] """ if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) else: return list(map(list, zip(*matrix))) def minor(matrix: list[list], row: int, column: int) -> list[list]: """ >>> minor([[1, 2], [3, 4]], 1, 1) [[1]] """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor] def determinant(matrix: list[list]) -> int: """ >>> determinant([[1, 2], [3, 4]]) -2 >>> determinant([[1.5, 2.5], [3, 4]]) -1.5 """ if len(matrix) == 1: return matrix[0][0] return sum( x * determinant(minor(matrix, 0, i)) * (-1) ** i for i, x in enumerate(matrix[0]) ) def inverse(matrix: list[list]) -> list[list]: """ >>> inverse([[1, 2], [3, 4]]) [[-2.0, 1.0], [1.5, -0.5]] >>> inverse([[1, 1], [1, 1]]) """ # https://stackoverflow.com/questions/20047519/python-doctests-test-for-none det = determinant(matrix) if det == 0: return None matrix_minor = [ [determinant(minor(matrix, i, j)) for j in range(len(matrix))] for i in range(len(matrix)) ] cofactors = [ [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix)) ] adjugate = transpose(cofactors) return scalar_multiply(adjugate, 1 / det) def _check_not_integer(matrix: list[list]) -> bool: if not isinstance(matrix, int) and not isinstance(matrix[0], int): return True raise TypeError("Expected a matrix, got int/list instead") def _shape(matrix: list[list]) -> list: return len(matrix), len(matrix[0]) def _verify_matrix_sizes(matrix_a: list[list], matrix_b: list[list]) -> tuple[list]: shape = _shape(matrix_a) + _shape(matrix_b) if shape[0] != shape[3] or shape[1] != shape[2]: raise ValueError( f"operands could not be broadcast together with shape " f"({shape[0], shape[1]}), ({shape[2], shape[3]})" ) return (shape[0], shape[2]), (shape[1], shape[3]) def main(): matrix_a = [[12, 10], [3, 9]] matrix_b = [[3, 4], [7, 4]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print(f"Add Operation, {add(matrix_a, matrix_b) = } \n") print( f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n", ) print(f"Identity: {identity(5)}\n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n") print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n") if __name__ == "__main__": import doctest doctest.testmod() 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}`.
""" Project Euler Problem 301: https://projecteuler.net/problem=301 Problem Statement: Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. We'll consider the three-heap normal-play version of Nim, which works as follows: - At the start of the game there are three heaps of stones. - On each player's turn, the player may remove any positive number of stones from any single heap. - The first player unable to move (because no stones remain) loses. If (n1, n2, n3) indicates a Nim position consisting of heaps of size n1, n2, and n3, then there is a simple function, which you may look up or attempt to deduce for yourself, X(n1, n2, n3) that returns: - zero if, with perfect strategy, the player about to move will eventually lose; or - non-zero if, with perfect strategy, the player about to move will eventually win. For example X(1,2,3) = 0 because, no matter what the current player does, the opponent can respond with a move that leaves two heaps of equal size, at which point every move by the current player can be mirrored by the opponent until no stones remain; so the current player loses. To illustrate: - current player moves to (1,2,1) - opponent moves to (1,0,1) - current player moves to (0,0,1) - opponent moves to (0,0,0), and so wins. For how many positive integers n <= 2^30 does X(n,2n,3n) = 0? """ def solution(exponent: int = 30) -> int: """ For any given exponent x >= 0, 1 <= n <= 2^x. This function returns how many Nim games are lost given that each Nim game has three heaps of the form (n, 2*n, 3*n). >>> solution(0) 1 >>> solution(2) 3 >>> solution(10) 144 """ # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5 ** 0.5) / 2 fibonacci = (phi ** fibonacci_index - (phi - 1) ** fibonacci_index) / 5 ** 0.5 return int(fibonacci) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 301: https://projecteuler.net/problem=301 Problem Statement: Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. We'll consider the three-heap normal-play version of Nim, which works as follows: - At the start of the game there are three heaps of stones. - On each player's turn, the player may remove any positive number of stones from any single heap. - The first player unable to move (because no stones remain) loses. If (n1, n2, n3) indicates a Nim position consisting of heaps of size n1, n2, and n3, then there is a simple function, which you may look up or attempt to deduce for yourself, X(n1, n2, n3) that returns: - zero if, with perfect strategy, the player about to move will eventually lose; or - non-zero if, with perfect strategy, the player about to move will eventually win. For example X(1,2,3) = 0 because, no matter what the current player does, the opponent can respond with a move that leaves two heaps of equal size, at which point every move by the current player can be mirrored by the opponent until no stones remain; so the current player loses. To illustrate: - current player moves to (1,2,1) - opponent moves to (1,0,1) - current player moves to (0,0,1) - opponent moves to (0,0,0), and so wins. For how many positive integers n <= 2^30 does X(n,2n,3n) = 0? """ def solution(exponent: int = 30) -> int: """ For any given exponent x >= 0, 1 <= n <= 2^x. This function returns how many Nim games are lost given that each Nim game has three heaps of the form (n, 2*n, 3*n). >>> solution(0) 1 >>> solution(2) 3 >>> solution(10) 144 """ # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5 ** 0.5) / 2 fibonacci = (phi ** fibonacci_index - (phi - 1) ** fibonacci_index) / 5 ** 0.5 return int(fibonacci) 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}`.
from typing import List """ A naive recursive implementation of 0-1 Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ def knapsack(capacity: int, weights: List[int], values: List[int], counter: int) -> int: """ Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap, w, val, c) 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. """ # Base Case if counter == 0 or capacity == 0: return 0 # If weight of the nth item is more than Knapsack of capacity, # then this item cannot be included in the optimal solution, # else return the maximum of two cases: # (1) nth item included # (2) not included if weights[counter - 1] > capacity: return knapsack(capacity, weights, values, counter - 1) else: left_capacity = capacity - weights[counter - 1] new_value_included = values[counter - 1] + knapsack( left_capacity, weights, values, counter - 1 ) without_new_value = knapsack(capacity, weights, values, counter - 1) return max(new_value_included, without_new_value) if __name__ == "__main__": import doctest doctest.testmod()
from typing import List """ A naive recursive implementation of 0-1 Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ def knapsack(capacity: int, weights: List[int], values: List[int], counter: int) -> int: """ Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap, w, val, c) 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. """ # Base Case if counter == 0 or capacity == 0: return 0 # If weight of the nth item is more than Knapsack of capacity, # then this item cannot be included in the optimal solution, # else return the maximum of two cases: # (1) nth item included # (2) not included if weights[counter - 1] > capacity: return knapsack(capacity, weights, values, counter - 1) else: left_capacity = capacity - weights[counter - 1] new_value_included = values[counter - 1] + knapsack( left_capacity, weights, values, counter - 1 ) without_new_value = knapsack(capacity, weights, values, counter - 1) return max(new_value_included, without_new_value) 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}`.
""" In a multi-threaded download, this algorithm could be used to provide each worker thread with a block of non-overlapping bytes to download. For example: for i in allocation_list: requests.get(url,headers={'Range':f'bytes={i}'}) """ from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: """ Divide a number of bytes into x partitions. :param number_of_bytes: the total of bytes. :param partitions: the number of partition need to be allocated. :return: list of bytes to be assigned to each worker thread >>> allocation_num(16647, 4) ['1-4161', '4162-8322', '8323-12483', '12484-16647'] >>> allocation_num(50000, 5) ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000'] >>> allocation_num(888, 999) Traceback (most recent call last): ... ValueError: partitions can not > number_of_bytes! >>> allocation_num(888, -4) Traceback (most recent call last): ... ValueError: partitions must be a positive number! """ if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!") bytes_per_partition = number_of_bytes // partitions allocation_list = [] for i in range(partitions): start_bytes = i * bytes_per_partition + 1 end_bytes = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}") return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
""" In a multi-threaded download, this algorithm could be used to provide each worker thread with a block of non-overlapping bytes to download. For example: for i in allocation_list: requests.get(url,headers={'Range':f'bytes={i}'}) """ from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: """ Divide a number of bytes into x partitions. :param number_of_bytes: the total of bytes. :param partitions: the number of partition need to be allocated. :return: list of bytes to be assigned to each worker thread >>> allocation_num(16647, 4) ['1-4161', '4162-8322', '8323-12483', '12484-16647'] >>> allocation_num(50000, 5) ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000'] >>> allocation_num(888, 999) Traceback (most recent call last): ... ValueError: partitions can not > number_of_bytes! >>> allocation_num(888, -4) Traceback (most recent call last): ... ValueError: partitions must be a positive number! """ if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!") bytes_per_partition = number_of_bytes // partitions allocation_list = [] for i in range(partitions): start_bytes = i * bytes_per_partition + 1 end_bytes = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}") return allocation_list 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}`.
""" Coin sums Problem 31: https://projecteuler.net/problem=31 In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? """ def one_pence() -> int: return 1 def two_pence(x: int) -> int: return 0 if x < 0 else two_pence(x - 2) + one_pence() def five_pence(x: int) -> int: return 0 if x < 0 else five_pence(x - 5) + two_pence(x) def ten_pence(x: int) -> int: return 0 if x < 0 else ten_pence(x - 10) + five_pence(x) def twenty_pence(x: int) -> int: return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x) def fifty_pence(x: int) -> int: return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x) def one_pound(x: int) -> int: return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x) def two_pound(x: int) -> int: return 0 if x < 0 else two_pound(x - 200) + one_pound(x) def solution(n: int = 200) -> int: """Returns the number of different ways can n pence be made using any number of coins? >>> solution(500) 6295434 >>> solution(200) 73682 >>> solution(50) 451 >>> solution(10) 11 """ return two_pound(n) if __name__ == "__main__": print(solution(int(input().strip())))
""" Coin sums Problem 31: https://projecteuler.net/problem=31 In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? """ def one_pence() -> int: return 1 def two_pence(x: int) -> int: return 0 if x < 0 else two_pence(x - 2) + one_pence() def five_pence(x: int) -> int: return 0 if x < 0 else five_pence(x - 5) + two_pence(x) def ten_pence(x: int) -> int: return 0 if x < 0 else ten_pence(x - 10) + five_pence(x) def twenty_pence(x: int) -> int: return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x) def fifty_pence(x: int) -> int: return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x) def one_pound(x: int) -> int: return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x) def two_pound(x: int) -> int: return 0 if x < 0 else two_pound(x - 200) + one_pound(x) def solution(n: int = 200) -> int: """Returns the number of different ways can n pence be made using any number of coins? >>> solution(500) 6295434 >>> solution(200) 73682 >>> solution(50) 451 >>> solution(10) 11 """ return two_pound(n) if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
4,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}`.
""" Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ from statistics import mean from typing import List def calculate_waiting_times(burst_times: List[int]) -> List[int]: """ Calculate the waiting times of a list of processes that have a specified duration. Return: The waiting time for each process. >>> calculate_waiting_times([10, 5, 8]) [13, 10, 13] >>> calculate_waiting_times([4, 6, 3, 1]) [5, 8, 9, 6] >>> calculate_waiting_times([12, 2, 10]) [12, 2, 12] """ quantum = 2 rem_burst_times = list(burst_times) waiting_times = [0] * len(burst_times) t = 0 while True: done = True for i, burst_time in enumerate(burst_times): if rem_burst_times[i] > 0: done = False if rem_burst_times[i] > quantum: t += quantum rem_burst_times[i] -= quantum else: t += rem_burst_times[i] waiting_times[i] = t - burst_time rem_burst_times[i] = 0 if done is True: return waiting_times def calculate_turn_around_times( burst_times: List[int], waiting_times: List[int] ) -> List[int]: """ >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) [1, 3, 6] >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) [20, 9, 18] """ return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] if __name__ == "__main__": burst_times = [3, 5, 7] waiting_times = calculate_waiting_times(burst_times) turn_around_times = calculate_turn_around_times(burst_times, waiting_times) print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") for i, burst_time in enumerate(burst_times): print( f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " f"{turn_around_times[i]}" ) print(f"\nAverage waiting time = {mean(waiting_times):.5f}") print(f"Average turn around time = {mean(turn_around_times):.5f}")
""" Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ from statistics import mean from typing import List def calculate_waiting_times(burst_times: List[int]) -> List[int]: """ Calculate the waiting times of a list of processes that have a specified duration. Return: The waiting time for each process. >>> calculate_waiting_times([10, 5, 8]) [13, 10, 13] >>> calculate_waiting_times([4, 6, 3, 1]) [5, 8, 9, 6] >>> calculate_waiting_times([12, 2, 10]) [12, 2, 12] """ quantum = 2 rem_burst_times = list(burst_times) waiting_times = [0] * len(burst_times) t = 0 while True: done = True for i, burst_time in enumerate(burst_times): if rem_burst_times[i] > 0: done = False if rem_burst_times[i] > quantum: t += quantum rem_burst_times[i] -= quantum else: t += rem_burst_times[i] waiting_times[i] = t - burst_time rem_burst_times[i] = 0 if done is True: return waiting_times def calculate_turn_around_times( burst_times: List[int], waiting_times: List[int] ) -> List[int]: """ >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) [1, 3, 6] >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) [20, 9, 18] """ return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] if __name__ == "__main__": burst_times = [3, 5, 7] waiting_times = calculate_waiting_times(burst_times) turn_around_times = calculate_turn_around_times(burst_times, waiting_times) print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") for i, burst_time in enumerate(burst_times): print( f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " f"{turn_around_times[i]}" ) print(f"\nAverage waiting time = {mean(waiting_times):.5f}") print(f"Average turn around time = {mean(turn_around_times):.5f}")
-1
TheAlgorithms/Python
4,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 decimal import Decimal, getcontext from math import ceil, factorial def pi(precision: int) -> str: """ The Chudnovsky algorithm is a fast method for calculating the digits of PI, based on Ramanujan’s PI formulae. https://en.wikipedia.org/wiki/Chudnovsky_algorithm PI = constant_term / ((multinomial_term * linear_term) / exponential_term) where constant_term = 426880 * sqrt(10005) The linear_term and the exponential_term can be defined iteratively as follows: L_k+1 = L_k + 545140134 where L_0 = 13591409 X_k+1 = X_k * -262537412640768000 where X_0 = 1 The multinomial_term is defined as follows: 6k! / ((3k)! * (k!) ^ 3) where k is the k_th iteration. This algorithm correctly calculates around 14 digits of PI per iteration >>> pi(10) '3.14159265' >>> pi(100) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706' >>> pi('hello') Traceback (most recent call last): ... TypeError: Undefined for non-integers >>> pi(-1) Traceback (most recent call last): ... ValueError: Undefined for non-natural numbers """ if not isinstance(precision, int): raise TypeError("Undefined for non-integers") elif precision < 1: raise ValueError("Undefined for non-natural numbers") getcontext().prec = precision num_iterations = ceil(precision / 14) constant_term = 426880 * Decimal(10005).sqrt() exponential_term = 1 linear_term = 13591409 partial_sum = Decimal(linear_term) for k in range(1, num_iterations): multinomial_term = factorial(6 * k) // (factorial(3 * k) * factorial(k) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term) / exponential_term return str(constant_term / partial_sum)[:-1] if __name__ == "__main__": n = 50 print(f"The first {n} digits of pi is: {pi(n)}")
from decimal import Decimal, getcontext from math import ceil, factorial def pi(precision: int) -> str: """ The Chudnovsky algorithm is a fast method for calculating the digits of PI, based on Ramanujan’s PI formulae. https://en.wikipedia.org/wiki/Chudnovsky_algorithm PI = constant_term / ((multinomial_term * linear_term) / exponential_term) where constant_term = 426880 * sqrt(10005) The linear_term and the exponential_term can be defined iteratively as follows: L_k+1 = L_k + 545140134 where L_0 = 13591409 X_k+1 = X_k * -262537412640768000 where X_0 = 1 The multinomial_term is defined as follows: 6k! / ((3k)! * (k!) ^ 3) where k is the k_th iteration. This algorithm correctly calculates around 14 digits of PI per iteration >>> pi(10) '3.14159265' >>> pi(100) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706' >>> pi('hello') Traceback (most recent call last): ... TypeError: Undefined for non-integers >>> pi(-1) Traceback (most recent call last): ... ValueError: Undefined for non-natural numbers """ if not isinstance(precision, int): raise TypeError("Undefined for non-integers") elif precision < 1: raise ValueError("Undefined for non-natural numbers") getcontext().prec = precision num_iterations = ceil(precision / 14) constant_term = 426880 * Decimal(10005).sqrt() exponential_term = 1 linear_term = 13591409 partial_sum = Decimal(linear_term) for k in range(1, num_iterations): multinomial_term = factorial(6 * k) // (factorial(3 * k) * factorial(k) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term) / exponential_term return str(constant_term / partial_sum)[:-1] if __name__ == "__main__": n = 50 print(f"The first {n} digits of pi is: {pi(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}`.
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
-1
TheAlgorithms/Python
4,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}`.
""" Lychrel numbers Problem 55: https://projecteuler.net/problem=55 If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? """ def is_palindrome(n: int) -> bool: """ Returns True if a number is palindrome. >>> is_palindrome(12567321) False >>> is_palindrome(1221) True >>> is_palindrome(9876789) True """ return str(n) == str(n)[::-1] def sum_reverse(n: int) -> int: """ Returns the sum of n and reverse of n. >>> sum_reverse(123) 444 >>> sum_reverse(3478) 12221 >>> sum_reverse(12) 33 """ return int(n) + int(str(n)[::-1]) def solution(limit: int = 10000) -> int: """ Returns the count of all lychrel numbers below limit. >>> solution(10000) 249 >>> solution(5000) 76 >>> solution(1000) 13 """ lychrel_nums = [] for num in range(1, limit): iterations = 0 a = num while iterations < 50: num = sum_reverse(num) iterations += 1 if is_palindrome(num): break else: lychrel_nums.append(a) return len(lychrel_nums) if __name__ == "__main__": print(f"{solution() = }")
""" Lychrel numbers Problem 55: https://projecteuler.net/problem=55 If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? """ def is_palindrome(n: int) -> bool: """ Returns True if a number is palindrome. >>> is_palindrome(12567321) False >>> is_palindrome(1221) True >>> is_palindrome(9876789) True """ return str(n) == str(n)[::-1] def sum_reverse(n: int) -> int: """ Returns the sum of n and reverse of n. >>> sum_reverse(123) 444 >>> sum_reverse(3478) 12221 >>> sum_reverse(12) 33 """ return int(n) + int(str(n)[::-1]) def solution(limit: int = 10000) -> int: """ Returns the count of all lychrel numbers below limit. >>> solution(10000) 249 >>> solution(5000) 76 >>> solution(1000) 13 """ lychrel_nums = [] for num in range(1, limit): iterations = 0 a = num while iterations < 50: num = sum_reverse(num) iterations += 1 if is_palindrome(num): break else: lychrel_nums.append(a) return len(lychrel_nums) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,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://cp-algorithms.com/string/prefix-function.html Prefix function Knuth–Morris–Pratt algorithm Different algorithm than Knuth-Morris-Pratt pattern finding E.x. Finding longest prefix which is also suffix Time Complexity: O(n) - where n is the length of the string """ def prefix_function(input_string: str) -> list: """ For the given string this function computes value for each index(i), which represents the longest coincidence of prefix and sufix for given substring (input_str[0...i]) For the value of the first element the algorithm always returns 0 >>> prefix_function("aabcdaabc") [0, 1, 0, 0, 0, 1, 2, 3, 4] >>> prefix_function("asdasdad") [0, 0, 0, 1, 2, 3, 4, 0] """ # list for the result values prefix_result = [0] * len(input_string) for i in range(1, len(input_string)): # use last results for better performance - dynamic programming j = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: j = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 prefix_result[i] = j return prefix_result def longest_prefix(input_str: str) -> int: """ Prefix-function use case Finding longest prefix which is sufix as well >>> longest_prefix("aabcdaabc") 4 >>> longest_prefix("asdasdad") 4 >>> longest_prefix("abcab") 2 """ # just returning maximum value of the array gives us answer return max(prefix_function(input_str)) if __name__ == "__main__": import doctest doctest.testmod()
""" https://cp-algorithms.com/string/prefix-function.html Prefix function Knuth–Morris–Pratt algorithm Different algorithm than Knuth-Morris-Pratt pattern finding E.x. Finding longest prefix which is also suffix Time Complexity: O(n) - where n is the length of the string """ def prefix_function(input_string: str) -> list: """ For the given string this function computes value for each index(i), which represents the longest coincidence of prefix and sufix for given substring (input_str[0...i]) For the value of the first element the algorithm always returns 0 >>> prefix_function("aabcdaabc") [0, 1, 0, 0, 0, 1, 2, 3, 4] >>> prefix_function("asdasdad") [0, 0, 0, 1, 2, 3, 4, 0] """ # list for the result values prefix_result = [0] * len(input_string) for i in range(1, len(input_string)): # use last results for better performance - dynamic programming j = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: j = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 prefix_result[i] = j return prefix_result def longest_prefix(input_str: str) -> int: """ Prefix-function use case Finding longest prefix which is sufix as well >>> longest_prefix("aabcdaabc") 4 >>> longest_prefix("asdasdad") 4 >>> longest_prefix("abcab") 2 """ # just returning maximum value of the array gives us answer return max(prefix_function(input_str)) 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}`.
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(n: int) -> bool: """ Returns boolean representing primality of given number num. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True """ for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ if n > 2: sum_of_primes = 2 else: return 0 for i in range(3, n, 2): if is_prime(i): sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(n: int) -> bool: """ Returns boolean representing primality of given number num. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True """ for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ if n > 2: sum_of_primes = 2 else: return 0 for i in range(3, n, 2): if is_prime(i): sum_of_primes += i return sum_of_primes 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}`.
""" Conversion of weight units. __author__ = "Anubhav Solanki" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Anubhav Solanki" __email__ = "anubhavsolanki0@gmail.com" USAGE : -> Import this file into their respective project. -> Use the function weight_conversion() for conversion of weight units. -> Parameters : -> from_type : From which type you want to convert -> to_type : To which type you want to convert -> value : the value which you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilogram -> Wikipedia reference: https://en.wikipedia.org/wiki/Gram -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre -> Wikipedia reference: https://en.wikipedia.org/wiki/Tonne -> Wikipedia reference: https://en.wikipedia.org/wiki/Long_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Short_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound -> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce -> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat -> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit) """ KILOGRAM_CHART = { "kilogram": 1, "gram": pow(10, 3), "milligram": pow(10, 6), "metric-ton": pow(10, -3), "long-ton": 0.0009842073, "short-ton": 0.0011023122, "pound": 2.2046244202, "ounce": 35.273990723, "carrat": 5000, "atomic-mass-unit": 6.022136652e26, } WEIGHT_TYPE_CHART = { "kilogram": 1, "gram": pow(10, -3), "milligram": pow(10, -6), "metric-ton": pow(10, 3), "long-ton": 1016.04608, "short-ton": 907.184, "pound": 0.453592, "ounce": 0.0283495, "carrat": 0.0002, "atomic-mass-unit": 1.660540199e-27, } def weight_conversion(from_type: str, to_type: str, value: float) -> float: """ Conversion of weight unit with the help of KILOGRAM_CHART "kilogram" : 1, "gram" : pow(10, 3), "milligram" : pow(10, 6), "metric-ton" : pow(10, -3), "long-ton" : 0.0009842073, "short-ton" : 0.0011023122, "pound" : 2.2046244202, "ounce" : 35.273990723, "carrat" : 5000, "atomic-mass-unit" : 6.022136652E+26 >>> weight_conversion("kilogram","kilogram",4) 4 >>> weight_conversion("kilogram","gram",1) 1000 >>> weight_conversion("kilogram","milligram",4) 4000000 >>> weight_conversion("kilogram","metric-ton",4) 0.004 >>> weight_conversion("kilogram","long-ton",3) 0.0029526219 >>> weight_conversion("kilogram","short-ton",1) 0.0011023122 >>> weight_conversion("kilogram","pound",4) 8.8184976808 >>> weight_conversion("kilogram","ounce",4) 141.095962892 >>> weight_conversion("kilogram","carrat",3) 15000 >>> weight_conversion("kilogram","atomic-mass-unit",1) 6.022136652e+26 >>> weight_conversion("gram","kilogram",1) 0.001 >>> weight_conversion("gram","gram",3) 3.0 >>> weight_conversion("gram","milligram",2) 2000.0 >>> weight_conversion("gram","metric-ton",4) 4e-06 >>> weight_conversion("gram","long-ton",3) 2.9526219e-06 >>> weight_conversion("gram","short-ton",3) 3.3069366000000003e-06 >>> weight_conversion("gram","pound",3) 0.0066138732606 >>> weight_conversion("gram","ounce",1) 0.035273990723 >>> weight_conversion("gram","carrat",2) 10.0 >>> weight_conversion("gram","atomic-mass-unit",1) 6.022136652e+23 >>> weight_conversion("milligram","kilogram",1) 1e-06 >>> weight_conversion("milligram","gram",2) 0.002 >>> weight_conversion("milligram","milligram",3) 3.0 >>> weight_conversion("milligram","metric-ton",3) 3e-09 >>> weight_conversion("milligram","long-ton",3) 2.9526219e-09 >>> weight_conversion("milligram","short-ton",1) 1.1023122e-09 >>> weight_conversion("milligram","pound",3) 6.6138732605999995e-06 >>> weight_conversion("milligram","ounce",2) 7.054798144599999e-05 >>> weight_conversion("milligram","carrat",1) 0.005 >>> weight_conversion("milligram","atomic-mass-unit",1) 6.022136652e+20 >>> weight_conversion("metric-ton","kilogram",2) 2000 >>> weight_conversion("metric-ton","gram",2) 2000000 >>> weight_conversion("metric-ton","milligram",3) 3000000000 >>> weight_conversion("metric-ton","metric-ton",2) 2.0 >>> weight_conversion("metric-ton","long-ton",3) 2.9526219 >>> weight_conversion("metric-ton","short-ton",2) 2.2046244 >>> weight_conversion("metric-ton","pound",3) 6613.8732606 >>> weight_conversion("metric-ton","ounce",4) 141095.96289199998 >>> weight_conversion("metric-ton","carrat",4) 20000000 >>> weight_conversion("metric-ton","atomic-mass-unit",1) 6.022136652e+29 >>> weight_conversion("long-ton","kilogram",4) 4064.18432 >>> weight_conversion("long-ton","gram",4) 4064184.32 >>> weight_conversion("long-ton","milligram",3) 3048138240.0 >>> weight_conversion("long-ton","metric-ton",4) 4.06418432 >>> weight_conversion("long-ton","long-ton",3) 2.999999907217152 >>> weight_conversion("long-ton","short-ton",1) 1.119999989746176 >>> weight_conversion("long-ton","pound",3) 6720.000000049448 >>> weight_conversion("long-ton","ounce",1) 35840.000000060514 >>> weight_conversion("long-ton","carrat",4) 20320921.599999998 >>> weight_conversion("long-ton","atomic-mass-unit",4) 2.4475073353955697e+30 >>> weight_conversion("short-ton","kilogram",3) 2721.5519999999997 >>> weight_conversion("short-ton","gram",3) 2721552.0 >>> weight_conversion("short-ton","milligram",1) 907184000.0 >>> weight_conversion("short-ton","metric-ton",4) 3.628736 >>> weight_conversion("short-ton","long-ton",3) 2.6785713457296 >>> weight_conversion("short-ton","short-ton",3) 2.9999999725344 >>> weight_conversion("short-ton","pound",2) 4000.0000000294335 >>> weight_conversion("short-ton","ounce",4) 128000.00000021611 >>> weight_conversion("short-ton","carrat",4) 18143680.0 >>> weight_conversion("short-ton","atomic-mass-unit",1) 5.463186016507968e+29 >>> weight_conversion("pound","kilogram",4) 1.814368 >>> weight_conversion("pound","gram",2) 907.184 >>> weight_conversion("pound","milligram",3) 1360776.0 >>> weight_conversion("pound","metric-ton",3) 0.001360776 >>> weight_conversion("pound","long-ton",2) 0.0008928571152432 >>> weight_conversion("pound","short-ton",1) 0.0004999999954224 >>> weight_conversion("pound","pound",3) 3.0000000000220752 >>> weight_conversion("pound","ounce",1) 16.000000000027015 >>> weight_conversion("pound","carrat",1) 2267.96 >>> weight_conversion("pound","atomic-mass-unit",4) 1.0926372033015936e+27 >>> weight_conversion("ounce","kilogram",3) 0.0850485 >>> weight_conversion("ounce","gram",3) 85.0485 >>> weight_conversion("ounce","milligram",4) 113398.0 >>> weight_conversion("ounce","metric-ton",4) 0.000113398 >>> weight_conversion("ounce","long-ton",4) 0.0001116071394054 >>> weight_conversion("ounce","short-ton",4) 0.0001249999988556 >>> weight_conversion("ounce","pound",1) 0.0625000000004599 >>> weight_conversion("ounce","ounce",2) 2.000000000003377 >>> weight_conversion("ounce","carrat",1) 141.7475 >>> weight_conversion("ounce","atomic-mass-unit",1) 1.70724563015874e+25 >>> weight_conversion("carrat","kilogram",1) 0.0002 >>> weight_conversion("carrat","gram",4) 0.8 >>> weight_conversion("carrat","milligram",2) 400.0 >>> weight_conversion("carrat","metric-ton",2) 4.0000000000000003e-07 >>> weight_conversion("carrat","long-ton",3) 5.9052438e-07 >>> weight_conversion("carrat","short-ton",4) 8.818497600000002e-07 >>> weight_conversion("carrat","pound",1) 0.00044092488404000004 >>> weight_conversion("carrat","ounce",2) 0.0141095962892 >>> weight_conversion("carrat","carrat",4) 4.0 >>> weight_conversion("carrat","atomic-mass-unit",4) 4.8177093216e+23 >>> weight_conversion("atomic-mass-unit","kilogram",4) 6.642160796e-27 >>> weight_conversion("atomic-mass-unit","gram",2) 3.321080398e-24 >>> weight_conversion("atomic-mass-unit","milligram",2) 3.3210803980000002e-21 >>> weight_conversion("atomic-mass-unit","metric-ton",3) 4.9816205970000004e-30 >>> weight_conversion("atomic-mass-unit","long-ton",3) 4.9029473573977584e-30 >>> weight_conversion("atomic-mass-unit","short-ton",1) 1.830433719948128e-30 >>> weight_conversion("atomic-mass-unit","pound",3) 1.0982602420317504e-26 >>> weight_conversion("atomic-mass-unit","ounce",2) 1.1714775914938915e-25 >>> weight_conversion("atomic-mass-unit","carrat",2) 1.660540199e-23 >>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2) 1.999999998903455 """ if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: raise ValueError( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" ) return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] if __name__ == "__main__": import doctest doctest.testmod()
""" Conversion of weight units. __author__ = "Anubhav Solanki" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Anubhav Solanki" __email__ = "anubhavsolanki0@gmail.com" USAGE : -> Import this file into their respective project. -> Use the function weight_conversion() for conversion of weight units. -> Parameters : -> from_type : From which type you want to convert -> to_type : To which type you want to convert -> value : the value which you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilogram -> Wikipedia reference: https://en.wikipedia.org/wiki/Gram -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre -> Wikipedia reference: https://en.wikipedia.org/wiki/Tonne -> Wikipedia reference: https://en.wikipedia.org/wiki/Long_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Short_ton -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound -> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce -> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat -> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit) """ KILOGRAM_CHART = { "kilogram": 1, "gram": pow(10, 3), "milligram": pow(10, 6), "metric-ton": pow(10, -3), "long-ton": 0.0009842073, "short-ton": 0.0011023122, "pound": 2.2046244202, "ounce": 35.273990723, "carrat": 5000, "atomic-mass-unit": 6.022136652e26, } WEIGHT_TYPE_CHART = { "kilogram": 1, "gram": pow(10, -3), "milligram": pow(10, -6), "metric-ton": pow(10, 3), "long-ton": 1016.04608, "short-ton": 907.184, "pound": 0.453592, "ounce": 0.0283495, "carrat": 0.0002, "atomic-mass-unit": 1.660540199e-27, } def weight_conversion(from_type: str, to_type: str, value: float) -> float: """ Conversion of weight unit with the help of KILOGRAM_CHART "kilogram" : 1, "gram" : pow(10, 3), "milligram" : pow(10, 6), "metric-ton" : pow(10, -3), "long-ton" : 0.0009842073, "short-ton" : 0.0011023122, "pound" : 2.2046244202, "ounce" : 35.273990723, "carrat" : 5000, "atomic-mass-unit" : 6.022136652E+26 >>> weight_conversion("kilogram","kilogram",4) 4 >>> weight_conversion("kilogram","gram",1) 1000 >>> weight_conversion("kilogram","milligram",4) 4000000 >>> weight_conversion("kilogram","metric-ton",4) 0.004 >>> weight_conversion("kilogram","long-ton",3) 0.0029526219 >>> weight_conversion("kilogram","short-ton",1) 0.0011023122 >>> weight_conversion("kilogram","pound",4) 8.8184976808 >>> weight_conversion("kilogram","ounce",4) 141.095962892 >>> weight_conversion("kilogram","carrat",3) 15000 >>> weight_conversion("kilogram","atomic-mass-unit",1) 6.022136652e+26 >>> weight_conversion("gram","kilogram",1) 0.001 >>> weight_conversion("gram","gram",3) 3.0 >>> weight_conversion("gram","milligram",2) 2000.0 >>> weight_conversion("gram","metric-ton",4) 4e-06 >>> weight_conversion("gram","long-ton",3) 2.9526219e-06 >>> weight_conversion("gram","short-ton",3) 3.3069366000000003e-06 >>> weight_conversion("gram","pound",3) 0.0066138732606 >>> weight_conversion("gram","ounce",1) 0.035273990723 >>> weight_conversion("gram","carrat",2) 10.0 >>> weight_conversion("gram","atomic-mass-unit",1) 6.022136652e+23 >>> weight_conversion("milligram","kilogram",1) 1e-06 >>> weight_conversion("milligram","gram",2) 0.002 >>> weight_conversion("milligram","milligram",3) 3.0 >>> weight_conversion("milligram","metric-ton",3) 3e-09 >>> weight_conversion("milligram","long-ton",3) 2.9526219e-09 >>> weight_conversion("milligram","short-ton",1) 1.1023122e-09 >>> weight_conversion("milligram","pound",3) 6.6138732605999995e-06 >>> weight_conversion("milligram","ounce",2) 7.054798144599999e-05 >>> weight_conversion("milligram","carrat",1) 0.005 >>> weight_conversion("milligram","atomic-mass-unit",1) 6.022136652e+20 >>> weight_conversion("metric-ton","kilogram",2) 2000 >>> weight_conversion("metric-ton","gram",2) 2000000 >>> weight_conversion("metric-ton","milligram",3) 3000000000 >>> weight_conversion("metric-ton","metric-ton",2) 2.0 >>> weight_conversion("metric-ton","long-ton",3) 2.9526219 >>> weight_conversion("metric-ton","short-ton",2) 2.2046244 >>> weight_conversion("metric-ton","pound",3) 6613.8732606 >>> weight_conversion("metric-ton","ounce",4) 141095.96289199998 >>> weight_conversion("metric-ton","carrat",4) 20000000 >>> weight_conversion("metric-ton","atomic-mass-unit",1) 6.022136652e+29 >>> weight_conversion("long-ton","kilogram",4) 4064.18432 >>> weight_conversion("long-ton","gram",4) 4064184.32 >>> weight_conversion("long-ton","milligram",3) 3048138240.0 >>> weight_conversion("long-ton","metric-ton",4) 4.06418432 >>> weight_conversion("long-ton","long-ton",3) 2.999999907217152 >>> weight_conversion("long-ton","short-ton",1) 1.119999989746176 >>> weight_conversion("long-ton","pound",3) 6720.000000049448 >>> weight_conversion("long-ton","ounce",1) 35840.000000060514 >>> weight_conversion("long-ton","carrat",4) 20320921.599999998 >>> weight_conversion("long-ton","atomic-mass-unit",4) 2.4475073353955697e+30 >>> weight_conversion("short-ton","kilogram",3) 2721.5519999999997 >>> weight_conversion("short-ton","gram",3) 2721552.0 >>> weight_conversion("short-ton","milligram",1) 907184000.0 >>> weight_conversion("short-ton","metric-ton",4) 3.628736 >>> weight_conversion("short-ton","long-ton",3) 2.6785713457296 >>> weight_conversion("short-ton","short-ton",3) 2.9999999725344 >>> weight_conversion("short-ton","pound",2) 4000.0000000294335 >>> weight_conversion("short-ton","ounce",4) 128000.00000021611 >>> weight_conversion("short-ton","carrat",4) 18143680.0 >>> weight_conversion("short-ton","atomic-mass-unit",1) 5.463186016507968e+29 >>> weight_conversion("pound","kilogram",4) 1.814368 >>> weight_conversion("pound","gram",2) 907.184 >>> weight_conversion("pound","milligram",3) 1360776.0 >>> weight_conversion("pound","metric-ton",3) 0.001360776 >>> weight_conversion("pound","long-ton",2) 0.0008928571152432 >>> weight_conversion("pound","short-ton",1) 0.0004999999954224 >>> weight_conversion("pound","pound",3) 3.0000000000220752 >>> weight_conversion("pound","ounce",1) 16.000000000027015 >>> weight_conversion("pound","carrat",1) 2267.96 >>> weight_conversion("pound","atomic-mass-unit",4) 1.0926372033015936e+27 >>> weight_conversion("ounce","kilogram",3) 0.0850485 >>> weight_conversion("ounce","gram",3) 85.0485 >>> weight_conversion("ounce","milligram",4) 113398.0 >>> weight_conversion("ounce","metric-ton",4) 0.000113398 >>> weight_conversion("ounce","long-ton",4) 0.0001116071394054 >>> weight_conversion("ounce","short-ton",4) 0.0001249999988556 >>> weight_conversion("ounce","pound",1) 0.0625000000004599 >>> weight_conversion("ounce","ounce",2) 2.000000000003377 >>> weight_conversion("ounce","carrat",1) 141.7475 >>> weight_conversion("ounce","atomic-mass-unit",1) 1.70724563015874e+25 >>> weight_conversion("carrat","kilogram",1) 0.0002 >>> weight_conversion("carrat","gram",4) 0.8 >>> weight_conversion("carrat","milligram",2) 400.0 >>> weight_conversion("carrat","metric-ton",2) 4.0000000000000003e-07 >>> weight_conversion("carrat","long-ton",3) 5.9052438e-07 >>> weight_conversion("carrat","short-ton",4) 8.818497600000002e-07 >>> weight_conversion("carrat","pound",1) 0.00044092488404000004 >>> weight_conversion("carrat","ounce",2) 0.0141095962892 >>> weight_conversion("carrat","carrat",4) 4.0 >>> weight_conversion("carrat","atomic-mass-unit",4) 4.8177093216e+23 >>> weight_conversion("atomic-mass-unit","kilogram",4) 6.642160796e-27 >>> weight_conversion("atomic-mass-unit","gram",2) 3.321080398e-24 >>> weight_conversion("atomic-mass-unit","milligram",2) 3.3210803980000002e-21 >>> weight_conversion("atomic-mass-unit","metric-ton",3) 4.9816205970000004e-30 >>> weight_conversion("atomic-mass-unit","long-ton",3) 4.9029473573977584e-30 >>> weight_conversion("atomic-mass-unit","short-ton",1) 1.830433719948128e-30 >>> weight_conversion("atomic-mass-unit","pound",3) 1.0982602420317504e-26 >>> weight_conversion("atomic-mass-unit","ounce",2) 1.1714775914938915e-25 >>> weight_conversion("atomic-mass-unit","carrat",2) 1.660540199e-23 >>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2) 1.999999998903455 """ if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: raise ValueError( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" ) return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] if __name__ == "__main__": import doctest doctest.testmod()
-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 Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return f"Node({self.data})" class LinkedList: def __init__(self): self.head = None def __iter__(self): node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("head") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self): """ String representation/visualization of a Linked Lists """ return "->".join([str(item) for item in self]) def __getitem__(self, index): """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node # Used to change the data of a particular node def __setitem__(self, index, data): """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for i in range(index): current = current.next current.data = data def insert_tail(self, data) -> None: self.insert_nth(len(self), data) def insert_head(self, data) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data print(self) def delete_head(self): return self.delete_nth(0) def delete_tail(self): # delete from tail return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0): if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("list index out of range") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: return self.head is None def reverse(self): prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() assert False # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() assert False # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return f"Node({self.data})" class LinkedList: def __init__(self): self.head = None def __iter__(self): node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("head") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self): """ String representation/visualization of a Linked Lists """ return "->".join([str(item) for item in self]) def __getitem__(self, index): """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node # Used to change the data of a particular node def __setitem__(self, index, data): """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for i in range(index): current = current.next current.data = data def insert_tail(self, data) -> None: self.insert_nth(len(self), data) def insert_head(self, data) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data print(self) def delete_head(self): return self.delete_nth(0) def delete_tail(self): # delete from tail return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0): if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("list index out of range") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: return self.head is None def reverse(self): prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() assert False # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() assert False # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
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}`.
"""Prime Check.""" import math import unittest def prime_check(number: int) -> bool: """Checks to see if a number is a prime. A number is prime if it has exactly two factors: 1 and itself. """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False odd_numbers = range(3, int(math.sqrt(number) + 1), 2) return not any(not number % i for i in odd_numbers) class Test(unittest.TestCase): def test_primes(self): self.assertTrue(prime_check(2)) self.assertTrue(prime_check(3)) self.assertTrue(prime_check(5)) self.assertTrue(prime_check(7)) self.assertTrue(prime_check(11)) self.assertTrue(prime_check(13)) self.assertTrue(prime_check(17)) self.assertTrue(prime_check(19)) self.assertTrue(prime_check(23)) self.assertTrue(prime_check(29)) def test_not_primes(self): self.assertFalse( prime_check(-19), "Negative numbers are excluded by definition of prime numbers.", ) self.assertFalse( prime_check(0), "Zero doesn't have any positive factors, primes must have exactly two.", ) self.assertFalse( prime_check(1), "One only has 1 positive factor, primes must have exactly two.", ) self.assertFalse(prime_check(2 * 2)) self.assertFalse(prime_check(2 * 3)) self.assertFalse(prime_check(3 * 3)) self.assertFalse(prime_check(3 * 5)) self.assertFalse(prime_check(3 * 5 * 7)) if __name__ == "__main__": unittest.main()
"""Prime Check.""" import math import unittest def prime_check(number: int) -> bool: """Checks to see if a number is a prime. A number is prime if it has exactly two factors: 1 and itself. """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False odd_numbers = range(3, int(math.sqrt(number) + 1), 2) return not any(not number % i for i in odd_numbers) class Test(unittest.TestCase): def test_primes(self): self.assertTrue(prime_check(2)) self.assertTrue(prime_check(3)) self.assertTrue(prime_check(5)) self.assertTrue(prime_check(7)) self.assertTrue(prime_check(11)) self.assertTrue(prime_check(13)) self.assertTrue(prime_check(17)) self.assertTrue(prime_check(19)) self.assertTrue(prime_check(23)) self.assertTrue(prime_check(29)) def test_not_primes(self): self.assertFalse( prime_check(-19), "Negative numbers are excluded by definition of prime numbers.", ) self.assertFalse( prime_check(0), "Zero doesn't have any positive factors, primes must have exactly two.", ) self.assertFalse( prime_check(1), "One only has 1 positive factor, primes must have exactly two.", ) self.assertFalse(prime_check(2 * 2)) self.assertFalse(prime_check(2 * 3)) self.assertFalse(prime_check(3 * 3)) self.assertFalse(prime_check(3 * 5)) self.assertFalse(prime_check(3 * 5 * 7)) if __name__ == "__main__": unittest.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}`.
""" Project Euler Problem 80: https://projecteuler.net/problem=80 Author: Sandeep Gupta Problem statement: For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ import decimal def solution() -> int: """ To evaluate the sum, Used decimal python module to calculate the decimal places up to 100, the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error. >>> solution() 40886 """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number = str(sqrt_number)[2:101] answer += sum([int(x) for x in sqrt_number]) return answer if __name__ == "__main__": import doctest doctest.testmod()
""" Project Euler Problem 80: https://projecteuler.net/problem=80 Author: Sandeep Gupta Problem statement: For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ import decimal def solution() -> int: """ To evaluate the sum, Used decimal python module to calculate the decimal places up to 100, the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error. >>> solution() 40886 """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number = str(sqrt_number)[2:101] answer += sum([int(x) for x in sqrt_number]) return answer 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}`.
# The Algorithms - Python [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/TheAlgorithms/Python)&nbsp; [![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms)&nbsp; [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/TheAlgorithms/Python/build?label=CI&logo=github&style=flat-square)](https://github.com/TheAlgorithms/Python/actions)&nbsp; [![LGTM](https://img.shields.io/lgtm/alerts/github/TheAlgorithms/Python.svg?label=LGTM&logo=LGTM&style=flat-square)](https://lgtm.com/projects/g/TheAlgorithms/Python/alerts)&nbsp; [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md)&nbsp; [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?logo=paypal&style=flat-square)](https://www.paypal.me/TheAlgorithms/100)&nbsp; ![](https://img.shields.io/github/repo-size/TheAlgorithms/Python.svg?label=Repo%20size&style=flat-square)&nbsp; [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square)](https://github.com/pre-commit/pre-commit)&nbsp; [![code style: black](https://img.shields.io/static/v1?label=code%20style&message=black&color=black&style=flat-square)](https://github.com/psf/black)&nbsp; <!--[![Tested on Python 3.8](https://img.shields.io/badge/Tested%20-Python%203.8-blue.svg?logo=python&style=flat-square)](https://www.python.org/downloads) &nbsp;--> ### All algorithms implemented in Python (for education) These implementations are for learning purposes only. Therefore they may be less efficient than the implementations in the Python standard library. ## Contribution Guidelines Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ## Community Channel We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us. ## List of Algorithms See our [directory](DIRECTORY.md).
# The Algorithms - Python [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/TheAlgorithms/Python)&nbsp; [![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms)&nbsp; [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/TheAlgorithms/Python/build?label=CI&logo=github&style=flat-square)](https://github.com/TheAlgorithms/Python/actions)&nbsp; [![LGTM](https://img.shields.io/lgtm/alerts/github/TheAlgorithms/Python.svg?label=LGTM&logo=LGTM&style=flat-square)](https://lgtm.com/projects/g/TheAlgorithms/Python/alerts)&nbsp; [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md)&nbsp; [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?logo=paypal&style=flat-square)](https://www.paypal.me/TheAlgorithms/100)&nbsp; ![](https://img.shields.io/github/repo-size/TheAlgorithms/Python.svg?label=Repo%20size&style=flat-square)&nbsp; [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square)](https://github.com/pre-commit/pre-commit)&nbsp; [![code style: black](https://img.shields.io/static/v1?label=code%20style&message=black&color=black&style=flat-square)](https://github.com/psf/black)&nbsp; <!--[![Tested on Python 3.8](https://img.shields.io/badge/Tested%20-Python%203.8-blue.svg?logo=python&style=flat-square)](https://www.python.org/downloads) &nbsp;--> ### All algorithms implemented in Python (for education) These implementations are for learning purposes only. Therefore they may be less efficient than the implementations in the Python standard library. ## Contribution Guidelines Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ## Community Channel We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us. ## List of Algorithms See our [directory](DIRECTORY.md).
-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}`.
""" Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ def solution(n: int = 100) -> int: """Returns the number of distinct terms in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100. >>> solution(100) 9183 >>> solution(50) 2184 >>> solution(20) 324 >>> solution(5) 15 >>> solution(2) 1 >>> solution(1) 0 """ collectPowers = set() currentPow = 0 N = n + 1 # maximum limit for a in range(2, N): for b in range(2, N): currentPow = a ** b # calculates the current power collectPowers.add(currentPow) # adds the result to the set return len(collectPowers) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
""" Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ def solution(n: int = 100) -> int: """Returns the number of distinct terms in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100. >>> solution(100) 9183 >>> solution(50) 2184 >>> solution(20) 324 >>> solution(5) 15 >>> solution(2) 1 >>> solution(1) 0 """ collectPowers = set() currentPow = 0 N = n + 1 # maximum limit for a in range(2, N): for b in range(2, N): currentPow = a ** b # calculates the current power collectPowers.add(currentPow) # adds the result to the set return len(collectPowers) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
-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 Burke's algorithm (dithering) """ import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: """ Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https://en.wikipedia.org/wiki/Dither Note: * Best results are given with threshold= ~1/2 * max greyscale value. * This implementation get RGB image and converts it to greyscale in runtime. """ def __init__(self, input_img, threshold: int): self.min_threshold = 0 # max greyscale value for #FFFFFF self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_threshold < threshold < self.max_threshold: raise ValueError(f"Factor value should be from 0 to {self.max_threshold}") self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] # error table size (+4 columns and +1 row) greater than input image because of # lack of if statements self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255 @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: """ >>> Burkes.get_greyscale(3, 4, 5) 3.753 """ return 0.114 * blue + 0.587 * green + 0.2126 * red def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[x][y] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[x][y] - 255 """ Burkes error propagation (`*` is current pixel): * 8/32 4/32 2/32 4/32 8/32 4/32 2/32 """ self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error) if __name__ == "__main__": # create Burke's instances with original images in greyscale burkes_instances = [ Burkes(imread("image_data/lena.jpg", 1), threshold) for threshold in (1, 126, 130, 140) ] for burkes in burkes_instances: burkes.process() for burkes in burkes_instances: imshow( f"Original image with dithering threshold: {burkes.threshold}", burkes.output_img, ) waitKey(0) destroyAllWindows()
""" Implementation Burke's algorithm (dithering) """ import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: """ Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https://en.wikipedia.org/wiki/Dither Note: * Best results are given with threshold= ~1/2 * max greyscale value. * This implementation get RGB image and converts it to greyscale in runtime. """ def __init__(self, input_img, threshold: int): self.min_threshold = 0 # max greyscale value for #FFFFFF self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_threshold < threshold < self.max_threshold: raise ValueError(f"Factor value should be from 0 to {self.max_threshold}") self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] # error table size (+4 columns and +1 row) greater than input image because of # lack of if statements self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255 @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: """ >>> Burkes.get_greyscale(3, 4, 5) 3.753 """ return 0.114 * blue + 0.587 * green + 0.2126 * red def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[x][y] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[x][y] - 255 """ Burkes error propagation (`*` is current pixel): * 8/32 4/32 2/32 4/32 8/32 4/32 2/32 """ self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error) if __name__ == "__main__": # create Burke's instances with original images in greyscale burkes_instances = [ Burkes(imread("image_data/lena.jpg", 1), threshold) for threshold in (1, 126, 130, 140) ] for burkes in burkes_instances: burkes.process() for burkes in burkes_instances: imshow( f"Original image with dithering threshold: {burkes.threshold}", burkes.output_img, ) waitKey(0) 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}`.
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,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}`.
Unnamed repository; edit this file 'description' to name the repository.
Unnamed repository; edit this file 'description' to name the repository.
-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}`.
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def translate_message(key, message, mode): """ >>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt") 'Pcssi Bidsm' """ chars_a = LETTERS if mode == "decrypt" else key chars_b = key if mode == "decrypt" else LETTERS translated = "" # loop through each symbol in the message for symbol in message: if symbol.upper() in chars_a: # encrypt/decrypt the symbol sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: # symbol is not in LETTERS, just add it translated += symbol return translated def encrypt_message(key: str, message: str) -> str: """ >>> encrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World") 'Pcssi Bidsm' """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: """ >>> decrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World") 'Itssg Vgksr' """ return translate_message(key, message, "decrypt") def main(): message = "Hello World" key = "QWERTYUIOPASDFGHJKLZXCVBNM" mode = "decrypt" # set to 'encrypt' or 'decrypt' if mode == "encrypt": translated = encrypt_message(key, message) elif mode == "decrypt": translated = decrypt_message(key, message) print(f"Using the key {key}, the {mode}ed message is: {translated}") if __name__ == "__main__": import doctest doctest.testmod() main()
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def translate_message(key, message, mode): """ >>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt") 'Pcssi Bidsm' """ chars_a = LETTERS if mode == "decrypt" else key chars_b = key if mode == "decrypt" else LETTERS translated = "" # loop through each symbol in the message for symbol in message: if symbol.upper() in chars_a: # encrypt/decrypt the symbol sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: # symbol is not in LETTERS, just add it translated += symbol return translated def encrypt_message(key: str, message: str) -> str: """ >>> encrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World") 'Pcssi Bidsm' """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: """ >>> decrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World") 'Itssg Vgksr' """ return translate_message(key, message, "decrypt") def main(): message = "Hello World" key = "QWERTYUIOPASDFGHJKLZXCVBNM" mode = "decrypt" # set to 'encrypt' or 'decrypt' if mode == "encrypt": translated = encrypt_message(key, message) elif mode == "decrypt": translated = decrypt_message(key, message) print(f"Using the key {key}, the {mode}ed message is: {translated}") if __name__ == "__main__": import doctest doctest.testmod() 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 Queue using a linked list like structure """ from typing import Any class Node: def __init__(self, data: Any) -> None: self.data = data self.next = None def __str__(self) -> str: return f"{self.data}" class LinkedQueue: """ >>> queue = LinkedQueue() >>> queue.is_empty() True >>> queue.put(5) >>> queue.put(9) >>> queue.put('python') >>> queue.is_empty(); False >>> queue.get() 5 >>> queue.put('algorithms') >>> queue.get() 9 >>> queue.get() 'python' >>> queue.get() 'algorithms' >>> queue.is_empty() True >>> queue.get() Traceback (most recent call last): ... IndexError: dequeue from empty queue """ def __init__(self) -> None: self.front = self.rear = None def __iter__(self): node = self.front while node: yield node.data node = node.next def __len__(self) -> int: """ >>> queue = LinkedQueue() >>> for i in range(1, 6): ... queue.put(i) >>> len(queue) 5 >>> for i in range(1, 6): ... assert len(queue) == 6 - i ... _ = queue.get() >>> len(queue) 0 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> queue = LinkedQueue() >>> for i in range(1, 4): ... queue.put(i) >>> queue.put("Python") >>> queue.put(3.14) >>> queue.put(True) >>> str(queue) '1 <- 2 <- 3 <- Python <- 3.14 <- True' """ return " <- ".join(str(item) for item in self) def is_empty(self) -> bool: """ >>> queue = LinkedQueue() >>> queue.is_empty() True >>> for i in range(1, 6): ... queue.put(i) >>> queue.is_empty() False """ return len(self) == 0 def put(self, item) -> None: """ >>> queue = LinkedQueue() >>> queue.get() Traceback (most recent call last): ... IndexError: dequeue from empty queue >>> for i in range(1, 6): ... queue.put(i) >>> str(queue) '1 <- 2 <- 3 <- 4 <- 5' """ node = Node(item) if self.is_empty(): self.front = self.rear = node else: assert isinstance(self.rear, Node) self.rear.next = node self.rear = node def get(self) -> Any: """ >>> queue = LinkedQueue() >>> queue.get() Traceback (most recent call last): ... IndexError: dequeue from empty queue >>> queue = LinkedQueue() >>> for i in range(1, 6): ... queue.put(i) >>> for i in range(1, 6): ... assert queue.get() == i >>> len(queue) 0 """ if self.is_empty(): raise IndexError("dequeue from empty queue") assert isinstance(self.front, Node) node = self.front self.front = self.front.next if self.front is None: self.rear = None return node.data def clear(self) -> None: """ >>> queue = LinkedQueue() >>> for i in range(1, 6): ... queue.put(i) >>> queue.clear() >>> len(queue) 0 >>> str(queue) '' """ self.front = self.rear = None if __name__ == "__main__": from doctest import testmod testmod()
""" A Queue using a linked list like structure """ from typing import Any class Node: def __init__(self, data: Any) -> None: self.data = data self.next = None def __str__(self) -> str: return f"{self.data}" class LinkedQueue: """ >>> queue = LinkedQueue() >>> queue.is_empty() True >>> queue.put(5) >>> queue.put(9) >>> queue.put('python') >>> queue.is_empty(); False >>> queue.get() 5 >>> queue.put('algorithms') >>> queue.get() 9 >>> queue.get() 'python' >>> queue.get() 'algorithms' >>> queue.is_empty() True >>> queue.get() Traceback (most recent call last): ... IndexError: dequeue from empty queue """ def __init__(self) -> None: self.front = self.rear = None def __iter__(self): node = self.front while node: yield node.data node = node.next def __len__(self) -> int: """ >>> queue = LinkedQueue() >>> for i in range(1, 6): ... queue.put(i) >>> len(queue) 5 >>> for i in range(1, 6): ... assert len(queue) == 6 - i ... _ = queue.get() >>> len(queue) 0 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> queue = LinkedQueue() >>> for i in range(1, 4): ... queue.put(i) >>> queue.put("Python") >>> queue.put(3.14) >>> queue.put(True) >>> str(queue) '1 <- 2 <- 3 <- Python <- 3.14 <- True' """ return " <- ".join(str(item) for item in self) def is_empty(self) -> bool: """ >>> queue = LinkedQueue() >>> queue.is_empty() True >>> for i in range(1, 6): ... queue.put(i) >>> queue.is_empty() False """ return len(self) == 0 def put(self, item) -> None: """ >>> queue = LinkedQueue() >>> queue.get() Traceback (most recent call last): ... IndexError: dequeue from empty queue >>> for i in range(1, 6): ... queue.put(i) >>> str(queue) '1 <- 2 <- 3 <- 4 <- 5' """ node = Node(item) if self.is_empty(): self.front = self.rear = node else: assert isinstance(self.rear, Node) self.rear.next = node self.rear = node def get(self) -> Any: """ >>> queue = LinkedQueue() >>> queue.get() Traceback (most recent call last): ... IndexError: dequeue from empty queue >>> queue = LinkedQueue() >>> for i in range(1, 6): ... queue.put(i) >>> for i in range(1, 6): ... assert queue.get() == i >>> len(queue) 0 """ if self.is_empty(): raise IndexError("dequeue from empty queue") assert isinstance(self.front, Node) node = self.front self.front = self.front.next if self.front is None: self.rear = None return node.data def clear(self) -> None: """ >>> queue = LinkedQueue() >>> for i in range(1, 6): ... queue.put(i) >>> queue.clear() >>> len(queue) 0 >>> str(queue) '' """ self.front = self.rear = None if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,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 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible - https://en.wikipedia.org/wiki/Euclidean_algorithm - https://en.wikipedia.org/wiki/Least_common_multiple """ def gcd(x: int, y: int) -> int: """ Euclidean GCD algorithm (Greatest Common Divisor) >>> gcd(0, 0) 0 >>> gcd(23, 42) 1 >>> gcd(15, 33) 3 >>> gcd(12345, 67890) 15 """ return x if y == 0 else gcd(y, x % y) def lcm(x: int, y: int) -> int: """ Least Common Multiple. Using the property that lcm(a, b) * gcd(a, b) = a*b >>> lcm(3, 15) 15 >>> lcm(1, 27) 27 >>> lcm(13, 27) 351 >>> lcm(64, 48) 192 """ return (x * y) // gcd(x, y) def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 """ g = 1 for i in range(1, n + 1): g = lcm(g, i) return g if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible - https://en.wikipedia.org/wiki/Euclidean_algorithm - https://en.wikipedia.org/wiki/Least_common_multiple """ def gcd(x: int, y: int) -> int: """ Euclidean GCD algorithm (Greatest Common Divisor) >>> gcd(0, 0) 0 >>> gcd(23, 42) 1 >>> gcd(15, 33) 3 >>> gcd(12345, 67890) 15 """ return x if y == 0 else gcd(y, x % y) def lcm(x: int, y: int) -> int: """ Least Common Multiple. Using the property that lcm(a, b) * gcd(a, b) = a*b >>> lcm(3, 15) 15 >>> lcm(1, 27) 27 >>> lcm(13, 27) 351 >>> lcm(64, 48) 192 """ return (x * y) // gcd(x, y) def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 """ g = 1 for i in range(1, n + 1): g = lcm(g, i) return g 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}`.
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(lambda f: os.remove(f), self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(lambda f: os.remove(f), self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,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}`.
""" Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue using Python lists. """ class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: """ Tasks can be added to a Priority Queue at any time and in any order but when Tasks are removed then the Task with the highest priority is removed in FIFO order. In code we will use three levels of priority with priority zero Tasks being the most urgent (high priority) and priority 2 tasks being the least urgent. Examples >>> fpq = FixedPriorityQueue() >>> fpq.enqueue(0, 10) >>> fpq.enqueue(1, 70) >>> fpq.enqueue(0, 100) >>> fpq.enqueue(2, 1) >>> fpq.enqueue(2, 5) >>> fpq.enqueue(1, 7) >>> fpq.enqueue(2, 4) >>> fpq.enqueue(1, 64) >>> fpq.enqueue(0, 128) >>> print(fpq) Priority 0: [10, 100, 128] Priority 1: [70, 7, 64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 10 >>> fpq.dequeue() 100 >>> fpq.dequeue() 128 >>> fpq.dequeue() 70 >>> fpq.dequeue() 7 >>> print(fpq) Priority 0: [] Priority 1: [64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 64 >>> fpq.dequeue() 1 >>> fpq.dequeue() 5 >>> fpq.dequeue() 4 >>> fpq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: All queues are empty >>> print(fpq) Priority 0: [] Priority 1: [] Priority 2: [] """ def __init__(self): self.queues = [ [], [], [], ] def enqueue(self, priority: int, data: int) -> None: """ Add an element to a queue based on its priority. If the priority is invalid ValueError is raised. If the queue is full an OverFlowError is raised. """ try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty") def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues)) class ElementPriorityQueue: """ Element Priority Queue is the same as Fixed Priority Queue except that the value of the element itself is the priority. The rules for priorities are the same the as Fixed Priority Queue. >>> epq = ElementPriorityQueue() >>> epq.enqueue(10) >>> epq.enqueue(70) >>> epq.enqueue(4) >>> epq.enqueue(1) >>> epq.enqueue(5) >>> epq.enqueue(7) >>> epq.enqueue(4) >>> epq.enqueue(64) >>> epq.enqueue(128) >>> print(epq) [10, 70, 4, 1, 5, 7, 4, 64, 128] >>> epq.dequeue() 1 >>> epq.dequeue() 4 >>> epq.dequeue() 4 >>> epq.dequeue() 5 >>> epq.dequeue() 7 >>> epq.dequeue() 10 >>> print(epq) [70, 64, 128] >>> epq.dequeue() 64 >>> epq.dequeue() 70 >>> epq.dequeue() 128 >>> epq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: The queue is empty >>> print(epq) [] """ def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: """ This function enters the element into the queue If the queue is full an Exception is raised saying Over Flow! """ if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data def __str__(self) -> str: """ Prints all the elements within the Element Priority Queue """ return str(self.queue) def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
""" Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue using Python lists. """ class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: """ Tasks can be added to a Priority Queue at any time and in any order but when Tasks are removed then the Task with the highest priority is removed in FIFO order. In code we will use three levels of priority with priority zero Tasks being the most urgent (high priority) and priority 2 tasks being the least urgent. Examples >>> fpq = FixedPriorityQueue() >>> fpq.enqueue(0, 10) >>> fpq.enqueue(1, 70) >>> fpq.enqueue(0, 100) >>> fpq.enqueue(2, 1) >>> fpq.enqueue(2, 5) >>> fpq.enqueue(1, 7) >>> fpq.enqueue(2, 4) >>> fpq.enqueue(1, 64) >>> fpq.enqueue(0, 128) >>> print(fpq) Priority 0: [10, 100, 128] Priority 1: [70, 7, 64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 10 >>> fpq.dequeue() 100 >>> fpq.dequeue() 128 >>> fpq.dequeue() 70 >>> fpq.dequeue() 7 >>> print(fpq) Priority 0: [] Priority 1: [64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 64 >>> fpq.dequeue() 1 >>> fpq.dequeue() 5 >>> fpq.dequeue() 4 >>> fpq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: All queues are empty >>> print(fpq) Priority 0: [] Priority 1: [] Priority 2: [] """ def __init__(self): self.queues = [ [], [], [], ] def enqueue(self, priority: int, data: int) -> None: """ Add an element to a queue based on its priority. If the priority is invalid ValueError is raised. If the queue is full an OverFlowError is raised. """ try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty") def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues)) class ElementPriorityQueue: """ Element Priority Queue is the same as Fixed Priority Queue except that the value of the element itself is the priority. The rules for priorities are the same the as Fixed Priority Queue. >>> epq = ElementPriorityQueue() >>> epq.enqueue(10) >>> epq.enqueue(70) >>> epq.enqueue(4) >>> epq.enqueue(1) >>> epq.enqueue(5) >>> epq.enqueue(7) >>> epq.enqueue(4) >>> epq.enqueue(64) >>> epq.enqueue(128) >>> print(epq) [10, 70, 4, 1, 5, 7, 4, 64, 128] >>> epq.dequeue() 1 >>> epq.dequeue() 4 >>> epq.dequeue() 4 >>> epq.dequeue() 5 >>> epq.dequeue() 7 >>> epq.dequeue() 10 >>> print(epq) [70, 64, 128] >>> epq.dequeue() 64 >>> epq.dequeue() 70 >>> epq.dequeue() 128 >>> epq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: The queue is empty >>> print(epq) [] """ def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: """ This function enters the element into the queue If the queue is full an Exception is raised saying Over Flow! """ if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data def __str__(self) -> str: """ Prints all the elements within the Element Priority Queue """ return str(self.queue) def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
-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}`.
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10 ** m2) b1, b2 = divmod(b, 10 ** m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10 ** m2) b1, b2 = divmod(b, 10 ** m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) 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}`.
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitterConverter(sizePar, data): """ :param sizePar: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitterConverter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if sizePar + len(data) <= 2 ** sizePar - (len(data) - 1): print("ERROR - size of parity don't match with size of data") exit(0) dataOut = [] parity = [] binPos = [bin(x)[2:] for x in range(1, sizePar + len(data) + 1)] # sorted information data for the size of the output data dataOrd = [] # data position template + parity dataOutGab = [] # parity bit counter qtdBP = 0 # counter position of data bits contData = 0 for x in range(1, sizePar + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtdBP < sizePar: if (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: dataOutGab.append("D") else: dataOutGab.append("D") # Sorts the data to the new output size if dataOutGab[-1] == "D": dataOrd.append(data[contData]) contData += 1 else: dataOrd.append(None) # Calculates parity qtdBP = 0 # parity bit counter for bp in range(1, sizePar + 1): # Bit counter one for a given parity contBO = 0 # counter to control the loop reading contLoop = 0 for x in dataOrd: if x is not None: try: aux = (binPos[contLoop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1": if x == "1": contBO += 1 contLoop += 1 parity.append(contBO % 2) qtdBP += 1 # Mount the message ContBP = 0 # parity bit counter for x in range(0, sizePar + len(data)): if dataOrd[x] is None: dataOut.append(str(parity[ContBP])) ContBP += 1 else: dataOut.append(dataOrd[x]) return dataOut def receptorConverter(sizePar, data): """ >>> receptorConverter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity dataOutGab = [] # Parity bit counter qtdBP = 0 # Counter p data bit reading contData = 0 # list of parity received parityReceived = [] dataOutput = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: dataOutGab.append("D") # Sorts the data to the new output size if dataOutGab[-1] == "D": dataOutput.append(data[contData]) else: parityReceived.append(data[contData]) contData += 1 # -----------calculates the parity with the data dataOut = [] parity = [] binPos = [bin(x)[2:] for x in range(1, sizePar + len(dataOutput) + 1)] # sorted information data for the size of the output data dataOrd = [] # Data position feedback + parity dataOutGab = [] # Parity bit counter qtdBP = 0 # Counter p data bit reading contData = 0 for x in range(1, sizePar + len(dataOutput) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: dataOutGab.append("D") # Sorts the data to the new output size if dataOutGab[-1] == "D": dataOrd.append(dataOutput[contData]) contData += 1 else: dataOrd.append(None) # Calculates parity qtdBP = 0 # parity bit counter for bp in range(1, sizePar + 1): # Bit counter one for a certain parity contBO = 0 # Counter to control loop reading contLoop = 0 for x in dataOrd: if x is not None: try: aux = (binPos[contLoop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": contBO += 1 contLoop += 1 parity.append(str(contBO % 2)) qtdBP += 1 # Mount the message ContBP = 0 # Parity bit counter for x in range(0, sizePar + len(dataOutput)): if dataOrd[x] is None: dataOut.append(str(parity[ContBP])) ContBP += 1 else: dataOut.append(dataOrd[x]) ack = parityReceived == parity return dataOutput, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitterConverter(sizePar, data): """ :param sizePar: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitterConverter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if sizePar + len(data) <= 2 ** sizePar - (len(data) - 1): print("ERROR - size of parity don't match with size of data") exit(0) dataOut = [] parity = [] binPos = [bin(x)[2:] for x in range(1, sizePar + len(data) + 1)] # sorted information data for the size of the output data dataOrd = [] # data position template + parity dataOutGab = [] # parity bit counter qtdBP = 0 # counter position of data bits contData = 0 for x in range(1, sizePar + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtdBP < sizePar: if (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: dataOutGab.append("D") else: dataOutGab.append("D") # Sorts the data to the new output size if dataOutGab[-1] == "D": dataOrd.append(data[contData]) contData += 1 else: dataOrd.append(None) # Calculates parity qtdBP = 0 # parity bit counter for bp in range(1, sizePar + 1): # Bit counter one for a given parity contBO = 0 # counter to control the loop reading contLoop = 0 for x in dataOrd: if x is not None: try: aux = (binPos[contLoop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1": if x == "1": contBO += 1 contLoop += 1 parity.append(contBO % 2) qtdBP += 1 # Mount the message ContBP = 0 # parity bit counter for x in range(0, sizePar + len(data)): if dataOrd[x] is None: dataOut.append(str(parity[ContBP])) ContBP += 1 else: dataOut.append(dataOrd[x]) return dataOut def receptorConverter(sizePar, data): """ >>> receptorConverter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity dataOutGab = [] # Parity bit counter qtdBP = 0 # Counter p data bit reading contData = 0 # list of parity received parityReceived = [] dataOutput = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: dataOutGab.append("D") # Sorts the data to the new output size if dataOutGab[-1] == "D": dataOutput.append(data[contData]) else: parityReceived.append(data[contData]) contData += 1 # -----------calculates the parity with the data dataOut = [] parity = [] binPos = [bin(x)[2:] for x in range(1, sizePar + len(dataOutput) + 1)] # sorted information data for the size of the output data dataOrd = [] # Data position feedback + parity dataOutGab = [] # Parity bit counter qtdBP = 0 # Counter p data bit reading contData = 0 for x in range(1, sizePar + len(dataOutput) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer(): dataOutGab.append("P") qtdBP = qtdBP + 1 else: dataOutGab.append("D") # Sorts the data to the new output size if dataOutGab[-1] == "D": dataOrd.append(dataOutput[contData]) contData += 1 else: dataOrd.append(None) # Calculates parity qtdBP = 0 # parity bit counter for bp in range(1, sizePar + 1): # Bit counter one for a certain parity contBO = 0 # Counter to control loop reading contLoop = 0 for x in dataOrd: if x is not None: try: aux = (binPos[contLoop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": contBO += 1 contLoop += 1 parity.append(str(contBO % 2)) qtdBP += 1 # Mount the message ContBP = 0 # Parity bit counter for x in range(0, sizePar + len(dataOutput)): if dataOrd[x] is None: dataOut.append(str(parity[ContBP])) ContBP += 1 else: dataOut.append(dataOrd[x]) ack = parityReceived == parity return dataOutput, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
-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}`.
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head = None self.size = 0 def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1 def remove(self) -> Any: if self.is_empty(): return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if not self.is_empty: return "" else: iterate = self.head item_str = "" item_list = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head = None self.size = 0 def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1 def remove(self) -> Any: if self.is_empty(): return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if not self.is_empty: return "" else: iterate = self.head item_str = "" item_list = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
-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 Armstrong number is equal to the sum of the cubes of its digits. For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An Armstrong number is often called Narcissistic number. """ def armstrong_number(n: int) -> bool: """ Return True if n is an Armstrong number or False if it is not. >>> armstrong_number(153) True >>> armstrong_number(200) False >>> armstrong_number(1634) True >>> armstrong_number(0) False >>> armstrong_number(-1) False >>> armstrong_number(1.2) False """ if not isinstance(n, int) or n < 1: return False # Initialization of sum and number of digits. sum = 0 number_of_digits = 0 temp = n # Calculation of digits of the number while temp > 0: number_of_digits += 1 temp //= 10 # Dividing number into separate digits and find Armstrong number temp = n while temp > 0: rem = temp % 10 sum += rem ** number_of_digits temp //= 10 return n == sum def narcissistic_number(n: int) -> bool: """Return True if n is a narcissistic number or False if it is not""" expo = len(str(n)) # power, all number will be raised to # each digit will be multiplied expo times temp = [(int(i) ** expo) for i in str(n)] # check if sum of cube of each digit is equal to number return n == sum(temp) def main(): """ Request that user input an integer and tell them if it is Armstrong number. """ num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") if __name__ == "__main__": import doctest doctest.testmod() main()
""" An Armstrong number is equal to the sum of the cubes of its digits. For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An Armstrong number is often called Narcissistic number. """ def armstrong_number(n: int) -> bool: """ Return True if n is an Armstrong number or False if it is not. >>> armstrong_number(153) True >>> armstrong_number(200) False >>> armstrong_number(1634) True >>> armstrong_number(0) False >>> armstrong_number(-1) False >>> armstrong_number(1.2) False """ if not isinstance(n, int) or n < 1: return False # Initialization of sum and number of digits. sum = 0 number_of_digits = 0 temp = n # Calculation of digits of the number while temp > 0: number_of_digits += 1 temp //= 10 # Dividing number into separate digits and find Armstrong number temp = n while temp > 0: rem = temp % 10 sum += rem ** number_of_digits temp //= 10 return n == sum def narcissistic_number(n: int) -> bool: """Return True if n is a narcissistic number or False if it is not""" expo = len(str(n)) # power, all number will be raised to # each digit will be multiplied expo times temp = [(int(i) ** expo) for i in str(n)] # check if sum of cube of each digit is equal to number return n == sum(temp) def main(): """ Request that user input an integer and tell them if it is Armstrong number. """ num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") if __name__ == "__main__": import doctest doctest.testmod() 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}`.
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https://en.wikipedia.org/wiki/Perfect_number """ def perfect(number: int) -> bool: """ >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. """ return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") number = int(input("Enter number: ").strip()) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https://en.wikipedia.org/wiki/Perfect_number """ def perfect(number: int) -> bool: """ >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. """ return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") number = int(input("Enter number: ").strip()) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
-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 # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from pprint import pformat class GraphAdjacencyList: """ Adjacency List type Graph Data Structure that accounts for directed and undirected Graphs. Initialize graph object indicating whether it's directed or undirected. Directed graph example: >>> d_graph = GraphAdjacencyList() >>> d_graph {} >>> d_graph.add_edge(0, 1) {0: [1], 1: []} >>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []} >>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(d_graph) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(repr(d_graph)) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} Undirected graph example: >>> u_graph = GraphAdjacencyList(directed=False) >>> u_graph.add_edge(0, 1) {0: [1], 1: [0]} >>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]} >>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]} >>> u_graph.add_edge(4, 5) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(u_graph) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(repr(u_graph)) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} """ def __init__(self, directed: bool = True): """ Parameters: directed: (bool) Indicates if graph is directed or undirected. Default is True. """ self.adj_list = {} # dictionary of lists self.directed = directed def add_edge(self, source_vertex: int, destination_vertex: int) -> object: """ Connects vertices together. Creates and Edge from source vertex to destination vertex. Vertices will be created if not found in graph """ if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex].append(source_vertex) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(source_vertex) self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [] return self def __repr__(self) -> str: return pformat(self.adj_list) if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from pprint import pformat class GraphAdjacencyList: """ Adjacency List type Graph Data Structure that accounts for directed and undirected Graphs. Initialize graph object indicating whether it's directed or undirected. Directed graph example: >>> d_graph = GraphAdjacencyList() >>> d_graph {} >>> d_graph.add_edge(0, 1) {0: [1], 1: []} >>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []} >>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(d_graph) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(repr(d_graph)) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} Undirected graph example: >>> u_graph = GraphAdjacencyList(directed=False) >>> u_graph.add_edge(0, 1) {0: [1], 1: [0]} >>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]} >>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]} >>> u_graph.add_edge(4, 5) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(u_graph) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(repr(u_graph)) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} """ def __init__(self, directed: bool = True): """ Parameters: directed: (bool) Indicates if graph is directed or undirected. Default is True. """ self.adj_list = {} # dictionary of lists self.directed = directed def add_edge(self, source_vertex: int, destination_vertex: int) -> object: """ Connects vertices together. Creates and Edge from source vertex to destination vertex. Vertices will be created if not found in graph """ if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex].append(source_vertex) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(source_vertex) self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [] return self def __repr__(self) -> str: return pformat(self.adj_list) 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}`.
"""Get the site emails from URL.""" __author__ = "Muhammad Umer Farooq" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Muhammad Umer Farooq" __email__ = "contact@muhammadumerfarooq.me" __status__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class Parser(HTMLParser): def __init__(self, domain: str): HTMLParser.__init__(self) self.data = [] self.domain = domain def handle_starttag(self, tag: str, attrs: str) -> None: """ This function parse html to take takes url from tags """ # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in data. if value not in self.data: url = parse.urljoin(self.domain, value) self.data.append(url) # Get main domain name (example.com) def get_domain_name(url: str) -> str: """ This function get the main domain name >>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'c.d' >>> get_domain_name("Not a URL!") '' """ return ".".join(get_sub_domain_name(url).split(".")[-2:]) # Get sub domain name (sub.example.com) def get_sub_domain_name(url: str) -> str: """ >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'a.b.c.d' >>> get_sub_domain_name("Not a URL!") '' """ return parse.urlparse(url).netloc def emails_from_url(url: str = "https://github.com") -> list: """ This function takes url and return all valid urls """ # Get the base domain from the url domain = get_domain_name(url) # Initialize the parser parser = Parser(domain) try: # Open URL r = requests.get(url) # pass the raw HTML to the parser to get links parser.feed(r.text) # Get links and loop through valid_emails = set() for link in parser.data: # open URL. # read = requests.get(link) try: read = requests.get(link) # Get the valid email. emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text) # If not in list then append it. for email in emails: valid_emails.add(email) except ValueError: pass except ValueError: exit(-1) # Finally return a sorted list of email addresses with no duplicates. return sorted(valid_emails) if __name__ == "__main__": emails = emails_from_url("https://github.com") print(f"{len(emails)} emails found:") print("\n".join(sorted(emails)))
"""Get the site emails from URL.""" __author__ = "Muhammad Umer Farooq" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Muhammad Umer Farooq" __email__ = "contact@muhammadumerfarooq.me" __status__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class Parser(HTMLParser): def __init__(self, domain: str): HTMLParser.__init__(self) self.data = [] self.domain = domain def handle_starttag(self, tag: str, attrs: str) -> None: """ This function parse html to take takes url from tags """ # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in data. if value not in self.data: url = parse.urljoin(self.domain, value) self.data.append(url) # Get main domain name (example.com) def get_domain_name(url: str) -> str: """ This function get the main domain name >>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'c.d' >>> get_domain_name("Not a URL!") '' """ return ".".join(get_sub_domain_name(url).split(".")[-2:]) # Get sub domain name (sub.example.com) def get_sub_domain_name(url: str) -> str: """ >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'a.b.c.d' >>> get_sub_domain_name("Not a URL!") '' """ return parse.urlparse(url).netloc def emails_from_url(url: str = "https://github.com") -> list: """ This function takes url and return all valid urls """ # Get the base domain from the url domain = get_domain_name(url) # Initialize the parser parser = Parser(domain) try: # Open URL r = requests.get(url) # pass the raw HTML to the parser to get links parser.feed(r.text) # Get links and loop through valid_emails = set() for link in parser.data: # open URL. # read = requests.get(link) try: read = requests.get(link) # Get the valid email. emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text) # If not in list then append it. for email in emails: valid_emails.add(email) except ValueError: pass except ValueError: exit(-1) # Finally return a sorted list of email addresses with no duplicates. return sorted(valid_emails) if __name__ == "__main__": emails = emails_from_url("https://github.com") print(f"{len(emails)} emails found:") print("\n".join(sorted(emails)))
-1
TheAlgorithms/Python
4,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 from itertools import chain from random import randrange, shuffle import pytest from .sol1 import PokerHand SORTED_HANDS = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) TEST_COMPARE = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) TEST_FLUSH = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) TEST_STRAIGHT = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) TEST_FIVE_HIGH_STRAIGHT = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) TEST_KIND = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) TEST_TYPES = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def generate_random_hand(): play, oppo = randrange(len(SORTED_HANDS)), randrange(len(SORTED_HANDS)) expected = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] hand, other = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def generate_random_hands(number_of_hands: int = 100): return (generate_random_hand() for _ in range(number_of_hands)) @pytest.mark.parametrize("hand, expected", TEST_FLUSH) def test_hand_is_flush(hand, expected): assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize("hand, expected", TEST_STRAIGHT) def test_hand_is_straight(hand, expected): assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values", TEST_FIVE_HIGH_STRAIGHT) def test_hand_is_five_high_straight(hand, expected, card_values): player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected", TEST_KIND) def test_hand_is_same_kind(hand, expected): assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize("hand, expected", TEST_TYPES) def test_hand_values(hand, expected): assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize("hand, other, expected", TEST_COMPARE) def test_compare_simple(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize("hand, other, expected", generate_random_hands()) def test_compare_random(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected def test_hand_sorted(): POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] list_copy = POKER_HANDS.copy() shuffle(list_copy) user_sorted = chain(sorted(list_copy)) for index, hand in enumerate(user_sorted): assert hand == POKER_HANDS[index] def test_custom_sort_five_high_straight(): # Test that five high straights are compared correctly. pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def test_multiple_calls_five_high_straight(): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. pokerhand = PokerHand("2C 4S AS 3D 5C") expected = True expected_card_values = [5, 4, 3, 2, 14] for _ in range(10): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def test_euler_project(): # Problem number 54 from Project Euler # Testing from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 assert answer == 376
import os from itertools import chain from random import randrange, shuffle import pytest from .sol1 import PokerHand SORTED_HANDS = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) TEST_COMPARE = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) TEST_FLUSH = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) TEST_STRAIGHT = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) TEST_FIVE_HIGH_STRAIGHT = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) TEST_KIND = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) TEST_TYPES = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def generate_random_hand(): play, oppo = randrange(len(SORTED_HANDS)), randrange(len(SORTED_HANDS)) expected = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] hand, other = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def generate_random_hands(number_of_hands: int = 100): return (generate_random_hand() for _ in range(number_of_hands)) @pytest.mark.parametrize("hand, expected", TEST_FLUSH) def test_hand_is_flush(hand, expected): assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize("hand, expected", TEST_STRAIGHT) def test_hand_is_straight(hand, expected): assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values", TEST_FIVE_HIGH_STRAIGHT) def test_hand_is_five_high_straight(hand, expected, card_values): player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected", TEST_KIND) def test_hand_is_same_kind(hand, expected): assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize("hand, expected", TEST_TYPES) def test_hand_values(hand, expected): assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize("hand, other, expected", TEST_COMPARE) def test_compare_simple(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize("hand, other, expected", generate_random_hands()) def test_compare_random(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected def test_hand_sorted(): POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] list_copy = POKER_HANDS.copy() shuffle(list_copy) user_sorted = chain(sorted(list_copy)) for index, hand in enumerate(user_sorted): assert hand == POKER_HANDS[index] def test_custom_sort_five_high_straight(): # Test that five high straights are compared correctly. pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def test_multiple_calls_five_high_straight(): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. pokerhand = PokerHand("2C 4S AS 3D 5C") expected = True expected_card_values = [5, 4, 3, 2, 14] for _ in range(10): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def test_euler_project(): # Problem number 54 from Project Euler # Testing from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 assert answer == 376
-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 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 """ xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) 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 """ xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) 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}`.
""" Convert International System of Units (SI) and Binary prefixes """ from enum import Enum from typing import Union class SI_Unit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class Binary_Unit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: Union[str, SI_Unit], unknown_prefix: Union[str, SI_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SI_Unit.giga, SI_Unit.mega) 1000 >>> convert_si_prefix(1, SI_Unit.mega, SI_Unit.giga) 0.001 >>> convert_si_prefix(1, SI_Unit.kilo, SI_Unit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix: SI_Unit = SI_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix: SI_Unit = SI_Unit[unknown_prefix.lower()] unknown_amount = known_amount * (10 ** (known_prefix.value - unknown_prefix.value)) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: Union[str, Binary_Unit], unknown_prefix: Union[str, Binary_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, Binary_Unit.giga, Binary_Unit.mega) 1024 >>> convert_binary_prefix(1, Binary_Unit.mega, Binary_Unit.giga) 0.0009765625 >>> convert_binary_prefix(1, Binary_Unit.kilo, Binary_Unit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix: Binary_Unit = Binary_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix: Binary_Unit = Binary_Unit[unknown_prefix.lower()] unknown_amount = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
""" Convert International System of Units (SI) and Binary prefixes """ from enum import Enum from typing import Union class SI_Unit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class Binary_Unit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: Union[str, SI_Unit], unknown_prefix: Union[str, SI_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SI_Unit.giga, SI_Unit.mega) 1000 >>> convert_si_prefix(1, SI_Unit.mega, SI_Unit.giga) 0.001 >>> convert_si_prefix(1, SI_Unit.kilo, SI_Unit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix: SI_Unit = SI_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix: SI_Unit = SI_Unit[unknown_prefix.lower()] unknown_amount = known_amount * (10 ** (known_prefix.value - unknown_prefix.value)) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: Union[str, Binary_Unit], unknown_prefix: Union[str, Binary_Unit], ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, Binary_Unit.giga, Binary_Unit.mega) 1024 >>> convert_binary_prefix(1, Binary_Unit.mega, Binary_Unit.giga) 0.0009765625 >>> convert_binary_prefix(1, Binary_Unit.kilo, Binary_Unit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix: Binary_Unit = Binary_Unit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix: Binary_Unit = Binary_Unit[unknown_prefix.lower()] unknown_amount = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
-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 median(nums): """ Find median of a list of numbers. >>> median([0]) 0 >>> median([4,1,3,2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums Returns: Median. """ sorted_list = sorted(nums) length = len(sorted_list) mid_index = length >> 1 return ( (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 if length % 2 == 0 else sorted_list[mid_index] ) def main(): import doctest doctest.testmod() if __name__ == "__main__": main()
def median(nums): """ Find median of a list of numbers. >>> median([0]) 0 >>> median([4,1,3,2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums Returns: Median. """ sorted_list = sorted(nums) length = len(sorted_list) mid_index = length >> 1 return ( (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 if length % 2 == 0 else sorted_list[mid_index] ) def main(): import doctest doctest.testmod() 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}`.
-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 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ """ The maximum base can be 9 because all n-digit numbers < 10^n. Now 9**23 has 22 digits so the maximum power can be 22. Using these conclusions, we will calculate the result. """ def solution(max_base: int = 10, max_power: int = 22) -> int: """ Returns the count of all n-digit numbers which are nth power >>> solution(10, 22) 49 >>> solution(0, 0) 0 >>> solution(1, 1) 0 >>> solution(-1, -1) 0 """ bases = range(1, max_base) powers = range(1, max_power) return sum( 1 for power in powers for base in bases if len(str(base ** power)) == power ) if __name__ == "__main__": print(f"{solution(10, 22) = }")
""" The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ """ The maximum base can be 9 because all n-digit numbers < 10^n. Now 9**23 has 22 digits so the maximum power can be 22. Using these conclusions, we will calculate the result. """ def solution(max_base: int = 10, max_power: int = 22) -> int: """ Returns the count of all n-digit numbers which are nth power >>> solution(10, 22) 49 >>> solution(0, 0) 0 >>> solution(1, 1) 0 >>> solution(-1, -1) 0 """ bases = range(1, max_base) powers = range(1, max_power) return sum( 1 for power in powers for base in bases if len(str(base ** power)) == power ) if __name__ == "__main__": print(f"{solution(10, 22) = }")
-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 math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
from math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,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}`.
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import numpy as np import requests def collect_dataset(): """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get( "https://raw.githubusercontent.com/yashLadha/" + "The_Math_of_Intelligence/master/Week1/ADRvs" + "Rating.csv" ) lines = response.text.splitlines() data = [] for item in lines: item = item.split(",") data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print("At Iteration %d - Error is %.5f " % (i + 1, error)) return theta def main(): """ Driver function """ data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): print("%.5f" % (theta[0, i])) if __name__ == "__main__": main()
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import numpy as np import requests def collect_dataset(): """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get( "https://raw.githubusercontent.com/yashLadha/" + "The_Math_of_Intelligence/master/Week1/ADRvs" + "Rating.csv" ) lines = response.text.splitlines() data = [] for item in lines: item = item.split(",") data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print("At Iteration %d - Error is %.5f " % (i + 1, error)) return theta def main(): """ Driver function """ data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): print("%.5f" % (theta[0, i])) 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}`.
""" Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter). Adler-32 is more reliable than Fletcher-16, and slightly less reliable than Fletcher-32.[2] source: https://en.wikipedia.org/wiki/Adler-32 """ def adler32(plain_text: str) -> str: """ Function implements adler-32 hash. Itterates and evaluates new value for each character >>> adler32('Algorithms') 363791387 >>> adler32('go adler em all') 708642122 """ MOD_ADLER = 65521 a = 1 b = 0 for plain_chr in plain_text: a = (a + ord(plain_chr)) % MOD_ADLER b = (b + a) % MOD_ADLER return (b << 16) | a
""" Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter). Adler-32 is more reliable than Fletcher-16, and slightly less reliable than Fletcher-32.[2] source: https://en.wikipedia.org/wiki/Adler-32 """ def adler32(plain_text: str) -> str: """ Function implements adler-32 hash. Itterates and evaluates new value for each character >>> adler32('Algorithms') 363791387 >>> adler32('go adler em all') 708642122 """ MOD_ADLER = 65521 a = 1 b = 0 for plain_chr in plain_text: a = (a + ord(plain_chr)) % MOD_ADLER b = (b + a) % MOD_ADLER return (b << 16) | a
-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}`.
9caf4784aada17dc75348f77cc8c356df503c0f3
9caf4784aada17dc75348f77cc8c356df503c0f3
-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}`.
-,-,-,427,668,495,377,678,-,177,-,-,870,-,869,624,300,609,131,-,251,-,-,-,856,221,514,-,591,762,182,56,-,884,412,273,636,-,-,774 -,-,262,-,-,508,472,799,-,956,578,363,940,143,-,162,122,910,-,729,802,941,922,573,531,539,667,607,-,920,-,-,315,649,937,-,185,102,636,289 -,262,-,-,926,-,958,158,647,47,621,264,81,-,402,813,649,386,252,391,264,637,349,-,-,-,108,-,727,225,578,699,-,898,294,-,575,168,432,833 427,-,-,-,366,-,-,635,-,32,962,468,893,854,718,427,448,916,258,-,760,909,529,311,404,-,-,588,680,875,-,615,-,409,758,221,-,-,76,257 668,-,926,366,-,-,-,250,268,-,503,944,-,677,-,727,793,457,981,191,-,-,-,351,969,925,987,328,282,589,-,873,477,-,-,19,450,-,-,- 495,508,-,-,-,-,-,765,711,819,305,302,926,-,-,582,-,861,-,683,293,-,-,66,-,27,-,-,290,-,786,-,554,817,33,-,54,506,386,381 377,472,958,-,-,-,-,-,-,120,42,-,134,219,457,639,538,374,-,-,-,966,-,-,-,-,-,449,120,797,358,232,550,-,305,997,662,744,686,239 678,799,158,635,250,765,-,-,-,35,-,106,385,652,160,-,890,812,605,953,-,-,-,79,-,712,613,312,452,-,978,900,-,901,-,-,225,533,770,722 -,-,647,-,268,711,-,-,-,283,-,172,-,663,236,36,403,286,986,-,-,810,761,574,53,793,-,-,777,330,936,883,286,-,174,-,-,-,828,711 177,956,47,32,-,819,120,35,283,-,50,-,565,36,767,684,344,489,565,-,-,103,810,463,733,665,494,644,863,25,385,-,342,470,-,-,-,730,582,468 -,578,621,962,503,305,42,-,-,50,-,155,519,-,-,256,990,801,154,53,474,650,402,-,-,-,966,-,-,406,989,772,932,7,-,823,391,-,-,933 -,363,264,468,944,302,-,106,172,-,155,-,-,-,380,438,-,41,266,-,-,104,867,609,-,270,861,-,-,165,-,675,250,686,995,366,191,-,433,- 870,940,81,893,-,926,134,385,-,565,519,-,-,313,851,-,-,-,248,220,-,826,359,829,-,234,198,145,409,68,359,-,814,218,186,-,-,929,203,- -,143,-,854,677,-,219,652,663,36,-,-,313,-,132,-,433,598,-,-,168,870,-,-,-,128,437,-,383,364,966,227,-,-,807,993,-,-,526,17 869,-,402,718,-,-,457,160,236,767,-,380,851,132,-,-,596,903,613,730,-,261,-,142,379,885,89,-,848,258,112,-,900,-,-,818,639,268,600,- 624,162,813,427,727,582,639,-,36,684,256,438,-,-,-,-,539,379,664,561,542,-,999,585,-,-,321,398,-,-,950,68,193,-,697,-,390,588,848,- 300,122,649,448,793,-,538,890,403,344,990,-,-,433,596,539,-,-,73,-,318,-,-,500,-,968,-,291,-,-,765,196,504,757,-,542,-,395,227,148 609,910,386,916,457,861,374,812,286,489,801,41,-,598,903,379,-,-,-,946,136,399,-,941,707,156,757,258,251,-,807,-,-,-,461,501,-,-,616,- 131,-,252,258,981,-,-,605,986,565,154,266,248,-,613,664,73,-,-,686,-,-,575,627,817,282,-,698,398,222,-,649,-,-,-,-,-,654,-,- -,729,391,-,191,683,-,953,-,-,53,-,220,-,730,561,-,946,686,-,-,389,729,553,304,703,455,857,260,-,991,182,351,477,867,-,-,889,217,853 251,802,264,760,-,293,-,-,-,-,474,-,-,168,-,542,318,136,-,-,-,-,392,-,-,-,267,407,27,651,80,927,-,974,977,-,-,457,117,- -,941,637,909,-,-,966,-,810,103,650,104,826,870,261,-,-,399,-,389,-,-,-,202,-,-,-,-,867,140,403,962,785,-,511,-,1,-,707,- -,922,349,529,-,-,-,-,761,810,402,867,359,-,-,999,-,-,575,729,392,-,-,388,939,-,959,-,83,463,361,-,-,512,931,-,224,690,369,- -,573,-,311,351,66,-,79,574,463,-,609,829,-,142,585,500,941,627,553,-,202,388,-,164,829,-,620,523,639,936,-,-,490,-,695,-,505,109,- 856,531,-,404,969,-,-,-,53,733,-,-,-,-,379,-,-,707,817,304,-,-,939,164,-,-,616,716,728,-,889,349,-,963,150,447,-,292,586,264 221,539,-,-,925,27,-,712,793,665,-,270,234,128,885,-,968,156,282,703,-,-,-,829,-,-,-,822,-,-,-,736,576,-,697,946,443,-,205,194 514,667,108,-,987,-,-,613,-,494,966,861,198,437,89,321,-,757,-,455,267,-,959,-,616,-,-,-,349,156,339,-,102,790,359,-,439,938,809,260 -,607,-,588,328,-,449,312,-,644,-,-,145,-,-,398,291,258,698,857,407,-,-,620,716,822,-,-,293,486,943,-,779,-,6,880,116,775,-,947 591,-,727,680,282,290,120,452,777,863,-,-,409,383,848,-,-,251,398,260,27,867,83,523,728,-,349,293,-,212,684,505,341,384,9,992,507,48,-,- 762,920,225,875,589,-,797,-,330,25,406,165,68,364,258,-,-,-,222,-,651,140,463,639,-,-,156,486,212,-,-,349,723,-,-,186,-,36,240,752 182,-,578,-,-,786,358,978,936,385,989,-,359,966,112,950,765,807,-,991,80,403,361,936,889,-,339,943,684,-,-,965,302,676,725,-,327,134,-,147 56,-,699,615,873,-,232,900,883,-,772,675,-,227,-,68,196,-,649,182,927,962,-,-,349,736,-,-,505,349,965,-,474,178,833,-,-,555,853,- -,315,-,-,477,554,550,-,286,342,932,250,814,-,900,193,504,-,-,351,-,785,-,-,-,576,102,779,341,723,302,474,-,689,-,-,-,451,-,- 884,649,898,409,-,817,-,901,-,470,7,686,218,-,-,-,757,-,-,477,974,-,512,490,963,-,790,-,384,-,676,178,689,-,245,596,445,-,-,343 412,937,294,758,-,33,305,-,174,-,-,995,186,807,-,697,-,461,-,867,977,511,931,-,150,697,359,6,9,-,725,833,-,245,-,949,-,270,-,112 273,-,-,221,19,-,997,-,-,-,823,366,-,993,818,-,542,501,-,-,-,-,-,695,447,946,-,880,992,186,-,-,-,596,949,-,91,-,768,273 636,185,575,-,450,54,662,225,-,-,391,191,-,-,639,390,-,-,-,-,-,1,224,-,-,443,439,116,507,-,327,-,-,445,-,91,-,248,-,344 -,102,168,-,-,506,744,533,-,730,-,-,929,-,268,588,395,-,654,889,457,-,690,505,292,-,938,775,48,36,134,555,451,-,270,-,248,-,371,680 -,636,432,76,-,386,686,770,828,582,-,433,203,526,600,848,227,616,-,217,117,707,369,109,586,205,809,-,-,240,-,853,-,-,-,768,-,371,-,540 774,289,833,257,-,381,239,722,711,468,933,-,-,17,-,-,148,-,-,853,-,-,-,-,264,194,260,947,-,752,147,-,-,343,112,273,344,680,540,-
-,-,-,427,668,495,377,678,-,177,-,-,870,-,869,624,300,609,131,-,251,-,-,-,856,221,514,-,591,762,182,56,-,884,412,273,636,-,-,774 -,-,262,-,-,508,472,799,-,956,578,363,940,143,-,162,122,910,-,729,802,941,922,573,531,539,667,607,-,920,-,-,315,649,937,-,185,102,636,289 -,262,-,-,926,-,958,158,647,47,621,264,81,-,402,813,649,386,252,391,264,637,349,-,-,-,108,-,727,225,578,699,-,898,294,-,575,168,432,833 427,-,-,-,366,-,-,635,-,32,962,468,893,854,718,427,448,916,258,-,760,909,529,311,404,-,-,588,680,875,-,615,-,409,758,221,-,-,76,257 668,-,926,366,-,-,-,250,268,-,503,944,-,677,-,727,793,457,981,191,-,-,-,351,969,925,987,328,282,589,-,873,477,-,-,19,450,-,-,- 495,508,-,-,-,-,-,765,711,819,305,302,926,-,-,582,-,861,-,683,293,-,-,66,-,27,-,-,290,-,786,-,554,817,33,-,54,506,386,381 377,472,958,-,-,-,-,-,-,120,42,-,134,219,457,639,538,374,-,-,-,966,-,-,-,-,-,449,120,797,358,232,550,-,305,997,662,744,686,239 678,799,158,635,250,765,-,-,-,35,-,106,385,652,160,-,890,812,605,953,-,-,-,79,-,712,613,312,452,-,978,900,-,901,-,-,225,533,770,722 -,-,647,-,268,711,-,-,-,283,-,172,-,663,236,36,403,286,986,-,-,810,761,574,53,793,-,-,777,330,936,883,286,-,174,-,-,-,828,711 177,956,47,32,-,819,120,35,283,-,50,-,565,36,767,684,344,489,565,-,-,103,810,463,733,665,494,644,863,25,385,-,342,470,-,-,-,730,582,468 -,578,621,962,503,305,42,-,-,50,-,155,519,-,-,256,990,801,154,53,474,650,402,-,-,-,966,-,-,406,989,772,932,7,-,823,391,-,-,933 -,363,264,468,944,302,-,106,172,-,155,-,-,-,380,438,-,41,266,-,-,104,867,609,-,270,861,-,-,165,-,675,250,686,995,366,191,-,433,- 870,940,81,893,-,926,134,385,-,565,519,-,-,313,851,-,-,-,248,220,-,826,359,829,-,234,198,145,409,68,359,-,814,218,186,-,-,929,203,- -,143,-,854,677,-,219,652,663,36,-,-,313,-,132,-,433,598,-,-,168,870,-,-,-,128,437,-,383,364,966,227,-,-,807,993,-,-,526,17 869,-,402,718,-,-,457,160,236,767,-,380,851,132,-,-,596,903,613,730,-,261,-,142,379,885,89,-,848,258,112,-,900,-,-,818,639,268,600,- 624,162,813,427,727,582,639,-,36,684,256,438,-,-,-,-,539,379,664,561,542,-,999,585,-,-,321,398,-,-,950,68,193,-,697,-,390,588,848,- 300,122,649,448,793,-,538,890,403,344,990,-,-,433,596,539,-,-,73,-,318,-,-,500,-,968,-,291,-,-,765,196,504,757,-,542,-,395,227,148 609,910,386,916,457,861,374,812,286,489,801,41,-,598,903,379,-,-,-,946,136,399,-,941,707,156,757,258,251,-,807,-,-,-,461,501,-,-,616,- 131,-,252,258,981,-,-,605,986,565,154,266,248,-,613,664,73,-,-,686,-,-,575,627,817,282,-,698,398,222,-,649,-,-,-,-,-,654,-,- -,729,391,-,191,683,-,953,-,-,53,-,220,-,730,561,-,946,686,-,-,389,729,553,304,703,455,857,260,-,991,182,351,477,867,-,-,889,217,853 251,802,264,760,-,293,-,-,-,-,474,-,-,168,-,542,318,136,-,-,-,-,392,-,-,-,267,407,27,651,80,927,-,974,977,-,-,457,117,- -,941,637,909,-,-,966,-,810,103,650,104,826,870,261,-,-,399,-,389,-,-,-,202,-,-,-,-,867,140,403,962,785,-,511,-,1,-,707,- -,922,349,529,-,-,-,-,761,810,402,867,359,-,-,999,-,-,575,729,392,-,-,388,939,-,959,-,83,463,361,-,-,512,931,-,224,690,369,- -,573,-,311,351,66,-,79,574,463,-,609,829,-,142,585,500,941,627,553,-,202,388,-,164,829,-,620,523,639,936,-,-,490,-,695,-,505,109,- 856,531,-,404,969,-,-,-,53,733,-,-,-,-,379,-,-,707,817,304,-,-,939,164,-,-,616,716,728,-,889,349,-,963,150,447,-,292,586,264 221,539,-,-,925,27,-,712,793,665,-,270,234,128,885,-,968,156,282,703,-,-,-,829,-,-,-,822,-,-,-,736,576,-,697,946,443,-,205,194 514,667,108,-,987,-,-,613,-,494,966,861,198,437,89,321,-,757,-,455,267,-,959,-,616,-,-,-,349,156,339,-,102,790,359,-,439,938,809,260 -,607,-,588,328,-,449,312,-,644,-,-,145,-,-,398,291,258,698,857,407,-,-,620,716,822,-,-,293,486,943,-,779,-,6,880,116,775,-,947 591,-,727,680,282,290,120,452,777,863,-,-,409,383,848,-,-,251,398,260,27,867,83,523,728,-,349,293,-,212,684,505,341,384,9,992,507,48,-,- 762,920,225,875,589,-,797,-,330,25,406,165,68,364,258,-,-,-,222,-,651,140,463,639,-,-,156,486,212,-,-,349,723,-,-,186,-,36,240,752 182,-,578,-,-,786,358,978,936,385,989,-,359,966,112,950,765,807,-,991,80,403,361,936,889,-,339,943,684,-,-,965,302,676,725,-,327,134,-,147 56,-,699,615,873,-,232,900,883,-,772,675,-,227,-,68,196,-,649,182,927,962,-,-,349,736,-,-,505,349,965,-,474,178,833,-,-,555,853,- -,315,-,-,477,554,550,-,286,342,932,250,814,-,900,193,504,-,-,351,-,785,-,-,-,576,102,779,341,723,302,474,-,689,-,-,-,451,-,- 884,649,898,409,-,817,-,901,-,470,7,686,218,-,-,-,757,-,-,477,974,-,512,490,963,-,790,-,384,-,676,178,689,-,245,596,445,-,-,343 412,937,294,758,-,33,305,-,174,-,-,995,186,807,-,697,-,461,-,867,977,511,931,-,150,697,359,6,9,-,725,833,-,245,-,949,-,270,-,112 273,-,-,221,19,-,997,-,-,-,823,366,-,993,818,-,542,501,-,-,-,-,-,695,447,946,-,880,992,186,-,-,-,596,949,-,91,-,768,273 636,185,575,-,450,54,662,225,-,-,391,191,-,-,639,390,-,-,-,-,-,1,224,-,-,443,439,116,507,-,327,-,-,445,-,91,-,248,-,344 -,102,168,-,-,506,744,533,-,730,-,-,929,-,268,588,395,-,654,889,457,-,690,505,292,-,938,775,48,36,134,555,451,-,270,-,248,-,371,680 -,636,432,76,-,386,686,770,828,582,-,433,203,526,600,848,227,616,-,217,117,707,369,109,586,205,809,-,-,240,-,853,-,-,-,768,-,371,-,540 774,289,833,257,-,381,239,722,711,468,933,-,-,17,-,-,148,-,-,853,-,-,-,-,264,194,260,947,-,752,147,-,-,343,112,273,344,680,540,-
-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 bogosort algorithm, also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. Bogosort generates random permutations until it guesses the correct one. More info on: https://en.wikipedia.org/wiki/Bogosort For doctests run following command: python -m doctest -v bogo_sort.py or python3 -m doctest -v bogo_sort.py For manual testing run: python bogo_sort.py """ import random def bogo_sort(collection): """Pure implementation of the bogosort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bogo_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> bogo_sort([]) [] >>> bogo_sort([-2, -5, -45]) [-45, -5, -2] """ def is_sorted(collection): if len(collection) < 2: return True for i in range(len(collection) - 1): if collection[i] > collection[i + 1]: return False return True while not is_sorted(collection): random.shuffle(collection) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(bogo_sort(unsorted))
""" This is a pure Python implementation of the bogosort algorithm, also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. Bogosort generates random permutations until it guesses the correct one. More info on: https://en.wikipedia.org/wiki/Bogosort For doctests run following command: python -m doctest -v bogo_sort.py or python3 -m doctest -v bogo_sort.py For manual testing run: python bogo_sort.py """ import random def bogo_sort(collection): """Pure implementation of the bogosort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bogo_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> bogo_sort([]) [] >>> bogo_sort([-2, -5, -45]) [-45, -5, -2] """ def is_sorted(collection): if len(collection) < 2: return True for i in range(len(collection) - 1): if collection[i] > collection[i + 1]: return False return True while not is_sorted(collection): random.shuffle(collection) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(bogo_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}`.
""" This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. In bubble sort, distance (or gap) between two compared elements is always one. Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values at the end of a list. More info on: https://en.wikipedia.org/wiki/Comb_sort For doctests run following command: python -m doctest -v comb_sort.py or python3 -m doctest -v comb_sort.py For manual testing run: python comb_sort.py """ def comb_sort(data: list) -> list: """Pure implementation of comb sort algorithm in Python :param data: mutable collection with comparable items :return: the same collection in ascending order Examples: >>> comb_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> comb_sort([]) [] >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3]) [-15, -7, 0, 2, 3, 8, 45, 99] """ shrink_factor = 1.3 gap = len(data) completed = False while not completed: # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data): if data[index] > data[index + gap]: # Swap values data[index], data[index + gap] = data[index + gap], data[index] completed = False index += 1 return data if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted))
""" This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. In bubble sort, distance (or gap) between two compared elements is always one. Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values at the end of a list. More info on: https://en.wikipedia.org/wiki/Comb_sort For doctests run following command: python -m doctest -v comb_sort.py or python3 -m doctest -v comb_sort.py For manual testing run: python comb_sort.py """ def comb_sort(data: list) -> list: """Pure implementation of comb sort algorithm in Python :param data: mutable collection with comparable items :return: the same collection in ascending order Examples: >>> comb_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> comb_sort([]) [] >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3]) [-15, -7, 0, 2, 3, 8, 45, 99] """ shrink_factor = 1.3 gap = len(data) completed = False while not completed: # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data): if data[index] > data[index + gap]: # Swap values data[index], data[index + gap] = data[index + gap], data[index] completed = False index += 1 return data if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted))
-1
TheAlgorithms/Python
4,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}`.
""" Approximates the area under the curve using the trapezoidal rule """ from typing import Callable, Union def trapezoidal_area( fnc: Callable[[Union[int, float]], Union[int, float]], x_start: Union[int, float], x_end: Union[int, float], steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" '10.000' >>> def f(x): ... return 9*x**2 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" '192.0000' >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for i in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x ** 3 + x ** 2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
""" Approximates the area under the curve using the trapezoidal rule """ from typing import Callable, Union def trapezoidal_area( fnc: Callable[[Union[int, float]], Union[int, float]], x_start: Union[int, float], x_end: Union[int, float], steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" '10.000' >>> def f(x): ... return 9*x**2 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" '192.0000' >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for i in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x ** 3 + x ** 2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
-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 import svm from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # different functions implementing different types of SVM's def NuSVC(train_x, train_y): svc_NuSVC = svm.NuSVC() svc_NuSVC.fit(train_x, train_y) return svc_NuSVC def Linearsvc(train_x, train_y): svc_linear = svm.LinearSVC(tol=10e-2) svc_linear.fit(train_x, train_y) return svc_linear def SVC(train_x, train_y): # svm.SVC(C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, # probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, # max_iter=1000, random_state=None) # various parameters like "kernel","gamma","C" can effectively tuned for a given # machine learning model. SVC = svm.SVC(gamma="auto") SVC.fit(train_x, train_y) return SVC def test(X_new): """ 3 test cases to be passed an array containing the sepal length (cm), sepal width (cm), petal length (cm), petal width (cm) based on which the target name will be predicted >>> test([1,2,1,4]) 'virginica' >>> test([5, 2, 4, 1]) 'versicolor' >>> test([6,3,4,1]) 'versicolor' """ iris = load_iris() # splitting the dataset to test and train train_x, test_x, train_y, test_y = train_test_split( iris["data"], iris["target"], random_state=4 ) # any of the 3 types of SVM can be used # current_model=SVC(train_x, train_y) # current_model=NuSVC(train_x, train_y) current_model = Linearsvc(train_x, train_y) prediction = current_model.predict([X_new]) return iris["target_names"][prediction][0] if __name__ == "__main__": import doctest doctest.testmod()
from sklearn import svm from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # different functions implementing different types of SVM's def NuSVC(train_x, train_y): svc_NuSVC = svm.NuSVC() svc_NuSVC.fit(train_x, train_y) return svc_NuSVC def Linearsvc(train_x, train_y): svc_linear = svm.LinearSVC(tol=10e-2) svc_linear.fit(train_x, train_y) return svc_linear def SVC(train_x, train_y): # svm.SVC(C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, # probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, # max_iter=1000, random_state=None) # various parameters like "kernel","gamma","C" can effectively tuned for a given # machine learning model. SVC = svm.SVC(gamma="auto") SVC.fit(train_x, train_y) return SVC def test(X_new): """ 3 test cases to be passed an array containing the sepal length (cm), sepal width (cm), petal length (cm), petal width (cm) based on which the target name will be predicted >>> test([1,2,1,4]) 'virginica' >>> test([5, 2, 4, 1]) 'versicolor' >>> test([6,3,4,1]) 'versicolor' """ iris = load_iris() # splitting the dataset to test and train train_x, test_x, train_y, test_y = train_test_split( iris["data"], iris["target"], random_state=4 ) # any of the 3 types of SVM can be used # current_model=SVC(train_x, train_y) # current_model=NuSVC(train_x, train_y) current_model = Linearsvc(train_x, train_y) prediction = current_model.predict([X_new]) return iris["target_names"][prediction][0] 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}`.
-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 P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ def p_series(nth_term: int, power: int) -> list: """Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) [1, '1/4', '1/9', '1/16', '1/25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) [1, '1/0.25', '1/0.1111111111111111', '1/0.0625', '1/0.04'] >>> p_series("", 1000) '' >>> p_series(0, 0) [] >>> p_series(1, 1) [1] """ if nth_term == "": return nth_term nth_term = int(nth_term) power = int(power) series = [] for temp in range(int(nth_term)): series.append(f"1/{pow(temp + 1, int(power))}" if series else 1) return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the P-Series") power = input("Enter the power for P-Series") print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ def p_series(nth_term: int, power: int) -> list: """Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) [1, '1/4', '1/9', '1/16', '1/25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) [1, '1/0.25', '1/0.1111111111111111', '1/0.0625', '1/0.04'] >>> p_series("", 1000) '' >>> p_series(0, 0) [] >>> p_series(1, 1) [1] """ if nth_term == "": return nth_term nth_term = int(nth_term) power = int(power) series = [] for temp in range(int(nth_term)): series.append(f"1/{pow(temp + 1, int(power))}" if series else 1) return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the P-Series") power = input("Enter the power for P-Series") print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
-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}`.
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i ** i return str(total)[-10:] if __name__ == "__main__": print(solution())
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i ** i return str(total)[-10:] if __name__ == "__main__": print(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}`.
# https://en.wikipedia.org/wiki/Ohm%27s_law def ohms_law(voltage: float, current: float, resistance: float) -> float: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Ohm%27s_law def ohms_law(voltage: float, current: float, resistance: float) -> float: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} 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}`.
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) Calculate the class probabilities : P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. ------------------------------------------------ Squared_Difference = (x - mean(k)) ** 2 Variance = (1 / (count(x) - count(classes))) * (for i = 1 to i = n --> sum(Squared_Difference(xi))) Making Predictions : discriminant(x) = x * (mean / variance) - ((mean ** 2) / (2 * variance)) + Ln(probability) --------------------------------------------------------------------------- After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: @EverLookNeverSee """ from math import log from os import name, system from random import gauss, seed from typing import Callable, TypeVar # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: """ Generate gaussian distribution instances based-on given mean and standard deviation :param mean: mean value of class :param std_dev: value of standard deviation entered by usr or default value of it :param instance_count: instance number of class :return: a list containing generated values based-on given mean, std_dev and instance_count >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079] """ seed(1) return [gauss(mean, std_dev) for _ in range(instance_count)] # Make corresponding Y flags to detecting classes def y_generator(class_count: int, instance_count: list) -> list: """ Generate y values for corresponding classes :param class_count: Number of classes(data groupings) in dataset :param instance_count: number of instances in class :return: corresponding values for data groupings in dataset >>> y_generator(1, [10]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> y_generator(2, [5, 10]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] """ return [k for k in range(class_count) for _ in range(instance_count[k])] # Calculate the class means def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class >>> items = gaussian_distribution(5.0, 1.0, 20) >>> calculate_mean(len(items), items) 5.011267842911003 """ # the sum of all items divided by number of instances return sum(items) / instance_count # Calculate the class probabilities def calculate_probabilities(instance_count: int, total_count: int) -> float: """ Calculate the probability that a given instance will belong to which class :param instance_count: number of instances in class :param total_count: the number of all instances :return: value of probability for considered class >>> calculate_probabilities(20, 60) 0.3333333333333333 >>> calculate_probabilities(30, 100) 0.3 """ # number of instances in specific class divided by number of all instances return instance_count / total_count # Calculate the variance def calculate_variance(items: list, means: list, total_count: int) -> float: """ Calculate the variance :param items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param total_count: the number of all instances :return: calculated variance for considered dataset >>> items = gaussian_distribution(5.0, 1.0, 20) >>> means = [5.011267842911003] >>> total_count = 20 >>> calculate_variance([items], means, total_count) 0.9618530973487491 """ squared_diff = [] # An empty list to store all squared differences # iterate over number of elements in items for i in range(len(items)): # for loop iterates over number of elements in inner layer of items for j in range(len(items[i])): # appending squared differences to 'squared_diff' list squared_diff.append((items[i][j] - means[i]) ** 2) # one divided by (the number of all instances - number of classes) multiplied by # sum of all squared differences n_classes = len(means) # Number of classes in dataset return 1 / (total_count - n_classes) * sum(squared_diff) # Making predictions def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079], [11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508], [16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508]] >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002] >>> variance = 0.9618530973487494 >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333] >>> predict_y_values(x_items, means, variance, ... probabilities) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ # An empty list to store generated discriminant values of all items in dataset for # each class results = [] # for loop iterates over number of elements in list for i in range(len(x_items)): # for loop iterates over number of inner items of each element for j in range(len(x_items[i])): temp = [] # to store all discriminant values of each item as a list # for loop iterates over number of classes we have in our dataset for k in range(len(x_items)): # appending values of discriminants for each class to 'temp' list temp.append( x_items[i][j] * (means[k] / variance) - (means[k] ** 2 / (2 * variance)) + log(probabilities[k]) ) # appending discriminant values of each item to 'results' list results.append(temp) return [result.index(max(result)) for result in results] # Calculating Accuracy def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_values' function :return: percentage of accuracy >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1] >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1] >>> accuracy(actual_y, predicted_y) 50.0 >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> accuracy(actual_y, predicted_y) 100.0 """ # iterate over one element of each list at a time (zip mode) # prediction is correct if actual Y value equals to predicted Y value correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j) # percentage of accuracy equals to number of correct predictions divided by number # of all data and multiplied by 100 return (correct / len(actual_y)) * 100 num = TypeVar("num") def valid_input( input_type: Callable[[object], num], # Usually float or int input_msg: str, err_msg: str, condition: Callable[[num], bool] = lambda x: True, default: str = None, ) -> num: """ Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input """ while True: try: user_input = input_type(input(input_msg).strip() or default) if condition(user_input): return user_input else: print(f"{user_input}: {err_msg}") continue except ValueError: print( f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" ) # Main Function def main(): """ This function starts execution phase """ while True: print(" Linear Discriminant Analysis ".center(50, "*")) print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes n_classes = valid_input( input_type=int, condition=lambda x: x > 0, input_msg="Enter the number of classes (Data Groupings): ", err_msg="Number of classes should be positive!", ) print("-" * 100) # Trying to get the value of standard deviation std_dev = valid_input( input_type=float, condition=lambda x: x >= 0, input_msg=( "Enter the value of standard deviation" "(Default value is 1.0 for all classes): " ), err_msg="Standard deviation should not be negative!", default="1.0", ) print("-" * 100) # Trying to get number of instances in classes and theirs means to generate # dataset counts = [] # An empty list to store instance counts of classes in dataset for i in range(n_classes): user_count = valid_input( input_type=int, condition=lambda x: x > 0, input_msg=(f"Enter The number of instances for class_{i+1}: "), err_msg="Number of instances should be positive!", ) counts.append(user_count) print("-" * 100) # An empty list to store values of user-entered means of classes user_means = [] for a in range(n_classes): user_mean = valid_input( input_type=float, input_msg=(f"Enter the value of mean for class_{a+1}: "), err_msg="This is an invalid value.", ) user_means.append(user_mean) print("-" * 100) print("Standard deviation: ", std_dev) # print out the number of instances in classes in separated line for i, count in enumerate(counts, 1): print(f"Number of instances in class_{i} is: {count}") print("-" * 100) # print out mean values of classes separated line for i, user_mean in enumerate(user_means, 1): print(f"Mean of class_{i} is: {user_mean}") print("-" * 100) # Generating training dataset drawn from gaussian distribution x = [ gaussian_distribution(user_means[j], std_dev, counts[j]) for j in range(n_classes) ] print("Generated Normal Distribution: \n", x) print("-" * 100) # Generating Ys to detecting corresponding classes y = y_generator(n_classes, counts) print("Generated Corresponding Ys: \n", y) print("-" * 100) # Calculating the value of actual mean for each class actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)] # for loop iterates over number of elements in 'actual_means' list and print # out them in separated line for i, actual_mean in enumerate(actual_means, 1): print(f"Actual(Real) mean of class_{i} is: {actual_mean}") print("-" * 100) # Calculating the value of probabilities for each class probabilities = [ calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes) ] # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class variance = calculate_variance(x, actual_means, sum(counts)) print("Variance: ", variance) print("-" * 100) # Predicting Y values # storing predicted Y values in 'pre_indexes' variable pre_indexes = predict_y_values(x, actual_means, variance, probabilities) print("-" * 100) # Calculating Accuracy of the model print(f"Accuracy: {accuracy(y, pre_indexes)}") print("-" * 100) print(" DONE ".center(100, "+")) if input("Press any key to restart or 'q' for quit: ").strip().lower() == "q": print("\n" + "GoodBye!".center(100, "-") + "\n") break system("cls" if name == "nt" else "clear") if __name__ == "__main__": main()
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) Calculate the class probabilities : P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. ------------------------------------------------ Squared_Difference = (x - mean(k)) ** 2 Variance = (1 / (count(x) - count(classes))) * (for i = 1 to i = n --> sum(Squared_Difference(xi))) Making Predictions : discriminant(x) = x * (mean / variance) - ((mean ** 2) / (2 * variance)) + Ln(probability) --------------------------------------------------------------------------- After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: @EverLookNeverSee """ from math import log from os import name, system from random import gauss, seed from typing import Callable, TypeVar # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: """ Generate gaussian distribution instances based-on given mean and standard deviation :param mean: mean value of class :param std_dev: value of standard deviation entered by usr or default value of it :param instance_count: instance number of class :return: a list containing generated values based-on given mean, std_dev and instance_count >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079] """ seed(1) return [gauss(mean, std_dev) for _ in range(instance_count)] # Make corresponding Y flags to detecting classes def y_generator(class_count: int, instance_count: list) -> list: """ Generate y values for corresponding classes :param class_count: Number of classes(data groupings) in dataset :param instance_count: number of instances in class :return: corresponding values for data groupings in dataset >>> y_generator(1, [10]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> y_generator(2, [5, 10]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] """ return [k for k in range(class_count) for _ in range(instance_count[k])] # Calculate the class means def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class >>> items = gaussian_distribution(5.0, 1.0, 20) >>> calculate_mean(len(items), items) 5.011267842911003 """ # the sum of all items divided by number of instances return sum(items) / instance_count # Calculate the class probabilities def calculate_probabilities(instance_count: int, total_count: int) -> float: """ Calculate the probability that a given instance will belong to which class :param instance_count: number of instances in class :param total_count: the number of all instances :return: value of probability for considered class >>> calculate_probabilities(20, 60) 0.3333333333333333 >>> calculate_probabilities(30, 100) 0.3 """ # number of instances in specific class divided by number of all instances return instance_count / total_count # Calculate the variance def calculate_variance(items: list, means: list, total_count: int) -> float: """ Calculate the variance :param items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param total_count: the number of all instances :return: calculated variance for considered dataset >>> items = gaussian_distribution(5.0, 1.0, 20) >>> means = [5.011267842911003] >>> total_count = 20 >>> calculate_variance([items], means, total_count) 0.9618530973487491 """ squared_diff = [] # An empty list to store all squared differences # iterate over number of elements in items for i in range(len(items)): # for loop iterates over number of elements in inner layer of items for j in range(len(items[i])): # appending squared differences to 'squared_diff' list squared_diff.append((items[i][j] - means[i]) ** 2) # one divided by (the number of all instances - number of classes) multiplied by # sum of all squared differences n_classes = len(means) # Number of classes in dataset return 1 / (total_count - n_classes) * sum(squared_diff) # Making predictions def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079], [11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508], [16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508]] >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002] >>> variance = 0.9618530973487494 >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333] >>> predict_y_values(x_items, means, variance, ... probabilities) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ # An empty list to store generated discriminant values of all items in dataset for # each class results = [] # for loop iterates over number of elements in list for i in range(len(x_items)): # for loop iterates over number of inner items of each element for j in range(len(x_items[i])): temp = [] # to store all discriminant values of each item as a list # for loop iterates over number of classes we have in our dataset for k in range(len(x_items)): # appending values of discriminants for each class to 'temp' list temp.append( x_items[i][j] * (means[k] / variance) - (means[k] ** 2 / (2 * variance)) + log(probabilities[k]) ) # appending discriminant values of each item to 'results' list results.append(temp) return [result.index(max(result)) for result in results] # Calculating Accuracy def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_values' function :return: percentage of accuracy >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1] >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1] >>> accuracy(actual_y, predicted_y) 50.0 >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> accuracy(actual_y, predicted_y) 100.0 """ # iterate over one element of each list at a time (zip mode) # prediction is correct if actual Y value equals to predicted Y value correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j) # percentage of accuracy equals to number of correct predictions divided by number # of all data and multiplied by 100 return (correct / len(actual_y)) * 100 num = TypeVar("num") def valid_input( input_type: Callable[[object], num], # Usually float or int input_msg: str, err_msg: str, condition: Callable[[num], bool] = lambda x: True, default: str = None, ) -> num: """ Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input """ while True: try: user_input = input_type(input(input_msg).strip() or default) if condition(user_input): return user_input else: print(f"{user_input}: {err_msg}") continue except ValueError: print( f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" ) # Main Function def main(): """ This function starts execution phase """ while True: print(" Linear Discriminant Analysis ".center(50, "*")) print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes n_classes = valid_input( input_type=int, condition=lambda x: x > 0, input_msg="Enter the number of classes (Data Groupings): ", err_msg="Number of classes should be positive!", ) print("-" * 100) # Trying to get the value of standard deviation std_dev = valid_input( input_type=float, condition=lambda x: x >= 0, input_msg=( "Enter the value of standard deviation" "(Default value is 1.0 for all classes): " ), err_msg="Standard deviation should not be negative!", default="1.0", ) print("-" * 100) # Trying to get number of instances in classes and theirs means to generate # dataset counts = [] # An empty list to store instance counts of classes in dataset for i in range(n_classes): user_count = valid_input( input_type=int, condition=lambda x: x > 0, input_msg=(f"Enter The number of instances for class_{i+1}: "), err_msg="Number of instances should be positive!", ) counts.append(user_count) print("-" * 100) # An empty list to store values of user-entered means of classes user_means = [] for a in range(n_classes): user_mean = valid_input( input_type=float, input_msg=(f"Enter the value of mean for class_{a+1}: "), err_msg="This is an invalid value.", ) user_means.append(user_mean) print("-" * 100) print("Standard deviation: ", std_dev) # print out the number of instances in classes in separated line for i, count in enumerate(counts, 1): print(f"Number of instances in class_{i} is: {count}") print("-" * 100) # print out mean values of classes separated line for i, user_mean in enumerate(user_means, 1): print(f"Mean of class_{i} is: {user_mean}") print("-" * 100) # Generating training dataset drawn from gaussian distribution x = [ gaussian_distribution(user_means[j], std_dev, counts[j]) for j in range(n_classes) ] print("Generated Normal Distribution: \n", x) print("-" * 100) # Generating Ys to detecting corresponding classes y = y_generator(n_classes, counts) print("Generated Corresponding Ys: \n", y) print("-" * 100) # Calculating the value of actual mean for each class actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)] # for loop iterates over number of elements in 'actual_means' list and print # out them in separated line for i, actual_mean in enumerate(actual_means, 1): print(f"Actual(Real) mean of class_{i} is: {actual_mean}") print("-" * 100) # Calculating the value of probabilities for each class probabilities = [ calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes) ] # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class variance = calculate_variance(x, actual_means, sum(counts)) print("Variance: ", variance) print("-" * 100) # Predicting Y values # storing predicted Y values in 'pre_indexes' variable pre_indexes = predict_y_values(x, actual_means, variance, probabilities) print("-" * 100) # Calculating Accuracy of the model print(f"Accuracy: {accuracy(y, pre_indexes)}") print("-" * 100) print(" DONE ".center(100, "+")) if input("Press any key to restart or 'q' for quit: ").strip().lower() == "q": print("\n" + "GoodBye!".center(100, "-") + "\n") break system("cls" if name == "nt" else "clear") 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}`.
-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 35 https://projecteuler.net/problem=35 Problem Statement: The number 197 is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? To solve this problem in an efficient manner, we will first mark all the primes below 1 million using the Seive of Eratosthenes. Then, out of all these primes, we will rule out the numbers which contain an even digit. After this we will generate each circular combination of the number and check if all are prime. """ from __future__ import annotations seive = [True] * 1000001 i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ For 2 <= n <= 1000000, return True if n is prime. >>> is_prime(87) False >>> is_prime(23) True >>> is_prime(25363) False """ return seive[n] def contains_an_even_digit(n: int) -> bool: """ Return True if n contains an even digit. >>> contains_an_even_digit(0) True >>> contains_an_even_digit(975317933) False >>> contains_an_even_digit(-245679) True """ return any(digit in "02468" for digit in str(n)) def find_circular_primes(limit: int = 1000000) -> list[int]: """ Return circular primes below limit. >>> len(find_circular_primes(100)) 13 >>> len(find_circular_primes(1000000)) 55 """ result = [2] # result already includes the number 2. for num in range(3, limit + 1, 2): if is_prime(num) and not contains_an_even_digit(num): str_num = str(num) list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))] if all(is_prime(i) for i in list_nums): result.append(num) return result def solution() -> int: """ >>> solution() 55 """ return len(find_circular_primes()) if __name__ == "__main__": print(f"{len(find_circular_primes()) = }")
""" Project Euler Problem 35 https://projecteuler.net/problem=35 Problem Statement: The number 197 is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? To solve this problem in an efficient manner, we will first mark all the primes below 1 million using the Seive of Eratosthenes. Then, out of all these primes, we will rule out the numbers which contain an even digit. After this we will generate each circular combination of the number and check if all are prime. """ from __future__ import annotations seive = [True] * 1000001 i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ For 2 <= n <= 1000000, return True if n is prime. >>> is_prime(87) False >>> is_prime(23) True >>> is_prime(25363) False """ return seive[n] def contains_an_even_digit(n: int) -> bool: """ Return True if n contains an even digit. >>> contains_an_even_digit(0) True >>> contains_an_even_digit(975317933) False >>> contains_an_even_digit(-245679) True """ return any(digit in "02468" for digit in str(n)) def find_circular_primes(limit: int = 1000000) -> list[int]: """ Return circular primes below limit. >>> len(find_circular_primes(100)) 13 >>> len(find_circular_primes(1000000)) 55 """ result = [2] # result already includes the number 2. for num in range(3, limit + 1, 2): if is_prime(num) and not contains_an_even_digit(num): str_num = str(num) list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))] if all(is_prime(i) for i in list_nums): result.append(num) return result def solution() -> int: """ >>> solution() 55 """ return len(find_circular_primes()) if __name__ == "__main__": print(f"{len(find_circular_primes()) = }")
-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 binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) def tim_sort(lst): """ >>> tim_sort("Python") ['P', 'h', 'n', 'o', 't', 'y'] >>> tim_sort((1.1, 1, 0, -1, -1.1)) [-1.1, -1, 0, 1, 1.1] >>> tim_sort(list(reversed(list(range(7))))) [0, 1, 2, 3, 4, 5, 6] >>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1]) True >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1]) True """ length = len(lst) runs, sorted_runs = [], [] new_run = [lst[0]] sorted_array = [] i = 1 while i < length: if lst[i] < lst[i - 1]: runs.append(new_run) new_run = [lst[i]] else: new_run.append(lst[i]) i += 1 runs.append(new_run) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array def main(): lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) if __name__ == "__main__": main()
def binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) def tim_sort(lst): """ >>> tim_sort("Python") ['P', 'h', 'n', 'o', 't', 'y'] >>> tim_sort((1.1, 1, 0, -1, -1.1)) [-1.1, -1, 0, 1, 1.1] >>> tim_sort(list(reversed(list(range(7))))) [0, 1, 2, 3, 4, 5, 6] >>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1]) True >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1]) True """ length = len(lst) runs, sorted_runs = [], [] new_run = [lst[0]] sorted_array = [] i = 1 while i < length: if lst[i] < lst[i - 1]: runs.append(new_run) new_run = [lst[i]] else: new_run.append(lst[i]) i += 1 runs.append(new_run) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array def main(): lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) 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}`.
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
-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}`.
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number, digitAmount): """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digitAmount > 0: return round(number - int(number), digitAmount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number, digitAmount): """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digitAmount > 0: return round(number - int(number), digitAmount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
-1
TheAlgorithms/Python
4,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 113: https://projecteuler.net/problem=113 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. As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 10^10. How many numbers below a googol (10^100) are not bouncy? """ def choose(n: int, r: int) -> int: """ Calculate the binomial coefficient c(n,r) using the multiplicative formula. >>> choose(4,2) 6 >>> choose(5,3) 10 >>> choose(20,6) 38760 """ ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i return round(ret) def non_bouncy_exact(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_exact(1) 9 >>> non_bouncy_exact(6) 7998 >>> non_bouncy_exact(10) 136126 """ return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_upto(1) 9 >>> non_bouncy_upto(6) 12951 >>> non_bouncy_upto(10) 277032 """ return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: """ Caclulate the number of non-bouncy numbers less than a googol. >>> solution(6) 12951 >>> solution(10) 277032 """ return non_bouncy_upto(num_digits) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 113: https://projecteuler.net/problem=113 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. As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 10^10. How many numbers below a googol (10^100) are not bouncy? """ def choose(n: int, r: int) -> int: """ Calculate the binomial coefficient c(n,r) using the multiplicative formula. >>> choose(4,2) 6 >>> choose(5,3) 10 >>> choose(20,6) 38760 """ ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i return round(ret) def non_bouncy_exact(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_exact(1) 9 >>> non_bouncy_exact(6) 7998 >>> non_bouncy_exact(10) 136126 """ return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_upto(1) 9 >>> non_bouncy_upto(6) 12951 >>> non_bouncy_upto(10) 277032 """ return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: """ Caclulate the number of non-bouncy numbers less than a googol. >>> solution(6) 12951 >>> solution(10) 277032 """ return non_bouncy_upto(num_digits) 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}`.
0000000000000000000000000000000000000000 9caf4784aada17dc75348f77cc8c356df503c0f3 jupyter <jupyter@data-collection2-susnato.c.rishabh-experiments.internal> 1704811012 +0000 clone: from https://github.com/TheAlgorithms/Python.git
0000000000000000000000000000000000000000 9caf4784aada17dc75348f77cc8c356df503c0f3 jupyter <jupyter@data-collection2-susnato.c.rishabh-experiments.internal> 1704811012 +0000 clone: from https://github.com/TheAlgorithms/Python.git
-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}`.
""" wiki: https://en.wikipedia.org/wiki/Anagram """ def check_anagrams(first_str: str, second_str: str) -> bool: """ Two strings are anagrams if they are made of the same letters arranged differently (ignoring the case). >>> check_anagrams('Silent', 'Listen') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('There', 'Their') False """ return ( "".join(sorted(first_str.lower())).strip() == "".join(sorted(second_str.lower())).strip() ) if __name__ == "__main__": from doctest import testmod testmod() input_A = input("Enter the first string ").strip() input_B = input("Enter the second string ").strip() status = check_anagrams(input_A, input_B) print(f"{input_A} and {input_B} are {'' if status else 'not '}anagrams.")
""" wiki: https://en.wikipedia.org/wiki/Anagram """ def check_anagrams(first_str: str, second_str: str) -> bool: """ Two strings are anagrams if they are made of the same letters arranged differently (ignoring the case). >>> check_anagrams('Silent', 'Listen') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('There', 'Their') False """ return ( "".join(sorted(first_str.lower())).strip() == "".join(sorted(second_str.lower())).strip() ) if __name__ == "__main__": from doctest import testmod testmod() input_A = input("Enter the first string ").strip() input_B = input("Enter the second string ").strip() status = check_anagrams(input_A, input_B) print(f"{input_A} and {input_B} are {'' if status else 'not '}anagrams.")
-1