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
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: """ Class Instagram crawl instagram user information Usage: (doctest failing on GitHub Actions) # >>> instagram_user = InstagramUser("github") # >>> instagram_user.is_verified True # >>> instagram_user.biography 'Built for developers.' """ def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: """ Return a dict of user information """ html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: """ A self running doctest >>> test_instagram_user() """ import os if os.environ.get("CI"): return None # test failing on GitHub Actions instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: """ Class Instagram crawl instagram user information Usage: (doctest failing on GitHub Actions) # >>> instagram_user = InstagramUser("github") # >>> instagram_user.is_verified True # >>> instagram_user.biography 'Built for developers.' """ def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: """ Return a dict of user information """ html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: """ A self running doctest >>> test_instagram_user() """ import os if os.environ.get("CI"): return None # test failing on GitHub Actions instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Floor_and_ceiling_functions """ def floor(x) -> int: """ Return the floor of x as an Integral. :param x: the number :return: the largest integer <= x. >>> import math >>> all(floor(n) == math.floor(n) for n ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) True """ return int(x) if x - int(x) >= 0 else int(x) - 1 if __name__ == "__main__": import doctest doctest.testmod()
""" https://en.wikipedia.org/wiki/Floor_and_ceiling_functions """ def floor(x) -> int: """ Return the floor of x as an Integral. :param x: the number :return: the largest integer <= x. >>> import math >>> all(floor(n) == math.floor(n) for n ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) True """ return int(x) if x - int(x) >= 0 else int(x) - 1 if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 87: https://projecteuler.net/problem=87 The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way: 28 = 22 + 23 + 24 33 = 32 + 23 + 24 49 = 52 + 23 + 24 47 = 22 + 33 + 24 How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power? """ def solution(limit: int = 50000000) -> int: """ Return the number of integers less than limit which can be expressed as the sum of a prime square, prime cube, and prime fourth power. >>> solution(50) 4 """ ret = set() prime_square_limit = int((limit - 24) ** (1 / 2)) primes = set(range(3, prime_square_limit + 1, 2)) primes.add(2) for p in range(3, prime_square_limit + 1, 2): if p not in primes: continue primes.difference_update(set(range(p * p, prime_square_limit + 1, p))) for prime1 in primes: square = prime1 * prime1 for prime2 in primes: cube = prime2 * prime2 * prime2 if square + cube >= limit - 16: break for prime3 in primes: tetr = prime3 * prime3 * prime3 * prime3 total = square + cube + tetr if total >= limit: break ret.add(total) return len(ret) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 87: https://projecteuler.net/problem=87 The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way: 28 = 22 + 23 + 24 33 = 32 + 23 + 24 49 = 52 + 23 + 24 47 = 22 + 33 + 24 How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power? """ def solution(limit: int = 50000000) -> int: """ Return the number of integers less than limit which can be expressed as the sum of a prime square, prime cube, and prime fourth power. >>> solution(50) 4 """ ret = set() prime_square_limit = int((limit - 24) ** (1 / 2)) primes = set(range(3, prime_square_limit + 1, 2)) primes.add(2) for p in range(3, prime_square_limit + 1, 2): if p not in primes: continue primes.difference_update(set(range(p * p, prime_square_limit + 1, p))) for prime1 in primes: square = prime1 * prime1 for prime2 in primes: cube = prime2 * prime2 * prime2 if square + cube >= limit - 16: break for prime3 in primes: tetr = prime3 * prime3 * prime3 * prime3 total = square + cube + tetr if total >= limit: break ret.add(total) return len(ret) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> twos_complement(-5) '0b1011' >>> twos_complement(-17) '0b101111' >>> twos_complement(-207) '0b100110001' >>> twos_complement(1) Traceback (most recent call last): ... ValueError: input must be a negative integer """ if number > 0: raise ValueError("input must be a negative integer") binary_number_length = len(bin(number)[3:]) twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:] twos_complement_number = ( ( "1" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
# Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> twos_complement(-5) '0b1011' >>> twos_complement(-17) '0b101111' >>> twos_complement(-207) '0b100110001' >>> twos_complement(1) Traceback (most recent call last): ... ValueError: input must be a negative integer """ if number > 0: raise ValueError("input must be a negative integer") binary_number_length = len(bin(number)[3:]) twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:] twos_complement_number = ( ( "1" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Normal Distribution QuickSort Algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution. This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one. ## Array Elements The array elements are taken from a Standard Normal Distribution , having mean = 0 and standard deviation 1. #### The code ```python >>> import numpy as np >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> p = 100 # 100 elements are to be sorted >>> mu, sigma = 0, 1 # mean and standard deviation >>> X = np.random.normal(mu, sigma, p) >>> np.save(outfile, X) >>> print('The array is') >>> print(X) ``` ------ #### The Distribution of the Array elements. ```python >>> mu, sigma = 0, 1 # mean and standard deviation >>> s = np.random.normal(mu, sigma, p) >>> count, bins, ignored = plt.hist(s, 30, normed=True) >>> plt.plot(bins , 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2) ),linewidth=2, color='r') >>> plt.show() ``` ----- ![](https://www.mathsisfun.com/data/images/normal-distrubution-large.gif) --- --------------------- -- ## Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort ```python >>>import matplotlib.pyplot as plt # Normal Disrtibution QuickSort is red >>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,6,15,43,136,340,800,2156,6821,16325],linewidth=2, color='r') #Ordinary QuickSort is green >>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,4,16,67,122,362,949,2131,5086,12866],linewidth=2, color='g') >>> plt.show() ``` ---- ------------------
# Normal Distribution QuickSort Algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution. This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one. ## Array Elements The array elements are taken from a Standard Normal Distribution , having mean = 0 and standard deviation 1. #### The code ```python >>> import numpy as np >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> p = 100 # 100 elements are to be sorted >>> mu, sigma = 0, 1 # mean and standard deviation >>> X = np.random.normal(mu, sigma, p) >>> np.save(outfile, X) >>> print('The array is') >>> print(X) ``` ------ #### The Distribution of the Array elements. ```python >>> mu, sigma = 0, 1 # mean and standard deviation >>> s = np.random.normal(mu, sigma, p) >>> count, bins, ignored = plt.hist(s, 30, normed=True) >>> plt.plot(bins , 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2) ),linewidth=2, color='r') >>> plt.show() ``` ----- ![](https://www.mathsisfun.com/data/images/normal-distrubution-large.gif) --- --------------------- -- ## Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort ```python >>>import matplotlib.pyplot as plt # Normal Disrtibution QuickSort is red >>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,6,15,43,136,340,800,2156,6821,16325],linewidth=2, color='r') #Ordinary QuickSort is green >>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,4,16,67,122,362,949,2131,5086,12866],linewidth=2, color='g') >>> plt.show() ``` ---- ------------------
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Lychrel numbers Problem 55: https://projecteuler.net/problem=55 If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? """ def is_palindrome(n: int) -> bool: """ Returns True if a number is palindrome. >>> is_palindrome(12567321) False >>> is_palindrome(1221) True >>> is_palindrome(9876789) True """ return str(n) == str(n)[::-1] def sum_reverse(n: int) -> int: """ Returns the sum of n and reverse of n. >>> sum_reverse(123) 444 >>> sum_reverse(3478) 12221 >>> sum_reverse(12) 33 """ return int(n) + int(str(n)[::-1]) def solution(limit: int = 10000) -> int: """ Returns the count of all lychrel numbers below limit. >>> solution(10000) 249 >>> solution(5000) 76 >>> solution(1000) 13 """ lychrel_nums = [] for num in range(1, limit): iterations = 0 a = num while iterations < 50: num = sum_reverse(num) iterations += 1 if is_palindrome(num): break else: lychrel_nums.append(a) return len(lychrel_nums) if __name__ == "__main__": print(f"{solution() = }")
""" Lychrel numbers Problem 55: https://projecteuler.net/problem=55 If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? """ def is_palindrome(n: int) -> bool: """ Returns True if a number is palindrome. >>> is_palindrome(12567321) False >>> is_palindrome(1221) True >>> is_palindrome(9876789) True """ return str(n) == str(n)[::-1] def sum_reverse(n: int) -> int: """ Returns the sum of n and reverse of n. >>> sum_reverse(123) 444 >>> sum_reverse(3478) 12221 >>> sum_reverse(12) 33 """ return int(n) + int(str(n)[::-1]) def solution(limit: int = 10000) -> int: """ Returns the count of all lychrel numbers below limit. >>> solution(10000) 249 >>> solution(5000) 76 >>> solution(1000) 13 """ lychrel_nums = [] for num in range(1, limit): iterations = 0 a = num while iterations < 50: num = sum_reverse(num) iterations += 1 if is_palindrome(num): break else: lychrel_nums.append(a) return len(lychrel_nums) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? Solution: First, we need to generate all 4 digits prime numbers. Then greedy all of them and use permutation to form new numbers. Use binary search to check if the permutated numbers is in our prime list and include them in a candidate list. After that, bruteforce all passed candidates sequences using 3 nested loops since we know the answer will be 12 digits. The bruteforce of this solution will be about 1 sec. """ from itertools import permutations from math import floor, sqrt def is_prime(number: int) -> bool: """ function to check whether the number is prime or not. >>> is_prime(2) True >>> is_prime(6) False >>> is_prime(1) False >>> is_prime(-800) False >>> is_prime(104729) True """ if number < 2: return False for i in range(2, floor(sqrt(number)) + 1): if number % i == 0: return False return True def search(target: int, prime_list: list) -> bool: """ function to search a number in a list using Binary Search. >>> search(3, [1, 2, 3]) True >>> search(4, [1, 2, 3]) False >>> search(101, list(range(-100, 100))) False """ left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False def solution(): """ Return the solution of the problem. >>> solution() 296962999629 """ prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer) if __name__ == "__main__": print(solution())
""" Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? Solution: First, we need to generate all 4 digits prime numbers. Then greedy all of them and use permutation to form new numbers. Use binary search to check if the permutated numbers is in our prime list and include them in a candidate list. After that, bruteforce all passed candidates sequences using 3 nested loops since we know the answer will be 12 digits. The bruteforce of this solution will be about 1 sec. """ from itertools import permutations from math import floor, sqrt def is_prime(number: int) -> bool: """ function to check whether the number is prime or not. >>> is_prime(2) True >>> is_prime(6) False >>> is_prime(1) False >>> is_prime(-800) False >>> is_prime(104729) True """ if number < 2: return False for i in range(2, floor(sqrt(number)) + 1): if number % i == 0: return False return True def search(target: int, prime_list: list) -> bool: """ function to search a number in a list using Binary Search. >>> search(3, [1, 2, 3]) True >>> search(4, [1, 2, 3]) False >>> search(101, list(range(-100, 100))) False """ left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False def solution(): """ Return the solution of the problem. >>> solution() 296962999629 """ prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Literal LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def translate_message( key: str, message: str, mode: Literal["encrypt", "decrypt"] ) -> str: """ >>> 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() -> None: 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()
from typing import Literal LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def translate_message( key: str, message: str, mode: Literal["encrypt", "decrypt"] ) -> str: """ >>> 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() -> None: 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
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LRU Cache >>> DoubleLinkedListNode(1,1) Node: key: 1, val: 1, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return "Node: key: {}, val: {}, has next: {}, has prev: {}".format( self.key, self.val, self.next is not None, self.prev is not None ) class DoubleLinkedList(Generic[T, U]): """ Double Linked List built specifically for LRU Cache >>> dll: DoubleLinkedList = DoubleLinkedList() >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: None, val: None, has next: False, has prev: True >>> first_node = DoubleLinkedListNode(1,10) >>> first_node Node: key: 1, val: 10, has next: False, has prev: False >>> dll.add(first_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # node is mutated >>> first_node Node: key: 1, val: 10, has next: True, has prev: True >>> second_node = DoubleLinkedListNode(2,20) >>> second_node Node: key: 2, val: 20, has next: False, has prev: False >>> dll.add(second_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> removed_node = dll.remove(first_node) >>> assert removed_node == first_node >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # Attempt to remove node not on list >>> removed_node = dll.remove(first_node) >>> removed_node is None True >>> # Attempt to remove head or rear >>> dll.head Node: key: None, val: None, has next: True, has prev: False >>> dll.remove(dll.head) is None True >>> # Attempt to remove head or rear >>> dll.rear Node: key: None, val: None, has next: False, has prev: True >>> dll.remove(dll.rear) is None True """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: """ Adds the given node to the end of the list (before rear) """ previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """ Removes and returns the given node from the list Returns None if node.prev or node.next is None """ if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LRUCache(Generic[T, U]): """ LRU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LRUCache(2) >>> cache.set(1, 1) >>> cache.set(2, 2) >>> cache.get(1) 1 >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 2, has next: True, has prev: True, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 2: Node: key: 2, val: 2, has next: True, has prev: True} >>> cache.set(3, 3) >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: 3, val: 3, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 3: Node: key: 3, val: 3, has next: True, has prev: True} >>> cache.get(2) is None True >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) 3 >>> cache.get(4) 4 >>> cache CacheInfo(hits=3, misses=2, capacity=2, current size=2) >>> @LRUCache.decorator(100) ... def fib(num): ... if num in (1, 2): ... return 1 ... return fib(num - 1) + fib(num - 2) >>> for i in range(1, 100): ... res = fib(i) >>> fib.cache_info() CacheInfo(hits=194, misses=99, capacity=100, current size=99) """ # class variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: """ Return the details for the cache instance [hits, misses, capacity, current_size] """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__(self, key: T) -> bool: """ >>> cache = LRUCache(1) >>> 1 in cache False >>> cache.set(1, 1) >>> 1 in cache True """ return key in self.cache def get(self, key: T) -> U | None: """ Returns the value for the input key and updates the Double Linked List. Returns None if key is not present in cache """ # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: # bump node to the end of the list, update value node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """ Decorator version of LRU Cache Decorated function must be function of T -> U """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LRUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LRU Cache >>> DoubleLinkedListNode(1,1) Node: key: 1, val: 1, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return "Node: key: {}, val: {}, has next: {}, has prev: {}".format( self.key, self.val, self.next is not None, self.prev is not None ) class DoubleLinkedList(Generic[T, U]): """ Double Linked List built specifically for LRU Cache >>> dll: DoubleLinkedList = DoubleLinkedList() >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: None, val: None, has next: False, has prev: True >>> first_node = DoubleLinkedListNode(1,10) >>> first_node Node: key: 1, val: 10, has next: False, has prev: False >>> dll.add(first_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # node is mutated >>> first_node Node: key: 1, val: 10, has next: True, has prev: True >>> second_node = DoubleLinkedListNode(2,20) >>> second_node Node: key: 2, val: 20, has next: False, has prev: False >>> dll.add(second_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> removed_node = dll.remove(first_node) >>> assert removed_node == first_node >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # Attempt to remove node not on list >>> removed_node = dll.remove(first_node) >>> removed_node is None True >>> # Attempt to remove head or rear >>> dll.head Node: key: None, val: None, has next: True, has prev: False >>> dll.remove(dll.head) is None True >>> # Attempt to remove head or rear >>> dll.rear Node: key: None, val: None, has next: False, has prev: True >>> dll.remove(dll.rear) is None True """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: """ Adds the given node to the end of the list (before rear) """ previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """ Removes and returns the given node from the list Returns None if node.prev or node.next is None """ if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LRUCache(Generic[T, U]): """ LRU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LRUCache(2) >>> cache.set(1, 1) >>> cache.set(2, 2) >>> cache.get(1) 1 >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 2, has next: True, has prev: True, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 2: Node: key: 2, val: 2, has next: True, has prev: True} >>> cache.set(3, 3) >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: 3, val: 3, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 3: Node: key: 3, val: 3, has next: True, has prev: True} >>> cache.get(2) is None True >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) 3 >>> cache.get(4) 4 >>> cache CacheInfo(hits=3, misses=2, capacity=2, current size=2) >>> @LRUCache.decorator(100) ... def fib(num): ... if num in (1, 2): ... return 1 ... return fib(num - 1) + fib(num - 2) >>> for i in range(1, 100): ... res = fib(i) >>> fib.cache_info() CacheInfo(hits=194, misses=99, capacity=100, current size=99) """ # class variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: """ Return the details for the cache instance [hits, misses, capacity, current_size] """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__(self, key: T) -> bool: """ >>> cache = LRUCache(1) >>> 1 in cache False >>> cache.set(1, 1) >>> 1 in cache True """ return key in self.cache def get(self, key: T) -> U | None: """ Returns the value for the input key and updates the Double Linked List. Returns None if key is not present in cache """ # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: # bump node to the end of the list, update value node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """ Decorator version of LRU Cache Decorated function must be function of T -> U """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LRUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def lower(word: str) -> str: """ Will convert the entire string to lowercase letters >>> lower("wow") 'wow' >>> lower("HellZo") 'hellzo' >>> lower("WHAT") 'what' >>> lower("wh[]32") 'wh[]32' >>> lower("whAT") 'what' """ # converting to ascii value int value and checking to see if char is a capital # letter if it is a capital letter it is getting shift by 32 which makes it a lower # case letter return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
def lower(word: str) -> str: """ Will convert the entire string to lowercase letters >>> lower("wow") 'wow' >>> lower("HellZo") 'hellzo' >>> lower("WHAT") 'what' >>> lower("wh[]32") 'wh[]32' >>> lower("whAT") 'what' """ # converting to ascii value int value and checking to see if char is a capital # letter if it is a capital letter it is getting shift by 32 which makes it a lower # case letter return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (127 < gray) & (gray <= 255) def dilation(image: np.array, kernel: np.array) -> np.array: """ Return dilated image >>> dilation(np.array([[True, False, True]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> dilation(np.array([[False, False, True]]), np.array([[1, 0, 1]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation > 0) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) output = dilation(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (127 < gray) & (gray <= 255) def dilation(image: np.array, kernel: np.array) -> np.array: """ Return dilated image >>> dilation(np.array([[True, False, True]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> dilation(np.array([[False, False, True]]), np.array([[1, 0, 1]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation > 0) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) output = dilation(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the Heap's algorithm (recursive version), returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: # k is even arr[i], arr[k - 1] = arr[k - 1], arr[i] else: # k is odd arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the Heap's algorithm (recursive version), returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: # k is even arr[i], arr[k - 1] = arr[k - 1], arr[i] else: # k is odd arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length ``n`` given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. """ def naive_cut_rod_recursive(n: int, prices: list): """ Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments ------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples -------- >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) 10 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_down_cut_rod(n: int, prices: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. This function serves as a wrapper for _top_down_cut_rod_recursive Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Note ---- For convenience and because Python's lists using 0-indexing, length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples ------- >>> top_down_cut_rod(4, [1, 5, 8, 9]) 10 >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` max_rev: list, the computed maximum revenue for a piece of rod. ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): """ Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments ---------- n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples ------- >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) 10 >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): """ Basic checks on the arguments to the rod-cutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod """ if n < 0: raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") if n > len(prices): raise ValueError( f"Each integral piece of rod must have a corresponding " f"price. Got n = {n} but length of prices = {len(prices)}" ) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length ``n`` given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. """ def naive_cut_rod_recursive(n: int, prices: list): """ Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments ------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples -------- >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) 10 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_down_cut_rod(n: int, prices: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. This function serves as a wrapper for _top_down_cut_rod_recursive Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Note ---- For convenience and because Python's lists using 0-indexing, length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples ------- >>> top_down_cut_rod(4, [1, 5, 8, 9]) 10 >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` max_rev: list, the computed maximum revenue for a piece of rod. ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): """ Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments ---------- n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples ------- >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) 10 >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): """ Basic checks on the arguments to the rod-cutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod """ if n < 0: raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") if n > len(prices): raise ValueError( f"Each integral piece of rod must have a corresponding " f"price. Got n = {n} but length of prices = {len(prices)}" ) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Euler Problem 26 https://projecteuler.net/problem=26 Problem Statement: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ def solution(numerator: int = 1, digit: int = 1000) -> int: """ Considering any range can be provided, because as per the problem, the digit d < 1000 >>> solution(1, 10) 7 >>> solution(10, 100) 97 >>> solution(10, 1000) 983 """ the_digit = 1 longest_list_length = 0 for divide_by_number in range(numerator, digit + 1): has_been_divided: list[int] = [] now_divide = numerator for division_cycle in range(1, digit + 1): if now_divide in has_been_divided: if longest_list_length < len(has_been_divided): longest_list_length = len(has_been_divided) the_digit = divide_by_number else: has_been_divided.append(now_divide) now_divide = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
""" Euler Problem 26 https://projecteuler.net/problem=26 Problem Statement: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ def solution(numerator: int = 1, digit: int = 1000) -> int: """ Considering any range can be provided, because as per the problem, the digit d < 1000 >>> solution(1, 10) 7 >>> solution(10, 100) 97 >>> solution(10, 1000) 983 """ the_digit = 1 longest_list_length = 0 for divide_by_number in range(numerator, digit + 1): has_been_divided: list[int] = [] now_divide = numerator for division_cycle in range(1, digit + 1): if now_divide in has_been_divided: if longest_list_length < len(has_been_divided): longest_list_length = len(has_been_divided) the_digit = divide_by_number else: has_been_divided.append(now_divide) now_divide = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ from __future__ import annotations from random import choice def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: list[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ from __future__ import annotations from random import choice def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: list[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars.keys() else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda l: l.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if type(root) is Letter: root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars.keys() else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda l: l.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if type(root) is Letter: root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Print all the Catalan numbers from 0 to n, n being the user input. * The Catalan numbers are a sequence of positive integers that * appear in many counting problems in combinatorics [1]. Such * problems include counting [2]: * - The number of Dyck words of length 2n * - The number well-formed expressions with n pairs of parentheses * (e.g., `()()` is valid but `())(` is not) * - The number of different ways n + 1 factors can be completely * parenthesized (e.g., for n = 2, C(n) = 2 and (ab)c and a(bc) * are the two valid ways to parenthesize. * - The number of full binary trees with n + 1 leaves * A Catalan number satisfies the following recurrence relation * which we will use in this algorithm [1]. * C(0) = C(1) = 1 * C(n) = sum(C(i).C(n-i-1)), from i = 0 to n-1 * In addition, the n-th Catalan number can be calculated using * the closed form formula below [1]: * C(n) = (1 / (n + 1)) * (2n choose n) * Sources: * [1] https://brilliant.org/wiki/catalan-numbers/ * [2] https://en.wikipedia.org/wiki/Catalan_number """ def catalan_numbers(upper_limit: int) -> "list[int]": """ Return a list of the Catalan number sequence from 0 through `upper_limit`. >>> catalan_numbers(5) [1, 1, 2, 5, 14, 42] >>> catalan_numbers(2) [1, 1, 2] >>> catalan_numbers(-1) Traceback (most recent call last): ValueError: Limit for the Catalan sequence must be ≥ 0 """ if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
""" Print all the Catalan numbers from 0 to n, n being the user input. * The Catalan numbers are a sequence of positive integers that * appear in many counting problems in combinatorics [1]. Such * problems include counting [2]: * - The number of Dyck words of length 2n * - The number well-formed expressions with n pairs of parentheses * (e.g., `()()` is valid but `())(` is not) * - The number of different ways n + 1 factors can be completely * parenthesized (e.g., for n = 2, C(n) = 2 and (ab)c and a(bc) * are the two valid ways to parenthesize. * - The number of full binary trees with n + 1 leaves * A Catalan number satisfies the following recurrence relation * which we will use in this algorithm [1]. * C(0) = C(1) = 1 * C(n) = sum(C(i).C(n-i-1)), from i = 0 to n-1 * In addition, the n-th Catalan number can be calculated using * the closed form formula below [1]: * C(n) = (1 / (n + 1)) * (2n choose n) * Sources: * [1] https://brilliant.org/wiki/catalan-numbers/ * [2] https://en.wikipedia.org/wiki/Catalan_number """ def catalan_numbers(upper_limit: int) -> "list[int]": """ Return a list of the Catalan number sequence from 0 through `upper_limit`. >>> catalan_numbers(5) [1, 1, 2, 5, 14, 42] >>> catalan_numbers(2) [1, 1, 2] >>> catalan_numbers(-1) Traceback (most recent call last): ValueError: Limit for the Catalan sequence must be ≥ 0 """ if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
__author__ = "Tobias Carryer" from time import time class LinearCongruentialGenerator: """ A pseudorandom number generator. """ # The default value for **seed** is the result of a function call which is not # normally recommended and causes flake8-bugbear to raise a B008 error. However, # in this case, it is accptable because `LinearCongruentialGenerator.__init__()` # will only be called once per instance and it ensures that each instance will # generate a unique sequence of numbers. def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B008 """ These parameters are saved and used when nextNumber() is called. modulo is the largest number that can be generated (exclusive). The most efficient values are powers of 2. 2^32 is a common value. """ self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed def next_number(self): """ The smallest number that can be generated is zero. The largest number that can be generated is modulo-1. modulo is set in the constructor. """ self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31) while True: print(lcg.next_number())
__author__ = "Tobias Carryer" from time import time class LinearCongruentialGenerator: """ A pseudorandom number generator. """ # The default value for **seed** is the result of a function call which is not # normally recommended and causes flake8-bugbear to raise a B008 error. However, # in this case, it is accptable because `LinearCongruentialGenerator.__init__()` # will only be called once per instance and it ensures that each instance will # generate a unique sequence of numbers. def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B008 """ These parameters are saved and used when nextNumber() is called. modulo is the largest number that can be generated (exclusive). The most efficient values are powers of 2. 2^32 is a common value. """ self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed def next_number(self): """ The smallest number that can be generated is zero. The largest number that can be generated is modulo-1. modulo is set in the constructor. """ self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31) while True: print(lcg.next_number())
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] 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 """ from collections import defaultdict from typing import DefaultDict def check_anagrams(first_str: str, second_str: str) -> bool: """ Two strings are anagrams if they are made up of the same letters but are 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 """ first_str = first_str.lower().strip() second_str = second_str.lower().strip() # Remove whitespace first_str = first_str.replace(" ", "") second_str = second_str.replace(" ", "") # Strings of different lengths are not anagrams if len(first_str) != len(second_str): return False # Default values for count should be 0 count: DefaultDict[str, int] = defaultdict(int) # For each character in input strings, # increment count in the corresponding for i in range(len(first_str)): count[first_str[i]] += 1 count[second_str[i]] -= 1 for _count in count.values(): if _count != 0: return False return True 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 """ from collections import defaultdict from typing import DefaultDict def check_anagrams(first_str: str, second_str: str) -> bool: """ Two strings are anagrams if they are made up of the same letters but are 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 """ first_str = first_str.lower().strip() second_str = second_str.lower().strip() # Remove whitespace first_str = first_str.replace(" ", "") second_str = second_str.replace(" ", "") # Strings of different lengths are not anagrams if len(first_str) != len(second_str): return False # Default values for count should be 0 count: DefaultDict[str, int] = defaultdict(int) # For each character in input strings, # increment count in the corresponding for i in range(len(first_str)): count[first_str[i]] += 1 count[second_str[i]] -= 1 for _count in count.values(): if _count != 0: return False return True 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
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence. """ from __future__ import annotations from typing import Any def generate_all_subsequences(sequence: list[Any]) -> None: create_state_space_tree(sequence, [], 0) def create_state_space_tree( sequence: list[Any], current_subsequence: list[Any], index: int ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() if __name__ == "__main__": seq: list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
""" In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence. """ from __future__ import annotations from typing import Any def generate_all_subsequences(sequence: list[Any]) -> None: create_state_space_tree(sequence, [], 0) def create_state_space_tree( sequence: list[Any], current_subsequence: list[Any], index: int ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() if __name__ == "__main__": seq: list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Algorithm for calculating the most cost-efficient sequence for converting one string into another. The only allowed operations are --- Cost to copy a character is copy_cost --- Cost to replace a character is replace_cost --- Cost to delete a character is delete_cost --- Cost to insert a character is insert_cost """ def compute_transform_tables( source_string: str, destination_string: str, copy_cost: int, replace_cost: int, delete_cost: int, insert_cost: int, ) -> tuple[list[list[int]], list[list[str]]]: source_seq = list(source_string) destination_seq = list(destination_string) len_source_seq = len(source_seq) len_destination_seq = len(destination_seq) costs = [ [0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] ops = [ ["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] for i in range(1, len_source_seq + 1): costs[i][0] = i * delete_cost ops[i][0] = "D%c" % source_seq[i - 1] for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = "I%c" % destination_seq[i - 1] for i in range(1, len_source_seq + 1): for j in range(1, len_destination_seq + 1): if source_seq[i - 1] == destination_seq[j - 1]: costs[i][j] = costs[i - 1][j - 1] + copy_cost ops[i][j] = "C%c" % source_seq[i - 1] else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1]) if costs[i - 1][j] + delete_cost < costs[i][j]: costs[i][j] = costs[i - 1][j] + delete_cost ops[i][j] = "D%c" % source_seq[i - 1] if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = "I%c" % destination_seq[j - 1] return costs, ops def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: if i == 0 and j == 0: return [] else: if ops[i][j][0] == "C" or ops[i][j][0] == "R": seq = assemble_transformation(ops, i - 1, j - 1) seq.append(ops[i][j]) return seq elif ops[i][j][0] == "D": seq = assemble_transformation(ops, i - 1, j) seq.append(ops[i][j]) return seq else: seq = assemble_transformation(ops, i, j - 1) seq.append(ops[i][j]) return seq if __name__ == "__main__": _, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2) m = len(operations) n = len(operations[0]) sequence = assemble_transformation(operations, m - 1, n - 1) string = list("Python") i = 0 cost = 0 with open("min_cost.txt", "w") as file: for op in sequence: print("".join(string)) if op[0] == "C": file.write("%-16s" % "Copy %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost -= 1 elif op[0] == "R": string[i] = op[2] file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) file.write("\t\t" + "".join(string)) file.write("\r\n") cost += 1 elif op[0] == "D": string.pop(i) file.write("%-16s" % "Delete %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 else: string.insert(i, op[1]) file.write("%-16s" % "Insert %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 i += 1 print("".join(string)) print("Cost: ", cost) file.write("\r\nMinimum cost: " + str(cost))
""" Algorithm for calculating the most cost-efficient sequence for converting one string into another. The only allowed operations are --- Cost to copy a character is copy_cost --- Cost to replace a character is replace_cost --- Cost to delete a character is delete_cost --- Cost to insert a character is insert_cost """ def compute_transform_tables( source_string: str, destination_string: str, copy_cost: int, replace_cost: int, delete_cost: int, insert_cost: int, ) -> tuple[list[list[int]], list[list[str]]]: source_seq = list(source_string) destination_seq = list(destination_string) len_source_seq = len(source_seq) len_destination_seq = len(destination_seq) costs = [ [0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] ops = [ ["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] for i in range(1, len_source_seq + 1): costs[i][0] = i * delete_cost ops[i][0] = "D%c" % source_seq[i - 1] for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = "I%c" % destination_seq[i - 1] for i in range(1, len_source_seq + 1): for j in range(1, len_destination_seq + 1): if source_seq[i - 1] == destination_seq[j - 1]: costs[i][j] = costs[i - 1][j - 1] + copy_cost ops[i][j] = "C%c" % source_seq[i - 1] else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1]) if costs[i - 1][j] + delete_cost < costs[i][j]: costs[i][j] = costs[i - 1][j] + delete_cost ops[i][j] = "D%c" % source_seq[i - 1] if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = "I%c" % destination_seq[j - 1] return costs, ops def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: if i == 0 and j == 0: return [] else: if ops[i][j][0] == "C" or ops[i][j][0] == "R": seq = assemble_transformation(ops, i - 1, j - 1) seq.append(ops[i][j]) return seq elif ops[i][j][0] == "D": seq = assemble_transformation(ops, i - 1, j) seq.append(ops[i][j]) return seq else: seq = assemble_transformation(ops, i, j - 1) seq.append(ops[i][j]) return seq if __name__ == "__main__": _, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2) m = len(operations) n = len(operations[0]) sequence = assemble_transformation(operations, m - 1, n - 1) string = list("Python") i = 0 cost = 0 with open("min_cost.txt", "w") as file: for op in sequence: print("".join(string)) if op[0] == "C": file.write("%-16s" % "Copy %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost -= 1 elif op[0] == "R": string[i] = op[2] file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) file.write("\t\t" + "".join(string)) file.write("\r\n") cost += 1 elif op[0] == "D": string.pop(i) file.write("%-16s" % "Delete %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 else: string.insert(i, op[1]) file.write("%-16s" % "Insert %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 i += 1 print("".join(string)) print("Cost: ", cost) file.write("\r\nMinimum cost: " + str(cost))
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def 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 __future__ import annotations 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
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh https://epaperpress.com/sortsearch/download/skiplist.pdf """ from __future__ import annotations from random import random from typing import Generic, TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class Node(Generic[KT, VT]): def __init__(self, key: KT | str = "root", value: VT | None = None): self.key = key self.value = value self.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: """ :return: Visual representation of Node >>> node = Node("Key", 2) >>> repr(node) 'Node(Key: 2)' """ return f"Node({self.key}: {self.value})" @property def level(self) -> int: """ :return: Number of forward references >>> node = Node("Key", 2) >>> node.level 0 >>> node.forward.append(Node("Key2", 4)) >>> node.level 1 >>> node.forward.append(Node("Key3", 6)) >>> node.level 2 """ return len(self.forward) class SkipList(Generic[KT, VT]): def __init__(self, p: float = 0.5, max_level: int = 16): self.head: Node[KT, VT] = Node[KT, VT]() self.level = 0 self.p = p self.max_level = max_level def __str__(self) -> str: """ :return: Visual representation of SkipList >>> skip_list = SkipList() >>> print(skip_list) SkipList(level=0) >>> skip_list.insert("Key1", "Value") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... None *... >>> skip_list.insert("Key2", "OtherValue") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... [Key2]--Key2... None *... """ items = list(self) if len(items) == 0: return f"SkipList(level={self.level})" label_size = max((len(str(item)) for item in items), default=4) label_size = max(label_size, 4) + 4 node = self.head lines = [] forwards = node.forward.copy() lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards)) lines.append(" " * label_size + "| " * len(forwards)) while len(node.forward) != 0: node = node.forward[0] lines.append( f"[{node.key}]".ljust(label_size, "-") + " ".join(str(n.key) if n.key == node.key else "|" for n in forwards) ) lines.append(" " * label_size + "| " * len(forwards)) forwards[: node.level] = node.forward lines.append("None".ljust(label_size) + "* " * len(forwards)) return f"SkipList(level={self.level})\n" + "\n".join(lines) def __iter__(self): node = self.head while len(node.forward) != 0: yield node.forward[0].key node = node.forward[0] def random_level(self) -> int: """ :return: Random level from [1, self.max_level] interval. Higher values are less likely. """ level = 1 while random() < self.p and level < self.max_level: level += 1 return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: """ :param key: Searched key, :return: Tuple with searched node (or None if given key is not present) and list of nodes that refer (if key is present) of should refer to given node. """ # Nodes with refer or should refer to output node update_vector = [] node = self.head for i in reversed(range(self.level)): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: node = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(node) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def delete(self, key: KT): """ :param key: Key to remove from list. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.insert(1, "One") >>> skip_list.insert(3, "Three") >>> list(skip_list) [1, 2, 3] >>> skip_list.delete(2) >>> list(skip_list) [1, 3] """ node, update_vector = self._locate_node(key) if node is not None: for i, update_node in enumerate(update_vector): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: update_node.forward[i] = node.forward[i] else: update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): """ :param key: Key to insert. :param value: Value associated with given key. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> list(skip_list) [2] """ node, update_vector = self._locate_node(key) if node is not None: node.value = value else: level = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for i in range(self.level - 1, level): update_vector.append(self.head) self.level = level new_node = Node(key, value) for i, update_node in enumerate(update_vector[:level]): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(new_node) else: update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: """ :param key: Search key. :return: Value associated with given key or None if given key is not present. >>> skip_list = SkipList() >>> skip_list.find(2) >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> skip_list.insert(2, "Three") >>> skip_list.find(2) 'Three' """ node, _ = self._locate_node(key) if node is not None: return node.value return None def test_insert(): skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) skip_list.insert("Key3", 41) skip_list.insert("Key4", -19) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value assert len(all_values) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def test_insert_overrides_existing_value(): skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) skip_list.insert("Key5", 7) skip_list.insert("Key7", 10) skip_list.insert("Key10", 5) skip_list.insert("Key7", 7) skip_list.insert("Key5", 5) skip_list.insert("Key10", 10) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value if len(all_values) != 4: print() assert len(all_values) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def test_searching_empty_list_returns_none(): skip_list = SkipList() assert skip_list.find("Some key") is None def test_search(): skip_list = SkipList() skip_list.insert("Key2", 20) assert skip_list.find("Key2") == 20 skip_list.insert("Some Key", 10) skip_list.insert("Key2", 8) skip_list.insert("V", 13) assert skip_list.find("Y") is None assert skip_list.find("Key2") == 8 assert skip_list.find("Some Key") == 10 assert skip_list.find("V") == 13 def test_deleting_item_from_empty_list_do_nothing(): skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 def test_deleted_items_are_not_founded_by_find_method(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("Key2") is None def test_delete_removes_only_given_key(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") assert skip_list.find("V") is None assert skip_list.find("X") == 14 assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("X") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("Key1") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") == 15 skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") is None def test_delete_doesnt_leave_dead_nodes(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 142) skip_list.insert("Key2", 15) skip_list.delete("X") def traverse_keys(node): yield node.key for forward_node in node.forward: yield from traverse_keys(forward_node) assert len(set(traverse_keys(skip_list.head))) == 4 def test_iter_always_yields_sorted_values(): def is_sorted(lst): for item, next_item in zip(lst, lst[1:]): if next_item < item: return False return True skip_list = SkipList() for i in range(10): skip_list.insert(i, i) assert is_sorted(list(skip_list)) skip_list.delete(5) skip_list.delete(8) skip_list.delete(2) assert is_sorted(list(skip_list)) skip_list.insert(-12, -12) skip_list.insert(77, 77) assert is_sorted(list(skip_list)) def pytests(): for i in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def main(): """ >>> pytests() """ skip_list = SkipList() skip_list.insert(2, "2") skip_list.insert(4, "4") skip_list.insert(6, "4") skip_list.insert(4, "5") skip_list.insert(8, "4") skip_list.insert(9, "4") skip_list.delete(4) print(skip_list) if __name__ == "__main__": main()
""" Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh https://epaperpress.com/sortsearch/download/skiplist.pdf """ from __future__ import annotations from random import random from typing import Generic, TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class Node(Generic[KT, VT]): def __init__(self, key: KT | str = "root", value: VT | None = None): self.key = key self.value = value self.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: """ :return: Visual representation of Node >>> node = Node("Key", 2) >>> repr(node) 'Node(Key: 2)' """ return f"Node({self.key}: {self.value})" @property def level(self) -> int: """ :return: Number of forward references >>> node = Node("Key", 2) >>> node.level 0 >>> node.forward.append(Node("Key2", 4)) >>> node.level 1 >>> node.forward.append(Node("Key3", 6)) >>> node.level 2 """ return len(self.forward) class SkipList(Generic[KT, VT]): def __init__(self, p: float = 0.5, max_level: int = 16): self.head: Node[KT, VT] = Node[KT, VT]() self.level = 0 self.p = p self.max_level = max_level def __str__(self) -> str: """ :return: Visual representation of SkipList >>> skip_list = SkipList() >>> print(skip_list) SkipList(level=0) >>> skip_list.insert("Key1", "Value") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... None *... >>> skip_list.insert("Key2", "OtherValue") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... [Key2]--Key2... None *... """ items = list(self) if len(items) == 0: return f"SkipList(level={self.level})" label_size = max((len(str(item)) for item in items), default=4) label_size = max(label_size, 4) + 4 node = self.head lines = [] forwards = node.forward.copy() lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards)) lines.append(" " * label_size + "| " * len(forwards)) while len(node.forward) != 0: node = node.forward[0] lines.append( f"[{node.key}]".ljust(label_size, "-") + " ".join(str(n.key) if n.key == node.key else "|" for n in forwards) ) lines.append(" " * label_size + "| " * len(forwards)) forwards[: node.level] = node.forward lines.append("None".ljust(label_size) + "* " * len(forwards)) return f"SkipList(level={self.level})\n" + "\n".join(lines) def __iter__(self): node = self.head while len(node.forward) != 0: yield node.forward[0].key node = node.forward[0] def random_level(self) -> int: """ :return: Random level from [1, self.max_level] interval. Higher values are less likely. """ level = 1 while random() < self.p and level < self.max_level: level += 1 return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: """ :param key: Searched key, :return: Tuple with searched node (or None if given key is not present) and list of nodes that refer (if key is present) of should refer to given node. """ # Nodes with refer or should refer to output node update_vector = [] node = self.head for i in reversed(range(self.level)): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: node = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(node) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def delete(self, key: KT): """ :param key: Key to remove from list. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.insert(1, "One") >>> skip_list.insert(3, "Three") >>> list(skip_list) [1, 2, 3] >>> skip_list.delete(2) >>> list(skip_list) [1, 3] """ node, update_vector = self._locate_node(key) if node is not None: for i, update_node in enumerate(update_vector): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: update_node.forward[i] = node.forward[i] else: update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): """ :param key: Key to insert. :param value: Value associated with given key. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> list(skip_list) [2] """ node, update_vector = self._locate_node(key) if node is not None: node.value = value else: level = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for i in range(self.level - 1, level): update_vector.append(self.head) self.level = level new_node = Node(key, value) for i, update_node in enumerate(update_vector[:level]): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(new_node) else: update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: """ :param key: Search key. :return: Value associated with given key or None if given key is not present. >>> skip_list = SkipList() >>> skip_list.find(2) >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> skip_list.insert(2, "Three") >>> skip_list.find(2) 'Three' """ node, _ = self._locate_node(key) if node is not None: return node.value return None def test_insert(): skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) skip_list.insert("Key3", 41) skip_list.insert("Key4", -19) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value assert len(all_values) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def test_insert_overrides_existing_value(): skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) skip_list.insert("Key5", 7) skip_list.insert("Key7", 10) skip_list.insert("Key10", 5) skip_list.insert("Key7", 7) skip_list.insert("Key5", 5) skip_list.insert("Key10", 10) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value if len(all_values) != 4: print() assert len(all_values) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def test_searching_empty_list_returns_none(): skip_list = SkipList() assert skip_list.find("Some key") is None def test_search(): skip_list = SkipList() skip_list.insert("Key2", 20) assert skip_list.find("Key2") == 20 skip_list.insert("Some Key", 10) skip_list.insert("Key2", 8) skip_list.insert("V", 13) assert skip_list.find("Y") is None assert skip_list.find("Key2") == 8 assert skip_list.find("Some Key") == 10 assert skip_list.find("V") == 13 def test_deleting_item_from_empty_list_do_nothing(): skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 def test_deleted_items_are_not_founded_by_find_method(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("Key2") is None def test_delete_removes_only_given_key(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") assert skip_list.find("V") is None assert skip_list.find("X") == 14 assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("X") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("Key1") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") == 15 skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") is None def test_delete_doesnt_leave_dead_nodes(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 142) skip_list.insert("Key2", 15) skip_list.delete("X") def traverse_keys(node): yield node.key for forward_node in node.forward: yield from traverse_keys(forward_node) assert len(set(traverse_keys(skip_list.head))) == 4 def test_iter_always_yields_sorted_values(): def is_sorted(lst): for item, next_item in zip(lst, lst[1:]): if next_item < item: return False return True skip_list = SkipList() for i in range(10): skip_list.insert(i, i) assert is_sorted(list(skip_list)) skip_list.delete(5) skip_list.delete(8) skip_list.delete(2) assert is_sorted(list(skip_list)) skip_list.insert(-12, -12) skip_list.insert(77, 77) assert is_sorted(list(skip_list)) def pytests(): for i in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def main(): """ >>> pytests() """ skip_list = SkipList() skip_list.insert(2, "2") skip_list.insert(4, "4") skip_list.insert(6, "4") skip_list.insert(4, "5") skip_list.insert(8, "4") skip_list.insert(9, "4") skip_list.delete(4) print(skip_list) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
def perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ import math def isprime(num: int) -> bool: """ Returns boolean representing primality of given number num. >>> isprime(2) True >>> isprime(3) True >>> isprime(27) False >>> isprime(2999) True >>> isprime(0) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. >>> isprime(1) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. """ if num <= 1: raise ValueError("Parameter num must be greater than or equal to two.") if num == 2: return True elif num % 2 == 0: return False for i in range(3, int(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") max_number = 0 if isprime(n): return n while n % 2 == 0: n //= 2 if isprime(n): return n for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: if isprime(n // i): max_number = n // i break elif isprime(i): max_number = i return max_number if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ import math def isprime(num: int) -> bool: """ Returns boolean representing primality of given number num. >>> isprime(2) True >>> isprime(3) True >>> isprime(27) False >>> isprime(2999) True >>> isprime(0) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. >>> isprime(1) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. """ if num <= 1: raise ValueError("Parameter num must be greater than or equal to two.") if num == 2: return True elif num % 2 == 0: return False for i in range(3, int(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") max_number = 0 if isprime(n): return n while n % 2 == 0: n //= 2 if isprime(n): return n for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: if isprime(n // i): max_number = n // i break elif isprime(i): max_number = i return max_number if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: """ True, if the point lies in the unit circle False, otherwise """ return (self.x ** 2 + self.y ** 2) <= 1 @classmethod def random_unit_square(cls): """ Generates a point randomly drawn from the unit square [0, 1) x [0, 1). """ return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: """ Generates an estimate of the mathematical constant PI. See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: P[U in unit circle] = 1/4 PI and therefore PI = 4 * P[U in unit circle] We can get an estimate of the probability P[U in unit circle]. See https://en.wikipedia.org/wiki/Empirical_probability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of P[U in unit circle] is m/n """ if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for simulation_index in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": # import doctest # doctest.testmod() from math import pi prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: """ True, if the point lies in the unit circle False, otherwise """ return (self.x ** 2 + self.y ** 2) <= 1 @classmethod def random_unit_square(cls): """ Generates a point randomly drawn from the unit square [0, 1) x [0, 1). """ return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: """ Generates an estimate of the mathematical constant PI. See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: P[U in unit circle] = 1/4 PI and therefore PI = 4 * P[U in unit circle] We can get an estimate of the probability P[U in unit circle]. See https://en.wikipedia.org/wiki/Empirical_probability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of P[U in unit circle] is m/n """ if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for simulation_index in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": # import doctest # doctest.testmod() from math import pi prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Bidirectional_search """ from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean HEURISTIC = 0 grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right TPosition = tuple[int, int] class Node: """ >>> k = Node(0, 0, 4, 3, 0, None) >>> k.calculate_heuristic() 5.0 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2.0 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, g_cost: int, parent: Node | None, ) -> None: self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.g_cost = g_cost self.parent = parent self.h_cost = self.calculate_heuristic() self.f_cost = self.g_cost + self.h_cost def calculate_heuristic(self) -> float: """ Heuristic for the A* """ dy = self.pos_x - self.goal_x dx = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(dx) + abs(dy) else: return sqrt(dy ** 2 + dx ** 2) def __lt__(self, other: Node) -> bool: return self.f_cost < other.f_cost class AStar: """ >>> astar = AStar((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> (astar.start.pos_y + delta[3][0], astar.start.pos_x + delta[3][1]) (0, 1) >>> [x.pos for x in astar.get_successors(astar.start)] [(1, 0), (0, 1)] >>> (astar.start.pos_y + delta[2][0], astar.start.pos_x + delta[2][1]) (1, 0) >>> astar.retrace_path(astar.start) [(0, 0)] >>> astar.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4), (5, 4), (5, 5), (6, 5), (6, 6)] """ def __init__(self, start: TPosition, goal: TPosition): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False def search(self) -> list[TPosition]: while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) return [self.start.pos] def get_successors(self, parent: Node) -> list[Node]: """ Returns a list of successors (both in the grid and free spaces) """ successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors def retrace_path(self, node: Node | None) -> list[TPosition]: """ Retrace the path from parents to parents until start node """ current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path class BidirectionalAStar: """ >>> bd_astar = BidirectionalAStar((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> bd_astar.fwd_astar.start.pos == bd_astar.bwd_astar.target.pos True >>> bd_astar.retrace_bidirectional_path(bd_astar.fwd_astar.start, ... bd_astar.bwd_astar.start) [(0, 0)] >>> bd_astar.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (2, 4), (2, 5), (3, 5), (4, 5), (5, 5), (5, 6), (6, 6)] """ def __init__(self, start: TPosition, goal: TPosition) -> None: self.fwd_astar = AStar(start, goal) self.bwd_astar = AStar(goal, start) self.reached = False def search(self) -> list[TPosition]: while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() current_fwd_node = self.fwd_astar.open_nodes.pop(0) current_bwd_node = self.bwd_astar.open_nodes.pop(0) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( current_fwd_node, current_bwd_node ) self.fwd_astar.closed_nodes.append(current_fwd_node) self.bwd_astar.closed_nodes.append(current_bwd_node) self.fwd_astar.target = current_bwd_node self.bwd_astar.target = current_fwd_node successors = { self.fwd_astar: self.fwd_astar.get_successors(current_fwd_node), self.bwd_astar: self.bwd_astar.get_successors(current_bwd_node), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(child_node) else: # retrieve the best current path better_node = astar.open_nodes.pop( astar.open_nodes.index(child_node) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(child_node) else: astar.open_nodes.append(better_node) return [self.fwd_astar.start.pos] def retrace_bidirectional_path( self, fwd_node: Node, bwd_node: Node ) -> list[TPosition]: fwd_path = self.fwd_astar.retrace_path(fwd_node) bwd_path = self.bwd_astar.retrace_path(bwd_node) bwd_path.pop() bwd_path.reverse() path = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] init = (0, 0) goal = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) start_time = time.time() a_star = AStar(init, goal) path = a_star.search() end_time = time.time() - start_time print(f"AStar execution time = {end_time:f} seconds") bd_start_time = time.time() bidir_astar = BidirectionalAStar(init, goal) bd_end_time = time.time() - bd_start_time print(f"BidirectionalAStar execution time = {bd_end_time:f} seconds")
""" https://en.wikipedia.org/wiki/Bidirectional_search """ from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean HEURISTIC = 0 grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right TPosition = tuple[int, int] class Node: """ >>> k = Node(0, 0, 4, 3, 0, None) >>> k.calculate_heuristic() 5.0 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2.0 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, g_cost: int, parent: Node | None, ) -> None: self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.g_cost = g_cost self.parent = parent self.h_cost = self.calculate_heuristic() self.f_cost = self.g_cost + self.h_cost def calculate_heuristic(self) -> float: """ Heuristic for the A* """ dy = self.pos_x - self.goal_x dx = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(dx) + abs(dy) else: return sqrt(dy ** 2 + dx ** 2) def __lt__(self, other: Node) -> bool: return self.f_cost < other.f_cost class AStar: """ >>> astar = AStar((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> (astar.start.pos_y + delta[3][0], astar.start.pos_x + delta[3][1]) (0, 1) >>> [x.pos for x in astar.get_successors(astar.start)] [(1, 0), (0, 1)] >>> (astar.start.pos_y + delta[2][0], astar.start.pos_x + delta[2][1]) (1, 0) >>> astar.retrace_path(astar.start) [(0, 0)] >>> astar.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (3, 3), (4, 3), (4, 4), (5, 4), (5, 5), (6, 5), (6, 6)] """ def __init__(self, start: TPosition, goal: TPosition): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False def search(self) -> list[TPosition]: while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) return [self.start.pos] def get_successors(self, parent: Node) -> list[Node]: """ Returns a list of successors (both in the grid and free spaces) """ successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors def retrace_path(self, node: Node | None) -> list[TPosition]: """ Retrace the path from parents to parents until start node """ current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path class BidirectionalAStar: """ >>> bd_astar = BidirectionalAStar((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> bd_astar.fwd_astar.start.pos == bd_astar.bwd_astar.target.pos True >>> bd_astar.retrace_bidirectional_path(bd_astar.fwd_astar.start, ... bd_astar.bwd_astar.start) [(0, 0)] >>> bd_astar.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (2, 4), (2, 5), (3, 5), (4, 5), (5, 5), (5, 6), (6, 6)] """ def __init__(self, start: TPosition, goal: TPosition) -> None: self.fwd_astar = AStar(start, goal) self.bwd_astar = AStar(goal, start) self.reached = False def search(self) -> list[TPosition]: while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() current_fwd_node = self.fwd_astar.open_nodes.pop(0) current_bwd_node = self.bwd_astar.open_nodes.pop(0) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( current_fwd_node, current_bwd_node ) self.fwd_astar.closed_nodes.append(current_fwd_node) self.bwd_astar.closed_nodes.append(current_bwd_node) self.fwd_astar.target = current_bwd_node self.bwd_astar.target = current_fwd_node successors = { self.fwd_astar: self.fwd_astar.get_successors(current_fwd_node), self.bwd_astar: self.bwd_astar.get_successors(current_bwd_node), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(child_node) else: # retrieve the best current path better_node = astar.open_nodes.pop( astar.open_nodes.index(child_node) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(child_node) else: astar.open_nodes.append(better_node) return [self.fwd_astar.start.pos] def retrace_bidirectional_path( self, fwd_node: Node, bwd_node: Node ) -> list[TPosition]: fwd_path = self.fwd_astar.retrace_path(fwd_node) bwd_path = self.bwd_astar.retrace_path(bwd_node) bwd_path.pop() bwd_path.reverse() path = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] init = (0, 0) goal = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) start_time = time.time() a_star = AStar(init, goal) path = a_star.search() end_time = time.time() - start_time print(f"AStar execution time = {end_time:f} seconds") bd_start_time = time.time() bidir_astar = BidirectionalAStar(init, goal) bd_end_time = time.time() - bd_start_time print(f"BidirectionalAStar execution time = {bd_end_time:f} seconds")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ Returns True if the pandigital number passes all the divisibility tests. >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) False >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) False >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) True """ if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False tests = [7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def solution(n: int = 10) -> int: """ Returns the sum of all pandigital numbers which pass the divisibility tests. >>> solution(10) 16695334890 """ return sum( int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ) if __name__ == "__main__": print(f"{solution() = }")
""" Problem 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ Returns True if the pandigital number passes all the divisibility tests. >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) False >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) False >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) True """ if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False tests = [7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def solution(n: int = 10) -> int: """ Returns the sum of all pandigital numbers which pass the divisibility tests. >>> solution(10) 16695334890 """ return sum( int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex. """ from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar T = TypeVar("T") def get_parent_position(position: int) -> int: """ heap helper function get the position of the parent of the current node >>> get_parent_position(1) 0 >>> get_parent_position(2) 0 """ return (position - 1) // 2 def get_child_left_position(position: int) -> int: """ heap helper function get the position of the left child of the current node >>> get_child_left_position(0) 1 """ return (2 * position) + 1 def get_child_right_position(position: int) -> int: """ heap helper function get the position of the right child of the current node >>> get_child_right_position(0) 2 """ return (2 * position) + 2 class MinPriorityQueue(Generic[T]): """ Minimum Priority Queue Class Functions: is_empty: function to check if the priority queue is empty push: function to add an element with given priority to the queue extract_min: function to remove and return the element with lowest weight (highest priority) update_key: function to update the weight of the given key _bubble_up: helper function to place a node at the proper position (upward movement) _bubble_down: helper function to place a node at the proper position (downward movement) _swap_nodes: helper function to swap the nodes at the given positions >>> queue = MinPriorityQueue() >>> queue.push(1, 1000) >>> queue.push(2, 100) >>> queue.push(3, 4000) >>> queue.push(4, 3000) >>> print(queue.extract_min()) 2 >>> queue.update_key(4, 50) >>> print(queue.extract_min()) 4 >>> print(queue.extract_min()) 1 >>> print(queue.extract_min()) 3 """ def __init__(self) -> None: self.heap: list[tuple[T, int]] = [] self.position_map: dict[T, int] = {} self.elements: int = 0 def __len__(self) -> int: return self.elements def __repr__(self) -> str: return str(self.heap) def is_empty(self) -> bool: # Check if the priority queue is empty return self.elements == 0 def push(self, elem: T, weight: int) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight)) self.position_map[elem] = self.elements self.elements += 1 self._bubble_up(elem) def extract_min(self) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0, self.elements - 1) elem, _ = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: bubble_down_elem, _ = self.heap[0] self._bubble_down(bubble_down_elem) return elem def update_key(self, elem: T, weight: int) -> None: # Update the weight of the given key position = self.position_map[elem] self.heap[position] = (elem, weight) if position > 0: parent_position = get_parent_position(position) _, parent_weight = self.heap[parent_position] if parent_weight > weight: self._bubble_up(elem) else: self._bubble_down(elem) else: self._bubble_down(elem) def _bubble_up(self, elem: T) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] curr_pos = self.position_map[elem] if curr_pos == 0: return parent_position = get_parent_position(curr_pos) _, weight = self.heap[curr_pos] _, parent_weight = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(parent_position, curr_pos) return self._bubble_up(elem) return def _bubble_down(self, elem: T) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] curr_pos = self.position_map[elem] _, weight = self.heap[curr_pos] child_left_position = get_child_left_position(curr_pos) child_right_position = get_child_right_position(curr_pos) if child_left_position < self.elements and child_right_position < self.elements: _, child_left_weight = self.heap[child_left_position] _, child_right_weight = self.heap[child_right_position] if child_right_weight < child_left_weight: if child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem) if child_left_position < self.elements: _, child_left_weight = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(child_left_position, curr_pos) return self._bubble_down(elem) else: return if child_right_position < self.elements: _, child_right_weight = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem) else: return def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None: # Swap the nodes at the given positions node1_elem = self.heap[node1_pos][0] node2_elem = self.heap[node2_pos][0] self.heap[node1_pos], self.heap[node2_pos] = ( self.heap[node2_pos], self.heap[node1_pos], ) self.position_map[node1_elem] = node2_pos self.position_map[node2_elem] = node1_pos class GraphUndirectedWeighted(Generic[T]): """ Graph Undirected Weighted Class Functions: add_node: function to add a node in the graph add_edge: function to add an edge between 2 nodes in the graph """ def __init__(self) -> None: self.connections: dict[T, dict[T, int]] = {} self.nodes: int = 0 def __repr__(self) -> str: return str(self.connections) def __len__(self) -> int: return self.nodes def add_node(self, node: T) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: self.connections[node] = {} self.nodes += 1 def add_edge(self, node1: T, node2: T, weight: int) -> None: # Add an edge between 2 nodes in the graph self.add_node(node1) self.add_node(node2) self.connections[node1][node2] = weight self.connections[node2][node1] = weight def prims_algo( graph: GraphUndirectedWeighted[T], ) -> tuple[dict[T, int], dict[T, T | None]]: """ >>> graph = GraphUndirectedWeighted() >>> graph.add_edge("a", "b", 3) >>> graph.add_edge("b", "c", 10) >>> graph.add_edge("c", "d", 5) >>> graph.add_edge("a", "c", 15) >>> graph.add_edge("b", "d", 100) >>> dist, parent = prims_algo(graph) >>> abs(dist["a"] - dist["b"]) 3 >>> abs(dist["d"] - dist["b"]) 15 >>> abs(dist["a"] - dist["c"]) 13 """ # prim's algorithm for minimum spanning tree dist: dict[T, int] = {node: maxsize for node in graph.connections} parent: dict[T, T | None] = {node: None for node in graph.connections} priority_queue: MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(node, weight) if priority_queue.is_empty(): return dist, parent # initialization node = priority_queue.extract_min() dist[node] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: dist[neighbour] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(neighbour, dist[neighbour]) parent[neighbour] = node # running prim's algorithm while not priority_queue.is_empty(): node = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: dist[neighbour] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(neighbour, dist[neighbour]) parent[neighbour] = node return dist, parent
""" Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex. """ from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar T = TypeVar("T") def get_parent_position(position: int) -> int: """ heap helper function get the position of the parent of the current node >>> get_parent_position(1) 0 >>> get_parent_position(2) 0 """ return (position - 1) // 2 def get_child_left_position(position: int) -> int: """ heap helper function get the position of the left child of the current node >>> get_child_left_position(0) 1 """ return (2 * position) + 1 def get_child_right_position(position: int) -> int: """ heap helper function get the position of the right child of the current node >>> get_child_right_position(0) 2 """ return (2 * position) + 2 class MinPriorityQueue(Generic[T]): """ Minimum Priority Queue Class Functions: is_empty: function to check if the priority queue is empty push: function to add an element with given priority to the queue extract_min: function to remove and return the element with lowest weight (highest priority) update_key: function to update the weight of the given key _bubble_up: helper function to place a node at the proper position (upward movement) _bubble_down: helper function to place a node at the proper position (downward movement) _swap_nodes: helper function to swap the nodes at the given positions >>> queue = MinPriorityQueue() >>> queue.push(1, 1000) >>> queue.push(2, 100) >>> queue.push(3, 4000) >>> queue.push(4, 3000) >>> print(queue.extract_min()) 2 >>> queue.update_key(4, 50) >>> print(queue.extract_min()) 4 >>> print(queue.extract_min()) 1 >>> print(queue.extract_min()) 3 """ def __init__(self) -> None: self.heap: list[tuple[T, int]] = [] self.position_map: dict[T, int] = {} self.elements: int = 0 def __len__(self) -> int: return self.elements def __repr__(self) -> str: return str(self.heap) def is_empty(self) -> bool: # Check if the priority queue is empty return self.elements == 0 def push(self, elem: T, weight: int) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight)) self.position_map[elem] = self.elements self.elements += 1 self._bubble_up(elem) def extract_min(self) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0, self.elements - 1) elem, _ = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: bubble_down_elem, _ = self.heap[0] self._bubble_down(bubble_down_elem) return elem def update_key(self, elem: T, weight: int) -> None: # Update the weight of the given key position = self.position_map[elem] self.heap[position] = (elem, weight) if position > 0: parent_position = get_parent_position(position) _, parent_weight = self.heap[parent_position] if parent_weight > weight: self._bubble_up(elem) else: self._bubble_down(elem) else: self._bubble_down(elem) def _bubble_up(self, elem: T) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] curr_pos = self.position_map[elem] if curr_pos == 0: return parent_position = get_parent_position(curr_pos) _, weight = self.heap[curr_pos] _, parent_weight = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(parent_position, curr_pos) return self._bubble_up(elem) return def _bubble_down(self, elem: T) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] curr_pos = self.position_map[elem] _, weight = self.heap[curr_pos] child_left_position = get_child_left_position(curr_pos) child_right_position = get_child_right_position(curr_pos) if child_left_position < self.elements and child_right_position < self.elements: _, child_left_weight = self.heap[child_left_position] _, child_right_weight = self.heap[child_right_position] if child_right_weight < child_left_weight: if child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem) if child_left_position < self.elements: _, child_left_weight = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(child_left_position, curr_pos) return self._bubble_down(elem) else: return if child_right_position < self.elements: _, child_right_weight = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(child_right_position, curr_pos) return self._bubble_down(elem) else: return def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None: # Swap the nodes at the given positions node1_elem = self.heap[node1_pos][0] node2_elem = self.heap[node2_pos][0] self.heap[node1_pos], self.heap[node2_pos] = ( self.heap[node2_pos], self.heap[node1_pos], ) self.position_map[node1_elem] = node2_pos self.position_map[node2_elem] = node1_pos class GraphUndirectedWeighted(Generic[T]): """ Graph Undirected Weighted Class Functions: add_node: function to add a node in the graph add_edge: function to add an edge between 2 nodes in the graph """ def __init__(self) -> None: self.connections: dict[T, dict[T, int]] = {} self.nodes: int = 0 def __repr__(self) -> str: return str(self.connections) def __len__(self) -> int: return self.nodes def add_node(self, node: T) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: self.connections[node] = {} self.nodes += 1 def add_edge(self, node1: T, node2: T, weight: int) -> None: # Add an edge between 2 nodes in the graph self.add_node(node1) self.add_node(node2) self.connections[node1][node2] = weight self.connections[node2][node1] = weight def prims_algo( graph: GraphUndirectedWeighted[T], ) -> tuple[dict[T, int], dict[T, T | None]]: """ >>> graph = GraphUndirectedWeighted() >>> graph.add_edge("a", "b", 3) >>> graph.add_edge("b", "c", 10) >>> graph.add_edge("c", "d", 5) >>> graph.add_edge("a", "c", 15) >>> graph.add_edge("b", "d", 100) >>> dist, parent = prims_algo(graph) >>> abs(dist["a"] - dist["b"]) 3 >>> abs(dist["d"] - dist["b"]) 15 >>> abs(dist["a"] - dist["c"]) 13 """ # prim's algorithm for minimum spanning tree dist: dict[T, int] = {node: maxsize for node in graph.connections} parent: dict[T, T | None] = {node: None for node in graph.connections} priority_queue: MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(node, weight) if priority_queue.is_empty(): return dist, parent # initialization node = priority_queue.extract_min() dist[node] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: dist[neighbour] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(neighbour, dist[neighbour]) parent[neighbour] = node # running prim's algorithm while not priority_queue.is_empty(): node = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: dist[neighbour] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(neighbour, dist[neighbour]) parent[neighbour] = node return dist, parent
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 56: https://projecteuler.net/problem=56 A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum? """ def solution(a: int = 100, b: int = 100) -> int: """ Considering natural numbers of the form, a**b, where a, b < 100, what is the maximum digital sum? :param a: :param b: :return: >>> solution(10,10) 45 >>> solution(100,100) 972 >>> solution(100,200) 1872 """ # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of # BASE raised to the POWER return max( sum(int(x) for x in str(base ** power)) for base in range(a) for power in range(b) ) # Tests if __name__ == "__main__": import doctest doctest.testmod()
""" Project Euler Problem 56: https://projecteuler.net/problem=56 A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum? """ def solution(a: int = 100, b: int = 100) -> int: """ Considering natural numbers of the form, a**b, where a, b < 100, what is the maximum digital sum? :param a: :param b: :return: >>> solution(10,10) 45 >>> solution(100,100) 972 >>> solution(100,200) 1872 """ # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of # BASE raised to the POWER return max( sum(int(x) for x in str(base ** power)) for base in range(a) for power in range(b) ) # Tests if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Strongly_connected_component Finding strongly connected components in directed graph """ test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def topology_sort( graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to sort graph At this time graph is the same as input >>> topology_sort(test_graph_1, 0, 5 * [False]) [1, 2, 4, 3, 0] >>> topology_sort(test_graph_2, 0, 6 * [False]) [2, 1, 5, 4, 3, 0] """ visited[vert] = True order = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(graph, neighbour, visited) order.append(vert) return order def find_components( reversed_graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to find strongliy connected vertices. Now graph is reversed >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False]) [0, 1, 2] >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False]) [0, 2, 1] """ visited[vert] = True component = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(reversed_graph, neighbour, visited) return component def strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]: """ This function takes graph as a parameter and then returns the list of strongly connected components >>> strongly_connected_components(test_graph_1) [[0, 1, 2], [3], [4]] >>> strongly_connected_components(test_graph_2) [[0, 2, 1], [3, 5, 4]] """ visited = len(graph) * [False] reversed_graph: dict[int, list[int]] = {vert: [] for vert in range(len(graph))} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(vert) order = [] for i, was_visited in enumerate(visited): if not was_visited: order += topology_sort(graph, i, visited) components_list = [] visited = len(graph) * [False] for i in range(len(graph)): vert = order[len(graph) - i - 1] if not visited[vert]: component = find_components(reversed_graph, vert, visited) components_list.append(component) return components_list
""" https://en.wikipedia.org/wiki/Strongly_connected_component Finding strongly connected components in directed graph """ test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def topology_sort( graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to sort graph At this time graph is the same as input >>> topology_sort(test_graph_1, 0, 5 * [False]) [1, 2, 4, 3, 0] >>> topology_sort(test_graph_2, 0, 6 * [False]) [2, 1, 5, 4, 3, 0] """ visited[vert] = True order = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(graph, neighbour, visited) order.append(vert) return order def find_components( reversed_graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to find strongliy connected vertices. Now graph is reversed >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False]) [0, 1, 2] >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False]) [0, 2, 1] """ visited[vert] = True component = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(reversed_graph, neighbour, visited) return component def strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]: """ This function takes graph as a parameter and then returns the list of strongly connected components >>> strongly_connected_components(test_graph_1) [[0, 1, 2], [3], [4]] >>> strongly_connected_components(test_graph_2) [[0, 2, 1], [3, 5, 4]] """ visited = len(graph) * [False] reversed_graph: dict[int, list[int]] = {vert: [] for vert in range(len(graph))} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(vert) order = [] for i, was_visited in enumerate(visited): if not was_visited: order += topology_sort(graph, i, visited) components_list = [] visited = len(graph) * [False] for i in range(len(graph)): vert = order[len(graph) - i - 1] if not visited[vert]: component = find_components(reversed_graph, vert, visited) components_list.append(component) return components_list
-1
TheAlgorithms/Python
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] 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
5,829
Replace typing.optional with new annotations syntax
### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2021-11-16T21:49:37Z"
"2021-11-17T03:43:02Z"
d848bfbf3229f2a3240a298a583f6b80a9efc1fd
1ae5abfc3ca5dcf89b7e378735ceb9ef41769cbf
Replace typing.optional with new annotations syntax. ### Describe your change: https://www.python.org/dev/peps/pep-0563/ * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
END = "#" class Trie: def __init__(self): self._trie = {} def insert_word(self, text): trie = self._trie for char in text: if char not in trie: trie[char] = {} trie = trie[char] trie[END] = True def find_word(self, prefix): trie = self._trie for char in prefix: if char in trie: trie = trie[char] else: return [] return self._elements(trie) def _elements(self, d): result = [] for c, v in d.items(): if c == END: sub_result = [" "] else: sub_result = [c + s for s in self._elements(v)] result.extend(sub_result) return tuple(result) trie = Trie() words = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def autocomplete_using_trie(s): """ >>> trie = Trie() >>> for word in words: ... trie.insert_word(word) ... >>> matches = autocomplete_using_trie("de") "detergent " in matches True "dog " in matches False """ suffixes = trie.find_word(s) return tuple(s + w for w in suffixes) def main(): print(autocomplete_using_trie("de")) if __name__ == "__main__": main()
from __future__ import annotations END = "#" class Trie: def __init__(self) -> None: self._trie: dict = {} def insert_word(self, text: str) -> None: trie = self._trie for char in text: if char not in trie: trie[char] = {} trie = trie[char] trie[END] = True def find_word(self, prefix: str) -> tuple | list: trie = self._trie for char in prefix: if char in trie: trie = trie[char] else: return [] return self._elements(trie) def _elements(self, d: dict) -> tuple: result = [] for c, v in d.items(): if c == END: sub_result = [" "] else: sub_result = [c + s for s in self._elements(v)] result.extend(sub_result) return tuple(result) trie = Trie() words = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def autocomplete_using_trie(string: str) -> tuple: """ >>> trie = Trie() >>> for word in words: ... trie.insert_word(word) ... >>> matches = autocomplete_using_trie("de") >>> "detergent " in matches True >>> "dog " in matches False """ suffixes = trie.find_word(string) return tuple(string + word for word in suffixes) def main() -> None: print(autocomplete_using_trie("de")) if __name__ == "__main__": import doctest doctest.testmod() main()
1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 load_dictionary() -> dict[str, None]: path = os.path.split(os.path.realpath(__file__)) english_words: dict[str, None] = {} with open(path[0] + "/dictionary.txt") as dictionary_file: for word in dictionary_file.read().split("\n"): english_words[word] = None return english_words ENGLISH_WORDS = load_dictionary() def get_english_count(message: str) -> float: message = message.upper() message = remove_non_letters(message) possible_words = message.split() if possible_words == []: return 0.0 matches = 0 for word in possible_words: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(possible_words) def remove_non_letters(message: str) -> str: letters_only = [] for symbol in message: if symbol in LETTERS_AND_SPACE: letters_only.append(symbol) return "".join(letters_only) def is_english( message: str, word_percentage: int = 20, letter_percentage: int = 85 ) -> bool: """ >>> is_english('Hello World') True >>> is_english('llold HorWd') False """ words_match = get_english_count(message) * 100 >= word_percentage num_letters = len(remove_non_letters(message)) message_letters_percentage = (float(num_letters) / len(message)) * 100 letters_match = message_letters_percentage >= letter_percentage return words_match and letters_match if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Frequency Finder # frequency taken from http://en.wikipedia.org/wiki/Letter_frequency englishLetterFreq = { "E": 12.70, "T": 9.06, "A": 8.17, "O": 7.51, "I": 6.97, "N": 6.75, "S": 6.33, "H": 6.09, "R": 5.99, "D": 4.25, "L": 4.03, "C": 2.78, "U": 2.76, "M": 2.41, "W": 2.36, "F": 2.23, "G": 2.02, "Y": 1.97, "P": 1.93, "B": 1.29, "V": 0.98, "K": 0.77, "J": 0.15, "X": 0.15, "Q": 0.10, "Z": 0.07, } ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ" LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def getLetterCount(message): letterCount = { "A": 0, "B": 0, "C": 0, "D": 0, "E": 0, "F": 0, "G": 0, "H": 0, "I": 0, "J": 0, "K": 0, "L": 0, "M": 0, "N": 0, "O": 0, "P": 0, "Q": 0, "R": 0, "S": 0, "T": 0, "U": 0, "V": 0, "W": 0, "X": 0, "Y": 0, "Z": 0, } for letter in message.upper(): if letter in LETTERS: letterCount[letter] += 1 return letterCount def getItemAtIndexZero(x): return x[0] def getFrequencyOrder(message): letterToFreq = getLetterCount(message) freqToLetter = {} for letter in LETTERS: if letterToFreq[letter] not in freqToLetter: freqToLetter[letterToFreq[letter]] = [letter] else: freqToLetter[letterToFreq[letter]].append(letter) for freq in freqToLetter: freqToLetter[freq].sort(key=ETAOIN.find, reverse=True) freqToLetter[freq] = "".join(freqToLetter[freq]) freqPairs = list(freqToLetter.items()) freqPairs.sort(key=getItemAtIndexZero, reverse=True) freqOrder = [] for freqPair in freqPairs: freqOrder.append(freqPair[1]) return "".join(freqOrder) def englishFreqMatchScore(message): """ >>> englishFreqMatchScore('Hello World') 1 """ freqOrder = getFrequencyOrder(message) matchScore = 0 for commonLetter in ETAOIN[:6]: if commonLetter in freqOrder[:6]: matchScore += 1 for uncommonLetter in ETAOIN[-6:]: if uncommonLetter in freqOrder[-6:]: matchScore += 1 return matchScore if __name__ == "__main__": import doctest doctest.testmod()
# Frequency Finder import string # frequency taken from http://en.wikipedia.org/wiki/Letter_frequency english_letter_freq = { "E": 12.70, "T": 9.06, "A": 8.17, "O": 7.51, "I": 6.97, "N": 6.75, "S": 6.33, "H": 6.09, "R": 5.99, "D": 4.25, "L": 4.03, "C": 2.78, "U": 2.76, "M": 2.41, "W": 2.36, "F": 2.23, "G": 2.02, "Y": 1.97, "P": 1.93, "B": 1.29, "V": 0.98, "K": 0.77, "J": 0.15, "X": 0.15, "Q": 0.10, "Z": 0.07, } ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ" LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def get_letter_count(message: str) -> dict[str, int]: letter_count = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def get_item_at_index_zero(x: tuple) -> str: return x[0] def get_frequency_order(message: str) -> str: letter_to_freq = get_letter_count(message) freq_to_letter: dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(letter) freq_to_letter_str: dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find, reverse=True) freq_to_letter_str[freq] = "".join(freq_to_letter[freq]) freq_pairs = list(freq_to_letter_str.items()) freq_pairs.sort(key=get_item_at_index_zero, reverse=True) freq_order: list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(freq_order) def english_freq_match_score(message: str) -> int: """ >>> english_freq_match_score('Hello World') 1 """ freq_order = get_frequency_order(message) match_score = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Created by sarathkaul on 17/11/19 # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 from collections import defaultdict def word_occurence(sentence: str) -> dict: """ >>> from collections import Counter >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" >>> occurence_dict = word_occurence(SENTENCE) >>> all(occurence_dict[word] == count for word, count ... in Counter(SENTENCE.split()).items()) True >>> dict(word_occurence("Two spaces")) {'Two': 1, 'spaces': 1} """ occurrence: dict = defaultdict(int) # Creating a dictionary containing count of each word for word in sentence.split(): occurrence[word] += 1 return occurrence if __name__ == "__main__": for word, count in word_occurence("INPUT STRING").items(): print(f"{word}: {count}")
# Created by sarathkaul on 17/11/19 # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 from collections import defaultdict from typing import DefaultDict def word_occurence(sentence: str) -> dict: """ >>> from collections import Counter >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" >>> occurence_dict = word_occurence(SENTENCE) >>> all(occurence_dict[word] == count for word, count ... in Counter(SENTENCE.split()).items()) True >>> dict(word_occurence("Two spaces")) {'Two': 1, 'spaces': 1} """ occurrence: DefaultDict[str, int] = defaultdict(int) # Creating a dictionary containing count of each word for word in sentence.split(): occurrence[word] += 1 return occurrence if __name__ == "__main__": for word, count in word_occurence("INPUT STRING").items(): print(f"{word}: {count}")
1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/z-function.html Z-function or Z algorithm Efficient algorithm for pattern occurrence in a string Time Complexity: O(n) - where n is the length of the string """ def z_function(input_str: str) -> list: """ For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element the algorithm always returns 0 >>> z_function("abracadabra") [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1] >>> z_function("aaaa") [0, 3, 2, 1] >>> z_function("zxxzxxz") [0, 0, 0, 4, 0, 0, 1] """ z_result = [0] * len(input_str) # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i, z_result, s): """ Check if we have to move forward to the next characters or not """ return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: """ Example of using z-function for pattern occurrence Given function returns the number of times 'pattern' appears in 'input_str' as a substring >>> find_pattern("abr", "abracadabra") 2 >>> find_pattern("a", "aaaa") 4 >>> find_pattern("xz", "zxxzxxz") 2 """ answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
""" https://cp-algorithms.com/string/z-function.html Z-function or Z algorithm Efficient algorithm for pattern occurrence in a string Time Complexity: O(n) - where n is the length of the string """ def z_function(input_str: str) -> list[int]: """ For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element the algorithm always returns 0 >>> z_function("abracadabra") [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1] >>> z_function("aaaa") [0, 3, 2, 1] >>> z_function("zxxzxxz") [0, 0, 0, 4, 0, 0, 1] """ z_result = [0 for i in range(len(input_str))] # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i: int, z_result: list[int], s: str) -> bool: """ Check if we have to move forward to the next characters or not """ return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: """ Example of using z-function for pattern occurrence Given function returns the number of times 'pattern' appears in 'input_str' as a substring >>> find_pattern("abr", "abracadabra") 2 >>> find_pattern("a", "aaaa") 4 >>> find_pattern("xz", "zxxzxxz") 2 """ answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection X = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(X_train, y_train) # to see how good the model fit the data training_score = model.score(X_train, y_train).round(3) test_score = model.score(X_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(X_test) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred)) # Explained variance score: 1 is perfect prediction print("Test Variance score: %.2f" % r2_score(y_test, y_pred)) # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection X = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(X_train, y_train) # to see how good the model fit the data training_score = model.score(X_train, y_train).round(3) test_score = model.score(X_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(X_test) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred)) # Explained variance score: 1 is perfect prediction print("Test Variance score: %.2f" % r2_score(y_test, y_pred)) # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k into k parts. These two facts together are used for this algorithm. """ def partition(m: int) -> int: memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
""" The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k into k parts. These two facts together are used for this algorithm. """ def partition(m: int) -> int: memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ from math import factorial def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(1000) 10539 >>> solution(200) 1404 >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 >>> solution(0) 1 """ return sum(map(int, str(factorial(num)))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
""" Problem 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ from math import factorial def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(1000) 10539 >>> solution(200) 1404 >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 >>> solution(0) 1 """ return sum(map(int, str(factorial(num)))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Get the citation from google scholar using title and year of publication, and volume and pages of journal. """ import requests from bs4 import BeautifulSoup def get_citation(base_url: str, params: dict) -> str: """ Return the citation number. """ soup = BeautifulSoup(requests.get(base_url, params=params).content, "html.parser") div = soup.find("div", attrs={"class": "gs_ri"}) anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") return anchors[2].get_text() if __name__ == "__main__": params = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 30, "pages": "3979-3990", "year": 2018, "hl": "en", } print(get_citation("http://scholar.google.com/scholar_lookup", params=params))
""" Get the citation from google scholar using title and year of publication, and volume and pages of journal. """ import requests from bs4 import BeautifulSoup def get_citation(base_url: str, params: dict) -> str: """ Return the citation number. """ soup = BeautifulSoup(requests.get(base_url, params=params).content, "html.parser") div = soup.find("div", attrs={"class": "gs_ri"}) anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") return anchors[2].get_text() if __name__ == "__main__": params = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 30, "pages": "3979-3990", "year": 2018, "hl": "en", } print(get_citation("http://scholar.google.com/scholar_lookup", params=params))
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 unittest from timeit import timeit def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> least_common_multiple_slow(5, 2) 10 >>> least_common_multiple_slow(12, 76) 228 """ max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): common_mult += max_num return common_mult def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). see greatest_common_divisor.py >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 """ return b if a == 0 else greatest_common_divisor(b % a, a) def least_common_multiple_fast(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor >>> least_common_multiple_fast(5,2) 10 >>> least_common_multiple_fast(12,76) 228 """ return first_num // greatest_common_divisor(first_num, second_num) * second_num def benchmark(): setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) print( "least_common_multiple_slow():", timeit("least_common_multiple_slow(1000, 999)", setup=setup), ) print( "least_common_multiple_fast():", timeit("least_common_multiple_fast(1000, 999)", setup=setup), ) class TestLeastCommonMultiple(unittest.TestCase): test_inputs = [ (10, 20), (13, 15), (4, 31), (10, 42), (43, 34), (5, 12), (12, 25), (10, 25), (6, 9), ] expected_results = [20, 195, 124, 210, 1462, 60, 300, 50, 18] def test_lcm_function(self): for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) with self.subTest(i=i): self.assertEqual(slow_result, self.expected_results[i]) self.assertEqual(fast_result, self.expected_results[i]) if __name__ == "__main__": benchmark() unittest.main()
import unittest from timeit import timeit def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> least_common_multiple_slow(5, 2) 10 >>> least_common_multiple_slow(12, 76) 228 """ max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): common_mult += max_num return common_mult def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). see greatest_common_divisor.py >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 """ return b if a == 0 else greatest_common_divisor(b % a, a) def least_common_multiple_fast(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor >>> least_common_multiple_fast(5,2) 10 >>> least_common_multiple_fast(12,76) 228 """ return first_num // greatest_common_divisor(first_num, second_num) * second_num def benchmark(): setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) print( "least_common_multiple_slow():", timeit("least_common_multiple_slow(1000, 999)", setup=setup), ) print( "least_common_multiple_fast():", timeit("least_common_multiple_fast(1000, 999)", setup=setup), ) class TestLeastCommonMultiple(unittest.TestCase): test_inputs = [ (10, 20), (13, 15), (4, 31), (10, 42), (43, 34), (5, 12), (12, 25), (10, 25), (6, 9), ] expected_results = [20, 195, 124, 210, 1462, 60, 300, 50, 18] def test_lcm_function(self): for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) with self.subTest(i=i): self.assertEqual(slow_result, self.expected_results[i]) self.assertEqual(fast_result, self.expected_results[i]) if __name__ == "__main__": benchmark() unittest.main()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """A Private class (to be inherited)""" class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """A Private class (to be inherited)""" class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Description : Newton's second law of motion pertains to the behavior of objects for which all existing forces are not balanced. The second law states that the acceleration of an object is dependent upon two variables - the net force acting upon the object and the mass of the object. The acceleration of an object depends directly upon the net force acting upon the object, and inversely upon the mass of the object. As the force acting upon an object is increased, the acceleration of the object is increased. As the mass of an object is increased, the acceleration of the object is decreased. Source: https://www.physicsclassroom.com/class/newtlaws/Lesson-3/Newton-s-Second-Law Formulation: Fnet = m • a Diagrammatic Explanation: Forces are unbalanced | | | V There is acceleration /\ / \ / \ / \ / \ / \ / \ __________________ ____ ________________ |The acceleration | |The acceleration | |depends directly | |depends inversely | |on the net Force | |upon the object's | |_________________| |mass_______________| Units: 1 Newton = 1 kg X meters / (seconds^2) How to use? Inputs: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |mass | (in kgs) | float | |-------------|-------------------------|-----------| |acceleration | (in meters/(seconds^2)) | float | |_____________|_________________________|___________| Output: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |force | (in Newtons) | float | |_____________|_________________________|___________| """ def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: """ >>> newtons_second_law_of_motion(10, 10) 100 >>> newtons_second_law_of_motion(2.0, 1) 2.0 """ force = float() try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
""" Description : Newton's second law of motion pertains to the behavior of objects for which all existing forces are not balanced. The second law states that the acceleration of an object is dependent upon two variables - the net force acting upon the object and the mass of the object. The acceleration of an object depends directly upon the net force acting upon the object, and inversely upon the mass of the object. As the force acting upon an object is increased, the acceleration of the object is increased. As the mass of an object is increased, the acceleration of the object is decreased. Source: https://www.physicsclassroom.com/class/newtlaws/Lesson-3/Newton-s-Second-Law Formulation: Fnet = m • a Diagrammatic Explanation: Forces are unbalanced | | | V There is acceleration /\ / \ / \ / \ / \ / \ / \ __________________ ____ ________________ |The acceleration | |The acceleration | |depends directly | |depends inversely | |on the net Force | |upon the object's | |_________________| |mass_______________| Units: 1 Newton = 1 kg X meters / (seconds^2) How to use? Inputs: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |mass | (in kgs) | float | |-------------|-------------------------|-----------| |acceleration | (in meters/(seconds^2)) | float | |_____________|_________________________|___________| Output: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |force | (in Newtons) | float | |_____________|_________________________|___________| """ def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: """ >>> newtons_second_law_of_motion(10, 10) 100 >>> newtons_second_law_of_motion(2.0, 1) 2.0 """ force = float() try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2 ,len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heap_sort(array) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(sort(unsorted))
""" Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2 ,len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heap_sort(array) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(sort(unsorted))
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 interpolation search algorithm """ def interpolation_search(sorted_collection, item): """Pure implementation of interpolation search algorithm in Python Be careful collection must be ascending sorted, otherwise result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found """ left = 0 right = len(sorted_collection) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(sorted_collection): return None current_item = sorted_collection[point] if current_item == item: return point else: if point < left: right = left left = point elif point > right: left = right right = point else: if item < current_item: right = point - 1 else: left = point + 1 return None def interpolation_search_by_recursion(sorted_collection, item, left, right): """Pure implementation of interpolation search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found """ # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(sorted_collection): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(sorted_collection, item, point, left) elif point > right: return interpolation_search_by_recursion(sorted_collection, item, right, left) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( sorted_collection, item, left, point - 1 ) else: return interpolation_search_by_recursion( sorted_collection, item, point + 1, right ) def __assert_sorted(collection): """Check if collection is ascending sorted, if not - raises :py:class:`ValueError` :param collection: collection :return: True if collection is ascending sorted :raise: :py:class:`ValueError` if collection is not ascending sorted Examples: >>> __assert_sorted([0, 1, 2, 4]) True >>> __assert_sorted([10, -1, 5]) Traceback (most recent call last): ... ValueError: Collection must be ascending sorted """ if collection != sorted(collection): raise ValueError("Collection must be ascending sorted") return True if __name__ == "__main__": import sys """ user_input = input('Enter numbers separated by comma:\n').strip() collection = [int(item) for item in user_input.split(',')] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') target_input = input('Enter a single number to be found in the list:\n') target = int(target_input) """ debug = 0 if debug == 1: collection = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("Sequence must be ascending sorted to apply interpolation search") target = 67 result = interpolation_search(collection, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
""" This is pure Python implementation of interpolation search algorithm """ def interpolation_search(sorted_collection, item): """Pure implementation of interpolation search algorithm in Python Be careful collection must be ascending sorted, otherwise result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found """ left = 0 right = len(sorted_collection) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(sorted_collection): return None current_item = sorted_collection[point] if current_item == item: return point else: if point < left: right = left left = point elif point > right: left = right right = point else: if item < current_item: right = point - 1 else: left = point + 1 return None def interpolation_search_by_recursion(sorted_collection, item, left, right): """Pure implementation of interpolation search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found """ # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(sorted_collection): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(sorted_collection, item, point, left) elif point > right: return interpolation_search_by_recursion(sorted_collection, item, right, left) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( sorted_collection, item, left, point - 1 ) else: return interpolation_search_by_recursion( sorted_collection, item, point + 1, right ) def __assert_sorted(collection): """Check if collection is ascending sorted, if not - raises :py:class:`ValueError` :param collection: collection :return: True if collection is ascending sorted :raise: :py:class:`ValueError` if collection is not ascending sorted Examples: >>> __assert_sorted([0, 1, 2, 4]) True >>> __assert_sorted([10, -1, 5]) Traceback (most recent call last): ... ValueError: Collection must be ascending sorted """ if collection != sorted(collection): raise ValueError("Collection must be ascending sorted") return True if __name__ == "__main__": import sys """ user_input = input('Enter numbers separated by comma:\n').strip() collection = [int(item) for item in user_input.split(',')] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') target_input = input('Enter a single number to be found in the list:\n') target = int(target_input) """ debug = 0 if debug == 1: collection = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("Sequence must be ascending sorted to apply interpolation search") target = 67 result = interpolation_search(collection, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def get_blocks_from_text( message: str, block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: message_bytes = message.encode("ascii") block_ints = [] for block_start in range(0, len(message_bytes), block_size): block_int = 0 for i in range(block_start, min(block_start + block_size, len(message_bytes))): block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size)) block_ints.append(block_int) return block_ints def get_text_from_blocks( block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE ) -> str: message: list[str] = [] for block_int in block_ints: block_message: list[str] = [] for i in range(block_size - 1, -1, -1): if len(message) + i < message_length: ascii_number = block_int // (BYTE_SIZE**i) block_int = block_int % (BYTE_SIZE**i) block_message.insert(0, chr(ascii_number)) message.extend(block_message) return "".join(message) def encrypt_message( message: str, key: tuple[int, int], blockSize: int = DEFAULT_BLOCK_SIZE ) -> list[int]: encrypted_blocks = [] n, e = key for block in get_blocks_from_text(message, blockSize): encrypted_blocks.append(pow(block, e, n)) return encrypted_blocks def decrypt_message( encrypted_blocks: list[int], message_length: int, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: decrypted_blocks = [] n, d = key for block in encrypted_blocks: decrypted_blocks.append(pow(block, d, n)) return get_text_from_blocks(decrypted_blocks, message_length, block_size) def read_key_file(key_filename: str) -> tuple[int, int, int]: with open(key_filename) as fo: content = fo.read() key_size, n, EorD = content.split(",") return (int(key_size), int(n), int(EorD)) def encrypt_and_write_to_file( message_filename: str, key_filename: str, message: str, block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: key_size, n, e = read_key_file(key_filename) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (block_size * 8, key_size) ) encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)] encrypted_content = ",".join(encrypted_blocks) encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}" with open(message_filename, "w") as fo: fo.write(encrypted_content) return encrypted_content def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str: key_size, n, d = read_key_file(key_filename) with open(message_filename) as fo: content = fo.read() message_length_str, block_size_str, encrypted_message = content.split("_") message_length = int(message_length_str) block_size = int(block_size_str) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (block_size * 8, key_size) ) encrypted_blocks = [] for block in encrypted_message.split(","): encrypted_blocks.append(int(block)) return decrypt_message(encrypted_blocks, message_length, (n, d), block_size) def main() -> None: filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.makeKeyFiles("rsa", 1024) message = input("\nEnter message: ") pubkey_filename = "rsa_pubkey.txt" print("Encrypting and writing to %s..." % (filename)) encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message) print("\nEncrypted text:") print(encryptedText) elif mode == "decrypt": privkey_filename = "rsa_privkey.txt" print("Reading from %s and decrypting..." % (filename)) decrypted_text = read_from_file_and_decrypt(filename, privkey_filename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decrypted_text) print("\nDecryption:") print(decrypted_text) if __name__ == "__main__": main()
import os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def get_blocks_from_text( message: str, block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: message_bytes = message.encode("ascii") block_ints = [] for block_start in range(0, len(message_bytes), block_size): block_int = 0 for i in range(block_start, min(block_start + block_size, len(message_bytes))): block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size)) block_ints.append(block_int) return block_ints def get_text_from_blocks( block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE ) -> str: message: list[str] = [] for block_int in block_ints: block_message: list[str] = [] for i in range(block_size - 1, -1, -1): if len(message) + i < message_length: ascii_number = block_int // (BYTE_SIZE**i) block_int = block_int % (BYTE_SIZE**i) block_message.insert(0, chr(ascii_number)) message.extend(block_message) return "".join(message) def encrypt_message( message: str, key: tuple[int, int], blockSize: int = DEFAULT_BLOCK_SIZE ) -> list[int]: encrypted_blocks = [] n, e = key for block in get_blocks_from_text(message, blockSize): encrypted_blocks.append(pow(block, e, n)) return encrypted_blocks def decrypt_message( encrypted_blocks: list[int], message_length: int, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: decrypted_blocks = [] n, d = key for block in encrypted_blocks: decrypted_blocks.append(pow(block, d, n)) return get_text_from_blocks(decrypted_blocks, message_length, block_size) def read_key_file(key_filename: str) -> tuple[int, int, int]: with open(key_filename) as fo: content = fo.read() key_size, n, EorD = content.split(",") return (int(key_size), int(n), int(EorD)) def encrypt_and_write_to_file( message_filename: str, key_filename: str, message: str, block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: key_size, n, e = read_key_file(key_filename) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (block_size * 8, key_size) ) encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)] encrypted_content = ",".join(encrypted_blocks) encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}" with open(message_filename, "w") as fo: fo.write(encrypted_content) return encrypted_content def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str: key_size, n, d = read_key_file(key_filename) with open(message_filename) as fo: content = fo.read() message_length_str, block_size_str, encrypted_message = content.split("_") message_length = int(message_length_str) block_size = int(block_size_str) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (block_size * 8, key_size) ) encrypted_blocks = [] for block in encrypted_message.split(","): encrypted_blocks.append(int(block)) return decrypt_message(encrypted_blocks, message_length, (n, d), block_size) def main() -> None: filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.makeKeyFiles("rsa", 1024) message = input("\nEnter message: ") pubkey_filename = "rsa_pubkey.txt" print("Encrypting and writing to %s..." % (filename)) encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message) print("\nEncrypted text:") print(encryptedText) elif mode == "decrypt": privkey_filename = "rsa_privkey.txt" print("Reading from %s and decrypting..." % (filename)) decrypted_text = read_from_file_and_decrypt(filename, privkey_filename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decrypted_text) print("\nDecryption:") print(decrypted_text) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Simulate the evolution of a highway with only one road that is a loop. The highway is divided in cells, each cell can have at most one car in it. The highway is a loop so when a car comes to one end, it will come out on the other. Each car is represented by its speed (from 0 to 5). Some information about speed: -1 means that the cell on the highway is empty 0 to 5 are the speed of the cars with 0 being the lowest and 5 the highest highway: list[int] Where every position and speed of every car will be stored probability The probability that a driver will slow down initial_speed The speed of the cars a the start frequency How many cells there are between two cars at the start max_speed The maximum speed a car can go to number_of_cells How many cell are there in the highway number_of_update How many times will the position be updated More information here: https://en.wikipedia.org/wiki/Nagel%E2%80%93Schreckenberg_model Examples for doctest: >>> simulate(construct_highway(6, 3, 0), 2, 0, 2) [[0, -1, -1, 0, -1, -1], [-1, 1, -1, -1, 1, -1], [-1, -1, 1, -1, -1, 1]] >>> simulate(construct_highway(5, 2, -2), 3, 0, 2) [[0, -1, 0, -1, 0], [0, -1, 0, -1, -1], [0, -1, -1, 1, -1], [-1, 1, -1, 0, -1]] """ from random import randint, random def construct_highway( number_of_cells: int, frequency: int, initial_speed: int, random_frequency: bool = False, random_speed: bool = False, max_speed: int = 5, ) -> list: """ Build the highway following the parameters given >>> construct_highway(10, 2, 6) [[6, -1, 6, -1, 6, -1, 6, -1, 6, -1]] >>> construct_highway(10, 10, 2) [[2, -1, -1, -1, -1, -1, -1, -1, -1, -1]] """ highway = [[-1] * number_of_cells] # Create a highway without any car i = 0 if initial_speed < 0: initial_speed = 0 while i < number_of_cells: highway[0][i] = ( randint(0, max_speed) if random_speed else initial_speed ) # Place the cars i += ( randint(1, max_speed * 2) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def get_distance(highway_now: list, car_index: int) -> int: """ Get the distance between a car (at index car_index) and the next car >>> get_distance([6, -1, 6, -1, 6], 2) 1 >>> get_distance([2, -1, -1, -1, 3, 1, 0, 1, 3, 2], 0) 3 >>> get_distance([-1, -1, -1, -1, 2, -1, -1, -1, 3], -1) 4 """ distance = 0 cells = highway_now[car_index + 1 :] for cell in range(len(cells)): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(highway_now, -1) def update(highway_now: list, probability: float, max_speed: int) -> list: """ Update the speed of the cars >>> update([-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) [-1, -1, -1, -1, -1, 3, -1, -1, -1, -1, 4] >>> update([-1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) [-1, -1, 3, -1, -1, -1, -1, 1] """ number_of_cells = len(highway_now) # Beforce calculations, the highway is empty next_highway = [-1] * number_of_cells for car_index in range(number_of_cells): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed next_highway[car_index] = min(highway_now[car_index] + 1, max_speed) # Number of empty cell before the next car dn = get_distance(highway_now, car_index) - 1 # We can't have the car causing an accident next_highway[car_index] = min(next_highway[car_index], dn) if random() < probability: # Randomly, a driver will slow down next_highway[car_index] = max(next_highway[car_index] - 1, 0) return next_highway def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: """ The main function, it will simulate the evolution of the highway >>> simulate([[-1, 2, -1, -1, -1, 3]], 2, 0.0, 3) [[-1, 2, -1, -1, -1, 3], [-1, -1, -1, 2, -1, 0], [1, -1, -1, 0, -1, -1]] >>> simulate([[-1, 2, -1, 3]], 4, 0.0, 3) [[-1, 2, -1, 3], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0]] """ number_of_cells = len(highway[0]) for i in range(number_of_update): next_speeds_calculated = update(highway[i], probability, max_speed) real_next_speeds = [-1] * number_of_cells for car_index in range(number_of_cells): speed = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) index = (car_index + speed) % number_of_cells # Commit the change of position real_next_speeds[index] = speed highway.append(real_next_speeds) return highway if __name__ == "__main__": import doctest doctest.testmod()
""" Simulate the evolution of a highway with only one road that is a loop. The highway is divided in cells, each cell can have at most one car in it. The highway is a loop so when a car comes to one end, it will come out on the other. Each car is represented by its speed (from 0 to 5). Some information about speed: -1 means that the cell on the highway is empty 0 to 5 are the speed of the cars with 0 being the lowest and 5 the highest highway: list[int] Where every position and speed of every car will be stored probability The probability that a driver will slow down initial_speed The speed of the cars a the start frequency How many cells there are between two cars at the start max_speed The maximum speed a car can go to number_of_cells How many cell are there in the highway number_of_update How many times will the position be updated More information here: https://en.wikipedia.org/wiki/Nagel%E2%80%93Schreckenberg_model Examples for doctest: >>> simulate(construct_highway(6, 3, 0), 2, 0, 2) [[0, -1, -1, 0, -1, -1], [-1, 1, -1, -1, 1, -1], [-1, -1, 1, -1, -1, 1]] >>> simulate(construct_highway(5, 2, -2), 3, 0, 2) [[0, -1, 0, -1, 0], [0, -1, 0, -1, -1], [0, -1, -1, 1, -1], [-1, 1, -1, 0, -1]] """ from random import randint, random def construct_highway( number_of_cells: int, frequency: int, initial_speed: int, random_frequency: bool = False, random_speed: bool = False, max_speed: int = 5, ) -> list: """ Build the highway following the parameters given >>> construct_highway(10, 2, 6) [[6, -1, 6, -1, 6, -1, 6, -1, 6, -1]] >>> construct_highway(10, 10, 2) [[2, -1, -1, -1, -1, -1, -1, -1, -1, -1]] """ highway = [[-1] * number_of_cells] # Create a highway without any car i = 0 if initial_speed < 0: initial_speed = 0 while i < number_of_cells: highway[0][i] = ( randint(0, max_speed) if random_speed else initial_speed ) # Place the cars i += ( randint(1, max_speed * 2) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def get_distance(highway_now: list, car_index: int) -> int: """ Get the distance between a car (at index car_index) and the next car >>> get_distance([6, -1, 6, -1, 6], 2) 1 >>> get_distance([2, -1, -1, -1, 3, 1, 0, 1, 3, 2], 0) 3 >>> get_distance([-1, -1, -1, -1, 2, -1, -1, -1, 3], -1) 4 """ distance = 0 cells = highway_now[car_index + 1 :] for cell in range(len(cells)): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(highway_now, -1) def update(highway_now: list, probability: float, max_speed: int) -> list: """ Update the speed of the cars >>> update([-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) [-1, -1, -1, -1, -1, 3, -1, -1, -1, -1, 4] >>> update([-1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) [-1, -1, 3, -1, -1, -1, -1, 1] """ number_of_cells = len(highway_now) # Beforce calculations, the highway is empty next_highway = [-1] * number_of_cells for car_index in range(number_of_cells): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed next_highway[car_index] = min(highway_now[car_index] + 1, max_speed) # Number of empty cell before the next car dn = get_distance(highway_now, car_index) - 1 # We can't have the car causing an accident next_highway[car_index] = min(next_highway[car_index], dn) if random() < probability: # Randomly, a driver will slow down next_highway[car_index] = max(next_highway[car_index] - 1, 0) return next_highway def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: """ The main function, it will simulate the evolution of the highway >>> simulate([[-1, 2, -1, -1, -1, 3]], 2, 0.0, 3) [[-1, 2, -1, -1, -1, 3], [-1, -1, -1, 2, -1, 0], [1, -1, -1, 0, -1, -1]] >>> simulate([[-1, 2, -1, 3]], 4, 0.0, 3) [[-1, 2, -1, 3], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0]] """ number_of_cells = len(highway[0]) for i in range(number_of_update): next_speeds_calculated = update(highway[i], probability, max_speed) real_next_speeds = [-1] * number_of_cells for car_index in range(number_of_cells): speed = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) index = (car_index + speed) % number_of_cells # Commit the change of position real_next_speeds[index] = speed highway.append(real_next_speeds) return highway if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ import math def is_prime(num: 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 >>> is_prime(0) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. >>> is_prime(1) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. """ if num <= 1: raise ValueError("Parameter num must be greater than or equal to two.") if num == 2: return True elif num % 2 == 0: return False for i in range(3, int(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") max_number = 0 if is_prime(n): return n while n % 2 == 0: n //= 2 if is_prime(n): return n for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: if is_prime(n // i): max_number = n // i break elif is_prime(i): max_number = i return max_number if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ import math def is_prime(num: 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 >>> is_prime(0) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. >>> is_prime(1) Traceback (most recent call last): ... ValueError: Parameter num must be greater than or equal to two. """ if num <= 1: raise ValueError("Parameter num must be greater than or equal to two.") if num == 2: return True elif num % 2 == 0: return False for i in range(3, int(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") max_number = 0 if is_prime(n): return n while n % 2 == 0: n //= 2 if is_prime(n): return n for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: if is_prime(n // i): max_number = n // i break elif is_prime(i): max_number = i return max_number if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 2 ans = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 ans = i while n % i == 0: n = n // i i += 1 return int(ans) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 2 ans = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 ans = i while n % i == 0: n = n // i i += 1 return int(ans) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 alternative_string_arrange(first_str: str, second_str: str) -> str: """ Return the alternative arrangements of the two strings. :param first_str: :param second_str: :return: String >>> alternative_string_arrange("ABCD", "XY") 'AXBYCD' >>> alternative_string_arrange("XY", "ABCD") 'XAYBCD' >>> alternative_string_arrange("AB", "XYZ") 'AXBYZ' >>> alternative_string_arrange("ABC", "") 'ABC' """ first_str_length: int = len(first_str) second_str_length: int = len(second_str) abs_length: int = ( first_str_length if first_str_length > second_str_length else second_str_length ) output_list: list = [] for char_count in range(abs_length): if char_count < first_str_length: output_list.append(first_str[char_count]) if char_count < second_str_length: output_list.append(second_str[char_count]) return "".join(output_list) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
def alternative_string_arrange(first_str: str, second_str: str) -> str: """ Return the alternative arrangements of the two strings. :param first_str: :param second_str: :return: String >>> alternative_string_arrange("ABCD", "XY") 'AXBYCD' >>> alternative_string_arrange("XY", "ABCD") 'XAYBCD' >>> alternative_string_arrange("AB", "XYZ") 'AXBYZ' >>> alternative_string_arrange("ABC", "") 'ABC' """ first_str_length: int = len(first_str) second_str_length: int = len(second_str) abs_length: int = ( first_str_length if first_str_length > second_str_length else second_str_length ) output_list: list = [] for char_count in range(abs_length): if char_count < first_str_length: output_list.append(first_str[char_count]) if char_count < second_str_length: output_list.append(second_str[char_count]) return "".join(output_list) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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: """ This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 num = 0 while 1: num += 3 if num >= n: break total += num num += 2 if num >= n: break total += num num += 1 if num >= n: break total += num num += 3 if num >= n: break total += num num += 1 if num >= n: break total += num num += 2 if num >= n: break total += num num += 3 if num >= n: break total += num return total if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 num = 0 while 1: num += 3 if num >= n: break total += num num += 2 if num >= n: break total += num num += 1 if num >= n: break total += num num += 3 if num >= n: break total += num num += 1 if num >= n: break total += num num += 2 if num >= n: break total += num num += 3 if num >= n: break total += num return total if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 longest distance in Directed Acyclic Graph using KahnsAlgorithm def longestDistance(graph): indegree = [0] * len(graph) queue = [] longDist = [1] * len(graph) for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if longDist[vertex] + 1 > longDist[x]: longDist[x] = longDist[vertex] + 1 if indegree[x] == 0: queue.append(x) print(max(longDist)) # Adjacency list of Graph graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longestDistance(graph)
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm def longestDistance(graph): indegree = [0] * len(graph) queue = [] longDist = [1] * len(graph) for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if longDist[vertex] + 1 > longDist[x]: longDist[x] = longDist[vertex] + 1 if indegree[x] == 0: queue.append(x) print(max(longDist)) # Adjacency list of Graph graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longestDistance(graph)
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # Converting to ascii value int value and checking to see if char is a lower letter # if it is a lowercase letter it is getting shift by 32 which makes it an uppercase # case letter return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
def upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # Converting to ascii value int value and checking to see if char is a lower letter # if it is a lowercase letter it is getting shift by 32 which makes it an uppercase # case letter return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def find_max(nums: list[int | float]) -> int | float: """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True >>> find_max([2, 4, 9, 7, 19, 94, 5]) 94 >>> find_max([]) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations def find_max(nums: list[int | float]) -> int | float: """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True >>> find_max([2, 4, 9, 7, 19, 94, 5]) 94 >>> find_max([]) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 234: https://projecteuler.net/problem=234 For any integer n, consider the three functions f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. Solution: By expanding the brackets it is easy to show that fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and only if x^n + y^n = z^n. By Fermat's Last Theorem, this means that the absolute value of n can not exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the equation would reduce to 1 + 1 = 1, for which there are no solutions. So all we have to do is iterate through the possible numerators and denominators of x and y, calculate the corresponding z, and check if the corresponding numerator and denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" to make sure there are no duplicates, and the fractions.Fraction class to make sure we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: """ Given the numerators and denominators of three fractions, return the numerator and denominator of their sum in lowest form. >>> add_three(1, 3, 1, 3, 1, 3) (1, 1) >>> add_three(2, 5, 4, 11, 12, 3) (262, 55) """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: """ Find the sum of the numerator and denominator of the sum of all s(x,y,z) for golden triples (x,y,z) of the given order. >>> solution(5) 296 >>> solution(10) 12519 >>> solution(20) 19408891927 """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 234: https://projecteuler.net/problem=234 For any integer n, consider the three functions f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. Solution: By expanding the brackets it is easy to show that fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and only if x^n + y^n = z^n. By Fermat's Last Theorem, this means that the absolute value of n can not exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the equation would reduce to 1 + 1 = 1, for which there are no solutions. So all we have to do is iterate through the possible numerators and denominators of x and y, calculate the corresponding z, and check if the corresponding numerator and denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" to make sure there are no duplicates, and the fractions.Fraction class to make sure we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: """ Given the numerators and denominators of three fractions, return the numerator and denominator of their sum in lowest form. >>> add_three(1, 3, 1, 3, 1, 3) (1, 1) >>> add_three(2, 5, 4, 11, 12, 3) (262, 55) """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: """ Find the sum of the numerator and denominator of the sum of all s(x,y,z) for golden triples (x,y,z) of the given order. >>> solution(5) 296 >>> solution(10) 12519 >>> solution(20) 19408891927 """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Kadane's algorithm to get maximum subarray sum https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d https://en.wikipedia.org/wiki/Maximum_subarray_problem """ test_data: tuple = ([-2, -8, -9], [2, 8, 9], [-1, 0, 1], [0, 0], []) def negative_exist(arr: list) -> int: """ >>> negative_exist([-2,-8,-9]) -2 >>> [negative_exist(arr) for arr in test_data] [-2, 0, 0, 0, 0] """ arr = arr or [0] max = arr[0] for i in arr: if i >= 0: return 0 elif max <= i: max = i return max def kadanes(arr: list) -> int: """ If negative_exist() returns 0 than this function will execute else it will return the value return by negative_exist function For example: arr = [2, 3, -9, 8, -2] Initially we set value of max_sum to 0 and max_till_element to 0 than when max_sum is less than max_till particular element it will assign that value to max_sum and when value of max_till_sum is less than 0 it will assign 0 to i and after that whole process, return the max_sum So the output for above arr is 8 >>> kadanes([2, 3, -9, 8, -2]) 8 >>> [kadanes(arr) for arr in test_data] [-2, 19, 1, 0, 0] """ max_sum = negative_exist(arr) if max_sum < 0: return max_sum max_sum = 0 max_till_element = 0 for i in arr: max_till_element += i if max_sum <= max_till_element: max_sum = max_till_element if max_till_element < 0: max_till_element = 0 return max_sum if __name__ == "__main__": try: print("Enter integer values sepatated by spaces") arr = [int(x) for x in input().split()] print(f"Maximum subarray sum of {arr} is {kadanes(arr)}") except ValueError: print("Please enter integer values.")
""" Kadane's algorithm to get maximum subarray sum https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d https://en.wikipedia.org/wiki/Maximum_subarray_problem """ test_data: tuple = ([-2, -8, -9], [2, 8, 9], [-1, 0, 1], [0, 0], []) def negative_exist(arr: list) -> int: """ >>> negative_exist([-2,-8,-9]) -2 >>> [negative_exist(arr) for arr in test_data] [-2, 0, 0, 0, 0] """ arr = arr or [0] max = arr[0] for i in arr: if i >= 0: return 0 elif max <= i: max = i return max def kadanes(arr: list) -> int: """ If negative_exist() returns 0 than this function will execute else it will return the value return by negative_exist function For example: arr = [2, 3, -9, 8, -2] Initially we set value of max_sum to 0 and max_till_element to 0 than when max_sum is less than max_till particular element it will assign that value to max_sum and when value of max_till_sum is less than 0 it will assign 0 to i and after that whole process, return the max_sum So the output for above arr is 8 >>> kadanes([2, 3, -9, 8, -2]) 8 >>> [kadanes(arr) for arr in test_data] [-2, 19, 1, 0, 0] """ max_sum = negative_exist(arr) if max_sum < 0: return max_sum max_sum = 0 max_till_element = 0 for i in arr: max_till_element += i if max_sum <= max_till_element: max_sum = max_till_element if max_till_element < 0: max_till_element = 0 return max_sum if __name__ == "__main__": try: print("Enter integer values sepatated by spaces") arr = [int(x) for x in input().split()] print(f"Maximum subarray sum of {arr} is {kadanes(arr)}") except ValueError: print("Please enter integer values.")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 collections import deque from .hash_table import HashTable class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _set_value(self, key, data): self.values[key] = deque([]) if self.values[key] is None else self.values[key] self.values[key].appendleft(data) self._keys[key] = self.values[key] def balanced_factor(self): return ( sum(self.charge_factor - len(slot) for slot in self.values) / self.size_table * self.charge_factor ) def _collision_resolution(self, key, data=None): if not ( len(self.values[key]) == self.charge_factor and self.values.count(None) == 0 ): return key return super()._collision_resolution(key, data)
from collections import deque from .hash_table import HashTable class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _set_value(self, key, data): self.values[key] = deque([]) if self.values[key] is None else self.values[key] self.values[key].appendleft(data) self._keys[key] = self.values[key] def balanced_factor(self): return ( sum(self.charge_factor - len(slot) for slot in self.values) / self.size_table * self.charge_factor ) def _collision_resolution(self, key, data=None): if not ( len(self.values[key]) == self.charge_factor and self.values.count(None) == 0 ): return key return super()._collision_resolution(key, data)
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ from __future__ import annotations import math # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() -> None: n = int(input("enter the numbers of values: ")) y: list[list[float]] = [] for i in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print("enter the values of parameters in a list: ") x = list(map(int, input().split())) print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) print(f"the value at {value} is {summ}") if __name__ == "__main__": main()
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ from __future__ import annotations import math # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() -> None: n = int(input("enter the numbers of values: ")) y: list[list[float]] = [] for i in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print("enter the values of parameters in a list: ") x = list(map(int, input().split())) print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) print(f"the value at {value} is {summ}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Implementation of First Come First Served scheduling algorithm # In this Algorithm we just care about the order that the processes arrived # without carring about their duration time # https://en.wikipedia.org/wiki/Scheduling_(computing)#First_come,_first_served from __future__ import annotations def calculate_waiting_times(duration_times: list[int]) -> list[int]: """ This function calculates the waiting time of some processes that have a specified duration time. Return: The waiting time for each process. >>> calculate_waiting_times([5, 10, 15]) [0, 5, 15] >>> calculate_waiting_times([1, 2, 3, 4, 5]) [0, 1, 3, 6, 10] >>> calculate_waiting_times([10, 3]) [0, 10] """ waiting_times = [0] * len(duration_times) for i in range(1, len(duration_times)): waiting_times[i] = duration_times[i - 1] + waiting_times[i - 1] return waiting_times def calculate_turnaround_times( duration_times: list[int], waiting_times: list[int] ) -> list[int]: """ This function calculates the turnaround time of some processes. Return: The time difference between the completion time and the arrival time. Practically waiting_time + duration_time >>> calculate_turnaround_times([5, 10, 15], [0, 5, 15]) [5, 15, 30] >>> calculate_turnaround_times([1, 2, 3, 4, 5], [0, 1, 3, 6, 10]) [1, 3, 6, 10, 15] >>> calculate_turnaround_times([10, 3], [0, 10]) [10, 13] """ return [ duration_time + waiting_times[i] for i, duration_time in enumerate(duration_times) ] def calculate_average_turnaround_time(turnaround_times: list[int]) -> float: """ This function calculates the average of the turnaround times Return: The average of the turnaround times. >>> calculate_average_turnaround_time([0, 5, 16]) 7.0 >>> calculate_average_turnaround_time([1, 5, 8, 12]) 6.5 >>> calculate_average_turnaround_time([10, 24]) 17.0 """ return sum(turnaround_times) / len(turnaround_times) def calculate_average_waiting_time(waiting_times: list[int]) -> float: """ This function calculates the average of the waiting times Return: The average of the waiting times. >>> calculate_average_waiting_time([0, 5, 16]) 7.0 >>> calculate_average_waiting_time([1, 5, 8, 12]) 6.5 >>> calculate_average_waiting_time([10, 24]) 17.0 """ return sum(waiting_times) / len(waiting_times) if __name__ == "__main__": # process id's processes = [1, 2, 3] # ensure that we actually have processes if len(processes) == 0: print("Zero amount of processes") exit() # duration time of all processes duration_times = [19, 8, 9] # ensure we can match each id to a duration time if len(duration_times) != len(processes): print("Unable to match all id's with their duration time") exit() # get the waiting times and the turnaround times waiting_times = calculate_waiting_times(duration_times) turnaround_times = calculate_turnaround_times(duration_times, waiting_times) # get the average times average_waiting_time = calculate_average_waiting_time(waiting_times) average_turnaround_time = calculate_average_turnaround_time(turnaround_times) # print all the results print("Process ID\tDuration Time\tWaiting Time\tTurnaround Time") for i, process in enumerate(processes): print( f"{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t" f"{turnaround_times[i]}" ) print(f"Average waiting time = {average_waiting_time}") print(f"Average turn around time = {average_turnaround_time}")
# Implementation of First Come First Served scheduling algorithm # In this Algorithm we just care about the order that the processes arrived # without carring about their duration time # https://en.wikipedia.org/wiki/Scheduling_(computing)#First_come,_first_served from __future__ import annotations def calculate_waiting_times(duration_times: list[int]) -> list[int]: """ This function calculates the waiting time of some processes that have a specified duration time. Return: The waiting time for each process. >>> calculate_waiting_times([5, 10, 15]) [0, 5, 15] >>> calculate_waiting_times([1, 2, 3, 4, 5]) [0, 1, 3, 6, 10] >>> calculate_waiting_times([10, 3]) [0, 10] """ waiting_times = [0] * len(duration_times) for i in range(1, len(duration_times)): waiting_times[i] = duration_times[i - 1] + waiting_times[i - 1] return waiting_times def calculate_turnaround_times( duration_times: list[int], waiting_times: list[int] ) -> list[int]: """ This function calculates the turnaround time of some processes. Return: The time difference between the completion time and the arrival time. Practically waiting_time + duration_time >>> calculate_turnaround_times([5, 10, 15], [0, 5, 15]) [5, 15, 30] >>> calculate_turnaround_times([1, 2, 3, 4, 5], [0, 1, 3, 6, 10]) [1, 3, 6, 10, 15] >>> calculate_turnaround_times([10, 3], [0, 10]) [10, 13] """ return [ duration_time + waiting_times[i] for i, duration_time in enumerate(duration_times) ] def calculate_average_turnaround_time(turnaround_times: list[int]) -> float: """ This function calculates the average of the turnaround times Return: The average of the turnaround times. >>> calculate_average_turnaround_time([0, 5, 16]) 7.0 >>> calculate_average_turnaround_time([1, 5, 8, 12]) 6.5 >>> calculate_average_turnaround_time([10, 24]) 17.0 """ return sum(turnaround_times) / len(turnaround_times) def calculate_average_waiting_time(waiting_times: list[int]) -> float: """ This function calculates the average of the waiting times Return: The average of the waiting times. >>> calculate_average_waiting_time([0, 5, 16]) 7.0 >>> calculate_average_waiting_time([1, 5, 8, 12]) 6.5 >>> calculate_average_waiting_time([10, 24]) 17.0 """ return sum(waiting_times) / len(waiting_times) if __name__ == "__main__": # process id's processes = [1, 2, 3] # ensure that we actually have processes if len(processes) == 0: print("Zero amount of processes") exit() # duration time of all processes duration_times = [19, 8, 9] # ensure we can match each id to a duration time if len(duration_times) != len(processes): print("Unable to match all id's with their duration time") exit() # get the waiting times and the turnaround times waiting_times = calculate_waiting_times(duration_times) turnaround_times = calculate_turnaround_times(duration_times, waiting_times) # get the average times average_waiting_time = calculate_average_waiting_time(waiting_times) average_turnaround_time = calculate_average_turnaround_time(turnaround_times) # print all the results print("Process ID\tDuration Time\tWaiting Time\tTurnaround Time") for i, process in enumerate(processes): print( f"{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t" f"{turnaround_times[i]}" ) print(f"Average waiting time = {average_waiting_time}") print(f"Average turn around time = {average_turnaround_time}")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorithm. Only works with positive integers :param list_of_ints: A list of integers :return: Returns the sorted list >>> msd_radix_sort([40, 12, 1, 100, 4]) [1, 4, 12, 40, 100] >>> msd_radix_sort([]) [] >>> msd_radix_sort([123, 345, 123, 80]) [80, 123, 123, 345] >>> msd_radix_sort([1209, 834598, 1, 540402, 45]) [1, 45, 1209, 540402, 834598] >>> msd_radix_sort([-1, 34, 45]) Traceback (most recent call last): ... ValueError: All numbers must be positive """ if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. :param list_of_ints: A list of integers :param bit_position: the position of the bit that gets compared :return: Returns a partially sorted list >>> _msd_radix_sort([45, 2, 32], 1) [2, 32, 45] >>> _msd_radix_sort([10, 4, 12], 2) [4, 12, 10] """ if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = list() ones = list() # Split numbers based on bit at bit_position from the right for number in list_of_ints: if (number >> (bit_position - 1)) & 1: # number has a one at bit bit_position ones.append(number) else: # number has a zero at bit bit_position zeros.append(number) # recursively split both lists further zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) # recombine lists res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, 0, 24, 3, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [] >>> msd_radix_sort_inplace(lst) >>> lst == [] True >>> lst = [-1, 34, 23, 4, -42] >>> msd_radix_sort_inplace(lst) Traceback (most recent call last): ... ValueError: All numbers must be positive """ length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. >>> lst = [45, 2, 32, 24, 534, 2932] >>> _msd_radix_sort_inplace(lst, 1, 0, 3) >>> lst == [32, 2, 45, 24, 534, 2932] True >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756] >>> _msd_radix_sort_inplace(lst, 2, 4, 7) >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756] True """ if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not ((list_of_ints[i] >> bit_position) & 1): # found zero at the beginning i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: # found one at the end j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if not j == i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorithm. Only works with positive integers :param list_of_ints: A list of integers :return: Returns the sorted list >>> msd_radix_sort([40, 12, 1, 100, 4]) [1, 4, 12, 40, 100] >>> msd_radix_sort([]) [] >>> msd_radix_sort([123, 345, 123, 80]) [80, 123, 123, 345] >>> msd_radix_sort([1209, 834598, 1, 540402, 45]) [1, 45, 1209, 540402, 834598] >>> msd_radix_sort([-1, 34, 45]) Traceback (most recent call last): ... ValueError: All numbers must be positive """ if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. :param list_of_ints: A list of integers :param bit_position: the position of the bit that gets compared :return: Returns a partially sorted list >>> _msd_radix_sort([45, 2, 32], 1) [2, 32, 45] >>> _msd_radix_sort([10, 4, 12], 2) [4, 12, 10] """ if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = list() ones = list() # Split numbers based on bit at bit_position from the right for number in list_of_ints: if (number >> (bit_position - 1)) & 1: # number has a one at bit bit_position ones.append(number) else: # number has a zero at bit bit_position zeros.append(number) # recursively split both lists further zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) # recombine lists res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, 0, 24, 3, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [] >>> msd_radix_sort_inplace(lst) >>> lst == [] True >>> lst = [-1, 34, 23, 4, -42] >>> msd_radix_sort_inplace(lst) Traceback (most recent call last): ... ValueError: All numbers must be positive """ length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. >>> lst = [45, 2, 32, 24, 534, 2932] >>> _msd_radix_sort_inplace(lst, 1, 0, 3) >>> lst == [32, 2, 45, 24, 534, 2932] True >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756] >>> _msd_radix_sort_inplace(lst, 2, 4, 7) >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756] True """ if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not ((list_of_ints[i] >> bit_position) & 1): # found zero at the beginning i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: # found one at the end j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if not j == i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
PNG  IHDR=GgAMA asRGBPLTEGpL  $7.G # e {}~~&y?I8MH` "l|/"w'xz v 0zB#H$?J` 'T^l %z &М/_s:OgR$ 'vP " xmju +Wze][p1"-7a|<G~?rs()7N .XAV1KC%@b:=@8ӊ/GSEKWl41}!}bŹɯd³mYXJvw,u)'&hf[%nOsjVVVH~~~) EEEfff544rrr׹cP7raGꡠ@qɲѐ.Vd~{DARLkLj,|DN\Z/KfMtRNS- 9? '3JYl|6$NL֋3o`zfAӪ옇i۶yӮ ֪dIDATxKiG4̍{tXQ*-Z+;Ȅ!11\8cXݖ xE"VʵOG.[լ-E".<$dd-d5y)/b\N\^q)erb2ywp0π|0&EXvhxǐ('2 + ~a.h@js^ =*@.6g,7GA~$KxXںON"$4]iVmׇF@T|]k~w=wx:/b8?QhcZ*vtbVW2p4ș"8A跿'qMuEL%a =YZrO1[Uc&`;;W~*+s^/m(>ćɏ4:j]/Fq_C EwZ[ŴeɩpD|| \: [v.1BA;kU姉[Fl ߟO"[0rD6 *jiit GN?r n<΍FwP;6 ݛ _QқO]vjYs/XnM7ڐhŽ#95 bSV;f\[7.pF>EZ(< ji}]#QرPd2Ct\A|D|M'$#E 6 ‹])Fm lS"(x7WizjvqڪKf,]NY74_a"LhtlXاu">h\q߀zE(/gWZjY k- ku&ˌ,[-?d l/r%DjY=(<pREټ^a'>uקSxyuwXLciW#z/0tn ^ Riu|\nx^7S e'{:Mtt5r>pÿ7w68fv…TYm2 p:K&^pf4'vX#&#:<l%-j5LV)/ \eMLy. OQn\ Y͘U@1n"=Tm<<>˚2f9RAeEYwBkNQ'V*V_p8g֌Yse' .U[MzŊ0HO10f$)K`I^2ڪ<о/vfAxĘ-Aw ;. #/;y2ez+40($E@rK[҃"*=`u1ⷬ\/?uoEt#=^+CaLyYl1Ap|C1@ફa*5nk5?Q%y9"َ'^ӆE$!Gy<,a %Z[*=,fJjx`r 4ա@ZW`^L'YMBzpN+.U#I>9'SG˘pǮʏK%J=Zj=esvxG"pL Uz#f)\"ѫ#+#jpA|wH/>> وnzyj*%frّ%ZsrsPl$.=no<ti&7` *%,Ɍ ĕaf(Y},a.lO_~vii`WΥo3_~Gs=8I7{2=#`䨜# sΕ7ܸ#Y<|  A0Kwe~nL̍rB&HV!s!Ɵ?"c πpGP*KKs;gLeu.JToWL!=,Γs ϏOWhGc౎Jv=9a%Z å;`\|Рʕ=w.$ @rc|: hFK) IUشt!0C[X}fH|/5|f>1>zQIGt! [owqJnJ/O-6B R>g|4nTTn) kkv{tW9^jfsPL.8|a` .Tb W]Rc:8+mo}.# kYFTd[EMzDsk[@wM}!g٦MO3I(ݕgGC$! I m|X甏g_ɺWo[ZvqJJu 0 7 Oݓv&dln1/pu}T 7㧊 :{/!Ǎm#xh*=YЯq]Z8hTJ#=E:X?TO˂jK`=m{ge6XS.I_XXl%j|?/A8S͹@oӆ"Grd4AK|+sViQhr/۫o'+R cORcz8@qcFmcuiFf\4$wzQ $[nrڮ@|$MEU}饀^T !oҚz76 nF/x#tCÀAzZ??sVqaw0˲, ea.0x{oC1{u!y%Z3Y(@5H4KkwFIe)<$vf!Dmy0\)=@oauﻱtȓ}+xivw{hU5kԟrcר0kYo=L/c{ӧcLRӱp蚉{K{o/ ;.<97{.t<EV1竣ѳK[zpOzk1@TyR5Fr}p+7Sx7=QGc xayt=w3ć%s&=<]1W{:j=;@9={v>]#ˈ7Se\|*eKuq}sz0LzWm}]#_\\|̚gU+ֵ˝c ye.{7</KY ;-;ٮ}dX2Opc$;FǸk,-^xȟ/>/^s TzzB:Ogv,>b;Ն\e;L~4U3xX(oˇq7}=AL;Tv6+ <+3lbVE@/'><ǣqWjX2=n亮&>`[Ns ^^ q@cl tݟBXƲv=Kod{oV6{g=:bxxk:#x9,@oi)߃ v bkGt7z__|KY3tȎ^?2hq6s^;9:|G~(9 ޤUv"gV9]v *Z ^Rm5 hO~&[~Ǔ@oe7ɼ^3 C41qv`(<'ZH F?jX?|=27^IzZ+/+GJxg,?F0.qtILZd0 ؟mW ?Y _oab^ʃ2'Vv l/W@`Yh0"~9@K#;Kx܄ȆK0~ׅLPzPU^Gy*QEz#?Xbz'4:;>`Uf7a!?շv\BZFrs|A%Dž|f} !eDϒ&:bg M&ՠ?|?L=rᱼ4?zn#hgFfA@H aʎJhjAw2A|+ fEq,ި6*?( *W^м͕`n"9ɮ 4+ ]o7z,o]r+Xqq o#Y[,c,vULHJȲpۢEOd6EЖ5mux=) B}Ṷv\(w6-6Aɫب9V%Eխt,7u8svL]m\4bC~Y U yAgbNt l'(Gώ׷VX_DɜxKT<Dxw xl[=(o+EJ9 ohg%ze5Mu4%/Zĭw/*;hW.@+ ƎcHx4n݉OV;/2S_DĖ(Y]ykV 1TS*ww ٙ dpWXdLhKf;qob5O{">/=!@ X.Q&!:O. BNӪM Wo_Obwxٙ VTmFwD`cq3&˙vvS箄_E6G yC|:"[ V6PuBxx7h=T$2U#ӗJ9 <h n|\>Э܋J*uS% 4 Dh&״x <I)ί 2B!TlIaZ5 \R$-hvlD3Z MύԧFZ_ƴM"xfHKAI @hS ?^Mt]Ja~ 5'|\, W$jQ> l9.T?C3QЭg'5I2x_nMLBh@fLlzbVKȎj,_*={t?}?Çid5ph e>ZtvnLnKZUSI$'@)59`DLC|3nROi7&K\Y8۽5XMO#! Cr&Qg_݃ے7SĬi~^'躘+b@|=T4JZJDf1".9 eeExLͳ@uUW]/ɂ'dfҳ%zmqHw}`6PWp$7Ў!йG;D Bsmgm,4\EKidj~l 0H"!QXf>7@߀^SM:f4wR?Bl%z+M!Y*t _C9#C ~.@3z @K i s|V:mTIgh >z/o抢#)3=aw2A;3@6V PXۥuc] xoA+:1@s)ɾj&`~@K8 U'O3;:rW=.%IE/?m K 0Vڵ x5l Co2hŅExnvWۚF-\nki֖, vb`<$K$nߢ:|y>Hy\եdZP\,yM.& >۸MA.=_|.'ܓm=B <^||X)WZpø* ^E O\4{ ~#x-v5 $@.Ւ;>N xr|8+լN OR xx( KZ:7&.)W9BP(yѱ\>SYM(jx#& 1m'MxN8Yw9dz?fI1. Z b q9" r?+ ]{լi4t4^P+~ 40UI`)n̋0/bcϔ=8YTPZIbd}BGjm1NyQcz<RN.iE1;|5Ւɕ՛R: 53BF)U^8"06 ^9OǛԷ"_^h{lJrC⸅":؂0 gTEӲc tX!!@|j t߿ɲ" [F獇aq6)ZH\3iAw/nx0_纑+Ua!P|}[aQt\FL7-̚%U'ũhx0>Ĥ7<b͂^X SU!rsNac: c>8fAH@=qzҞ]Ћ [n,98ZYx=1 5/nvdq`&1b ?XcvөG!]N)L*ꁯI#,mMu|pk[4IZ͂j} +>#>=;"^f" $I`lF4 K|Z"`X}긺gp{wv9"Z<9=}GH䂹''BzG鑁o]̳q㎬%59^98zq=wmQ{AG{ľ;H5^PqcRCzE'4:}zC\^{|k}hén`{g{~l<yr,Hh8sCVtҋ 7w6v{rg˧_ݽӭݗ];xr;>݃NwoMz1{p8y*?&D[w{9t:gggvW*%;;;_ܻq;0ӛaMu #aU3I}=ƽ8d 6_߼%ڿ}I֭v^ȥl{l H_MUؼY|fq3z0ՠJ d`w@r?twVyo6YKSNJ z0KWE03 PHGhTR |Aj= tEKhJ&>[`8R! u# dUa|M(J0րh5Xc+ D'StD\ZzB¯Jf?~Ɯ0p=>,2Ĩ'(8B];u|% _IS{຅TsY1] ͿǷp0ĥQ݈}p C/>Pz1U'7" ˗Հ3%)n5;LQwS40 ղf"@:-<0{ `xǫb:BmĮfP;p<&_çs Od$qL&a9Z mՌWך)<<L ==8=紁 ts81Rx3k-֦ eGٶf=#dSkOKNV1{0A pe]4VN/^HW9|<丘ey,[ \wsOLz OTqbelI_-"FYUZov&6 %D‡/@O^R -`W爙ASVO =7mp4$AP+WbΤC\l\FhgU3$ rs]ôbł`8f$I͚Q#*İOsCY?ȀX.[[NX!g؛Z*è$*FNdA|J_bX1 ^ð$ ϊ&S^Ff#VQɴ#c1At$8 $xtkKa@(ST!#) <iȬ /kVE {nEKsRңǔTlMpJd 6#E$\۬)B!ǿ`Ǥ<ǰxNd2OՈAߦ8 6T=f$I o{Oqt#sI8M8ʔLh=nY QGnv*ճ&q? ryy0%ۣDw?vU4ŸPs!7djƗ@&O1IB$2A<Ā0ɕ7g :(NpL65c,OH1 t濶"_dacْPǧEZx2 IUUī3@;<!v*> ^,F<>脧tp8WDOOd9.U"A /vgF[v&.DOؾ&`IR~>,=\D&A`0(|ƹn@{> -?v/mdkj*-,K_0(a`0$Y%$s1FPTH\u-nXXX{v[Vq9g&3dfٓF<VwZm⇹2ۼ(Vr-F~ZWeJ+y]>[V}<ܧK_W/nvt*d%uDuNwʕ+b,S]9{ ϖ+ KzZ}<ߕkڨ _X.#nGA[]^gUڍf#B~mһUJB5][}z=3<\gVaX 1 dp״#羮<F&- x/yt*2\%'vF4#ZQ,=0`,Z"9emL/hH}<6]<W|FrhoׯP:M'mxo4J*IғClFgצS~5BII`g h ٥GN{.p e!:8'zUHFz]׼70עBЈ\^28&#4}7;|h1CR]: [/=O!8^)TlCn봌yck04#T$΀S|?*a ><h =Z <G!V( &Ep|4ZKOIrq17J@G|c5s{mmY%77)g.m4 "ϥefŜ0cMLwA@#HI; a9lHWVWlC/bk|1kznq/Ϳ#cJ_u@LA  ԖrR L@*_ؗ6-lkL "4܅\* 0BzOehz"]P {NmC@/wThB.7n~/{^]?&84۝6i4b 95ˬ-tȦ"J ˠ?q}}s\jP̼#4fg }Ml-@XdrG mԀ)8njďW6WҨѾ<BFhϴ5ܴ,)r)MF KX`dJ[iR)3|X䬃)]{ziYʥ\BrӹLd[Y:d- >/=sH#42sXܧw.ω\Fp<K3n/]&zJۥQS@z+̴A-1]B“M- 5|}#=_K}/^.K\ӈfemy{`]?Yz^S9~aO#T X1ӽxq<-fʭ| ah ]IEE Qz=ަ{4-*@oySnStI@zТW};c؏9mɅD\LD% 5 {s4H{dL)Nm 43l*(^t L`/Ȣ˙jc_RdHӤy0|1ͭ!=9 $zbLiwE/~|/||3VQ8V #~L|tޞ af2ŔPre_mn<A1hfEtwĤh ћ%Ƿs5Eon2x*4~{>ɻw,؉m VON_ $= Cc 3sNwh[xT2Wٞ;%q}vٛ`*ix0(BjU|P8(tFp(_iSj^TM!=2\mn?[~=Z 6R3एp_MFmxًeBΟ:<.u C$Yt?/[$j ANjҗ&z{!9v.)ޖ>T~󕭔fq完E߂0%IOj(.NH|Y|M[X izRB2:F|bS1mEgsF4%axKjLWgzIA|f=e3>L[$Fǡdeö.7נ$=a(nPrl>htT?hH,m1n/H̆eƧ'3==MI/A)],qdPňqBN >V{Do/ |t^ڽTr#xO>-@_R;]:]Ct˭cNue{-/lK~ =qB1w`b򕭔 DDM7KRӪ0Q# q[Ywa6~oyyOKئ?N &O! ?)oU"Q~E{FC|tYQ^R2 Ll"Zhm+yEЏ 7,Zzw* E•H9{钞H.!sTQRO:hoayS\!|Ώ3Rhn/3>7U*Qjϱ#h/=#l"ˍ)ꯅ_B^,|&DQ}-kTi^~v^M\%|4G̖ a>14c !>=vy <\Yzmedo1]"Lwx[kCO^ ='퉸Ev{a?94#\~]Br(6uu{mԄ~b =nY,|;zs Z;AkGoJB,Yv^a<|{*H_6=w~]L-»ND_2XWv]gEO! uzI0hTTDl# W,K6y.Vˀ _Z, 㶮cԝ?BZ1A6E'Y"! yiƠyThDVGj)DF(c{νq<&6Ϸ{9S@!a@w>e) ]`^x{;X5ᣝ*/zx01b8Sx4ќKLJ{CcT'vK{:M%3C_𽚞^3q=)y;<>fʫ 9YrYF!g]NDAquPzW.]H81Um=Ѩ/nBϱ .8gb c;|{uzf~5VVkCz=:@DC1sÕږsImȢCoxAb(.zlek`mui$DTnmfowۢD.afƋv{Y0wqqV-$Z&.iN躌\^A<=|bngt؜N'4M89esc%*Y2^qOiг{h D|}}7M#MǓMGtjSMK/?~'u3eV$'鵷cG>{yK>%Ǜ0w,HkZ4x~<DmA̞G|A@U I}gE&=/PzzH1m{wu0M|)U'Jc>r>赵|}ңg&D_&͢{iލl;Xcscs&Oqn]vQ|)^+MI^N2Bi^~b2yc"|x"g`wzz;HҒy^W],J ς(%+U٬mVK &@67>sFC>sv!W\!,{waA1UFgs4{ W%,Iw(Qbd~bG(<qYw.,嬧 z _o Jz}k}}~E,E4ׂ1q>E|R:s*ѽp'R.z:ozcHPuūt=z'n`=)frƥ(P^~3鳢E@;l~.(_쀹[Yk j)ts]c$ ѓуξfJݹH kWjx*ו0> p\87ȩ4pgc[7K':dCEXM3-=*|3aÚ֭6(B-Ӕ6-=o}li4sE$I(rqg)gqKY> zN0zE0^kWzg>s4Ckr2?s8=A6dΗ,/rTg؆|u¾׈ie,퐼S-z=Gߟ7;NۙEN<Gz?6n$jd?=NHzӳ#щ #iadmױH/Gd4TPvF>ؘ<uϨ^ r1-7)p;*ָ'+o7d;t\HIݸ`hR:N3zr|& SWu$baL0{؍:b߰C }7kx2L!Ž%Aꥫ<M50^^ҖǣkO1XrjNt8O |S|TrPܬ6+BRnju&X*ˋN堐_TV*+aT*|rAO-Vwv*+fъʠSy lHpr|!ʖ"R;Ki7A{޹tpBXIQ.(x4dH5,†P =rg~t^N1@.~g)]|+Jb0̧e:V:e|$jJ;HwLP5fG_YOK f1وB^W ͲUc^Xo:x Жy.*[m\-Or@ /C<mMIJ_]l)d!;Sfxeɇ/\,G©vJ$J9e],3 Bu{Jl@ن߄67U:"Xr 3{ݑX6%OT]'*8jP6-ɋ6mSŝ METLPXBfj0)dK@dR.P*.^58%$ݿvzzh+ھ4(>^ONGUx^+*TU1 Yʊ\JC]/($|;GYe瓾gDz!+TWo8M}!'/ ::ܢR8UKO6%mX 2.ճZ<[ 6HĤ)X ZڦF$+i"["~7tmEs͡}g-  "jDׁݩ̓u JLk<fN:ȱtN|CVDыBo]r_{{pTW\n(GhB%8(~ zC!ᕕx^jD1w֜2e& 3 tUwG>SLG' JfQk!z>c~C_N1?$j=b*b pٚ!eXupK9Jv4Hz¢]TJ7NXB&z߆,§]/'aMˬnORUlǙFҔ% ze)eVf0,\'D`E:FDg"w/c Jr?B/LO)7y*$Gz8Ϊ^m]Ҫ7}z|)Y.\KƖEb:`1Kv4 cDŽKDX;KH msfΌ_Ȯ=F1O</62V؉B A~7"c6V|fu\ |XOI6|!`čG" қ0vi0>Q6 faVzTEU5%M>L{gg-Uw;.>Uo (f=*|]Q8…70<C{OLv2>K;{3%"*pX4xjO. b6s)?ʲΪf|wa,K?̬#zﰞb* kI/kI2CY')$"se|{9 z25Jv!_2T&=mvTb'@:rgᣀ=+>)ݵ-MfB7`W ʣSM*ײQ KYQH|a6nZbHBi5333; @$5 #.pO8="d7yܽOmi W5MurJŐ}r,ǃNXec!qS̓=1c-Lx Dw=a_b[jrUwxun) ?%uh[v_a25f x-_(sHt>cQ>(|73S(ndz#ydķ.79-sG1i\Ukc}}ܑ\e` w3mo÷b?߶ݎYt G Äw"ynﶏ.[xlr,c+<{ڇgKtgX 8XzߨEkg$3Y@~րzdoWh .'ϟ;xcII\rz2? zڤݒW8U9e9zZҫNޖv/yߥxAnmc !6 ^,obYG D ܾfk~&~W{h{-tXb`:==G#x=7$z\X&]M1^IFRvL@첪owݕ1o6.ı<8K~KQj/0=|@-x?Pkң}IqGN 2GS ƌc_#L{o&~e cw.~2? vL fyOh6[fRqp [;B^ ݺ,-U~ݿx3caYBxu1vSgᅇH|{䀧 z-g< Pu[Od/>FgsTkwhEtܛ2=,,iLfmͤbB:E. [,2<3/gLixsCeUfR?zL+\n/!Fy^R[[{f }+0bJm/3c(ˡ i=W6Wilrj׸GŻHUGWBz]+BxX C7"z2/H{Zmܲ_ZqMwGqQ1JI:Wǐ/C}#%GeOO(ƧW=D7-z6*^r]#m=Y㇣=RՒNej-h$tt7+8yb:*gLڡvk o|ēēm)!%zQapާ_%OhWjh0.oKrZr1EqeHR=-z 5Tqf60%ot*.g3ZN~v[FK ?dM%rgmKؼrE-5OF1AʪX0KY U<j`q?Ͱ^'4?_;Bgk686vC -e)t;r](˒A`GcwhXYP@}wARgM'СПf^0Dh3VRj%K~ /Kf72qվ$ޠŔ7zKt"7Zx! [k2Vh]TNnKGS!! .Zj_rusH 5r:GWo.Z!(6k-3\z,k~ #G06s &y5)]C" ": 'K|&\$L*Q+8 ^wbp6Ce }0|hYeW7azm_Mc=M/0|>]|e9L/hkD0;ASF9!F5 Ž L"~Nӛ ^>8i'zL[7\87['&sDSz~Ҟ)PĮ5t;Ӧ<Is9nr%Na>xu^)ɰ?q<NpЃV"Je><qx<U'Q%]< e3@S.;2je $t'73z'4p6e?LuVq1yܽS+d8磏gf@7>_@Bh-Flqa}{mMq+DG"tqd1{kH,0$?_p=:-28\h kPZ< RԲT&j[c`2=e g"ѣH,r9g 4 ujV^/ x@hӞE~i~8Ͼ"c]1_|իVmYk@Hbq$Ք,TK%D^c4=I}>UNw\{&Cl(un7Ç߼yÇNOO߽{ L*jC:JՑZ-ف > IИ#_4_~CM|~n]MWۦ4j*izhcF[,<= G# ,iY*Yl㰾uz9'}͛7׉|?s<x{0yoIdb 2ɩݫWAn \B<L?e .Tz"8ej*z^ݻn( uՁ?;=t@dpEoz SQ7bS@`-aQ˸TOFJ۷ *զJj+I[տL$%`_@ < .)=LCEzbMEEdwT߿~ߠ{oit|~Ӄ[T.tb dCϮHy8DK;ۍJܴ <4+fdj݇o~xarGoz=K:X*|%"Xl"",R4]{m[(kh( ײy^1X0= w;"݃Ite79C/bea/X1` m 7=T?siV!5$7PAMd)R\az=WyŦ)hã= ?®(,9rz`i-Kb7 P`a>( ϙyna-16㬦 (ba_M@($%ZƑ^M;_=21wull`^V@E&,/i>$:7=PEbr _y<!y(sZ%0^deYXOÏ_l% NJ97bjl!@zb8J_Y>@%9˵H@~ \hv97@R|_j@z9G TnPv Z Lg͍D¡؟$fhRZ`MOe CW\AA-ON|* B6(E!Kat> br"S"1b,p҃lh9;j`q7?wdT ~ߠQ@ J?  ?ϦgTUq?g*tpWvVvb +þ >yRW;՝^|W"vIuQq Ѿy>/Ge Bl1_JrD(mYVwbP?_j{1tM9U{0_]uV]H.ϭE?@|6 2"?h=,>}YjnA@1|Ji3Y`}[(tAbN%PW׶PYTO'UuNlUfcI@o\wXf nY8z(HϬ-[{VS3JF @t[bBNяna1x6wsf-Eg]$R\AV<ͥ2Q @=K?H$$^|VJP:[PN ub,%Zt]!|k33F 6gh禳 OD|C]yB8n&~cාS'6ɇs,T<|"ėـMIGx/<!v Õ[H=]D0#773s_h9kwڭboF#L)@y F;KԭDby1"FǞV;t}g0J㞓] ឡ~/5mZQCϗZXt/7MLn "*;w(Ɨw#@J^T՞Nabh-2" v Ƃ-L/͊h|>vz:]O(Dǐׂ%P \PuIsډWNsB'‘h _W;D/2ADŝ]: R?4{ ^Aw> &  _ ٩ u?R0;x";sG]ơq¸2;Lx'i޾7&Kg Kz Zs73q. :>7ŭ*ur˯'VOZ( ^ @.ˎi7b|,x ]CƩ%>RU$q3Z?p7@@`!Kib/VG?lW/{mroXڍO'&l@ģtk,vbl|=C' У/=};^mzTKa[ۻPd4~2v7cR%FukzlEϵmك1<n :;=ձ,iӔj;G&PZ?@x4 7[İR48= >* SG]VģztGvb< l| ##NMNL}ԳҪ<<LJg7gĢw`5:/Ng_C@6/v{MXDxO wBA@c?ov8H\t\4ݳv(e)20:a|gNꃥN99懸y@wcA/4'IZ$)]T:ۇۻ{@=/|$;w*T^giiXh"2Mr7L< ɩۖ'#zʧۧ-eH fO'"U<BؿyK x~|H 覦nLEsTK\ ww%+<~uK/%vB : ;/Ҽۯ(`6{'8>MqƧ=Qez76+'ehHq=r.mdYwI(@mӄJ`UW+bHV3 M `Л7sʏ<$y{O]ח1ϭwrߞ>;葳h$l淧gU~2>3<anE[{n'FUX8&}3<Jo﫫ѣ,g'ӜKNrxSуiG32w>䧅޿$z'`'3KExD[{#|ECǏ7<;A4ƞǧ_?׸Uzc|P @UL =jx-ʯPioGgw_5Q3-j'<1c_~D'1*5$x$v`Fnqo-*^X{7xߏ4 0? Oblž%zWTV~JG}\, _z >֏9'A$? ߞ0x:8a9n{j"g5wb~~a1k3#ڃQGG Q,cC;>>HƇI=+<Qw^z.~7ޘ!U">,|~'Ə{o-JK7ʀy9n/jGzL)w5DOxH-G>D|ci't| =$<|FNI }{V4r0wp@<\]+鍏;'L~TxrT/ iVzpbGG(H=4v[:" ^nhoYM渊XXc)y=Hoz0lhS)#b40)Ӆ XZp>i[#cVξ~(?ׅNS'K5u\ S{ȦĢ~QW Ozx|Rzр%4wm _ ~T0z`^v)@xoOO^ Fmu\zs۸ Ge08#o->$x2>P|=&=<4+UAX°'y-vVï^'oOs[Ҥz`nOnC%ܕ\C*=wb_踀W,]bۍd Rxz8*>[zJe=,Y~fݠւq,C<F}|>k4y疰di!7#'Xښ=5 'D8;qzC)KL޶K`f];. p~%)W*>uZ襬` r\8xMR-\f x;ju=xT#y9+ˢE{Y0Rfayn{ћ2x&(^7ҷ;?nׄ"Gzʳj/az?<_zzEl ?f3A0zI^{4g+9׋^:Ed[W8!Xso~VaԬT >\6+/C^[ߦr+U,uA| =V|~X=0[k>B 81Q=s!^+11PHb< 2h#JN35:}>J=ozX}VbQ!2LmSi -QK⋔z.zۇvCg<klɚTj>}yTw G(fQ+p+/[c//8lj5_VGՕymqY$Vz]mW3zbf E7&hO[w E U 7R"HZ ^ #5{Ky?W%}"b m0Ճ K[cی=0o*T|2w^b'm+-0"L{N[gjm,KuAO]Oqܳhog#kQx.=Jit~Q4$1rk"Tz7Y:'+"Ҿy[w&xbMmÁ[/lYA?]P?FZXi\CFo^J:JozzG-lc|_Z%0|,F9@I~Lƭ{\~|BdHMl+rG6 Q]g$ӣGO2kƖGgmᅢvL FY10#HD~Zs+$/q/!;݁i~O]c5[xQAz<e#&~Af>S#!9<Q zi2ΫVkt;0 7[op~AУ{%QY}r 8Nh#9Mm e5@zNggium_JyOG8@N?A!k-NVVNki mz'XGi$|F~AMaxO._q ?{0p>㇇SZk?k#Et": |)=7~[nF'M}VbTX)jdDžgdjMwO^6݁lqFh,c&9hޑUx& !kܛX]u}͖ w qڴn(8ވ5z^V1I$;`=ۑDɎd zsr+UZ|~:n1͊&8J)q͉4vh9Kvys(M T%S$tĺFM<xk9dq$Ǘ_#08RMXJ(B;&YЉZg7= A1ߦ待*l}S>/ i; Qvtv/~/ӻsҳj<iY HaG>/p2<}Y;O_'^)#<k;BfBuvd *O_?0)$9̴Qq$Bؙ~Y6 s#ajH1~fӸ7}DNѸ)tBصI? 3 [12;m )"ui# +ml3I&cE i XԾ`>=.|Mۿ?EԀr$]l괭0˫]Qqk6V [W9^|B?ߚ'ݵv)=`Y{{:Vr6֑LD ߫)KbQ.ucSi[ OkU[@-Xd;Ns@w墲lDۺoj;]uٟ{MFʱtN3_l-qN%N8[Q?U gj ([onHt/Wӱ `Ydԃhz&/OE(Ґl4V7~8+MwƳQm"pj $0oM]8UĎz< ڃiE0M$=hd7IyyH1$1gt4W w}z7$ƮsspVti2y"򐵬Lɬ[ y;<72 !0 :4h5(u\Wy#5%ws` IcFsWB2b՝10C.53.?]B0&ĆqT-HkI,^Sm9DCnr1 !CĘ1M 7[.- ˢL rU7@FFo #!!0Ĉ4zI e\ؠHADŤ =R# bizw`J xÐ#R<-Hl1+-%eK a~<\LFɃ|"|PlEJIENDB`
PNG  IHDR=GgAMA asRGBPLTEGpL  $7.G # e {}~~&y?I8MH` "l|/"w'xz v 0zB#H$?J` 'T^l %z &М/_s:OgR$ 'vP " xmju +Wze][p1"-7a|<G~?rs()7N .XAV1KC%@b:=@8ӊ/GSEKWl41}!}bŹɯd³mYXJvw,u)'&hf[%nOsjVVVH~~~) EEEfff544rrr׹cP7raGꡠ@qɲѐ.Vd~{DARLkLj,|DN\Z/KfMtRNS- 9? '3JYl|6$NL֋3o`zfAӪ옇i۶yӮ ֪dIDATxKiG4̍{tXQ*-Z+;Ȅ!11\8cXݖ xE"VʵOG.[լ-E".<$dd-d5y)/b\N\^q)erb2ywp0π|0&EXvhxǐ('2 + ~a.h@js^ =*@.6g,7GA~$KxXںON"$4]iVmׇF@T|]k~w=wx:/b8?QhcZ*vtbVW2p4ș"8A跿'qMuEL%a =YZrO1[Uc&`;;W~*+s^/m(>ćɏ4:j]/Fq_C EwZ[ŴeɩpD|| \: [v.1BA;kU姉[Fl ߟO"[0rD6 *jiit GN?r n<΍FwP;6 ݛ _QқO]vjYs/XnM7ڐhŽ#95 bSV;f\[7.pF>EZ(< ji}]#QرPd2Ct\A|D|M'$#E 6 ‹])Fm lS"(x7WizjvqڪKf,]NY74_a"LhtlXاu">h\q߀zE(/gWZjY k- ku&ˌ,[-?d l/r%DjY=(<pREټ^a'>uקSxyuwXLciW#z/0tn ^ Riu|\nx^7S e'{:Mtt5r>pÿ7w68fv…TYm2 p:K&^pf4'vX#&#:<l%-j5LV)/ \eMLy. OQn\ Y͘U@1n"=Tm<<>˚2f9RAeEYwBkNQ'V*V_p8g֌Yse' .U[MzŊ0HO10f$)K`I^2ڪ<о/vfAxĘ-Aw ;. #/;y2ez+40($E@rK[҃"*=`u1ⷬ\/?uoEt#=^+CaLyYl1Ap|C1@ફa*5nk5?Q%y9"َ'^ӆE$!Gy<,a %Z[*=,fJjx`r 4ա@ZW`^L'YMBzpN+.U#I>9'SG˘pǮʏK%J=Zj=esvxG"pL Uz#f)\"ѫ#+#jpA|wH/>> وnzyj*%frّ%ZsrsPl$.=no<ti&7` *%,Ɍ ĕaf(Y},a.lO_~vii`WΥo3_~Gs=8I7{2=#`䨜# sΕ7ܸ#Y<|  A0Kwe~nL̍rB&HV!s!Ɵ?"c πpGP*KKs;gLeu.JToWL!=,Γs ϏOWhGc౎Jv=9a%Z å;`\|Рʕ=w.$ @rc|: hFK) IUشt!0C[X}fH|/5|f>1>zQIGt! [owqJnJ/O-6B R>g|4nTTn) kkv{tW9^jfsPL.8|a` .Tb W]Rc:8+mo}.# kYFTd[EMzDsk[@wM}!g٦MO3I(ݕgGC$! I m|X甏g_ɺWo[ZvqJJu 0 7 Oݓv&dln1/pu}T 7㧊 :{/!Ǎm#xh*=YЯq]Z8hTJ#=E:X?TO˂jK`=m{ge6XS.I_XXl%j|?/A8S͹@oӆ"Grd4AK|+sViQhr/۫o'+R cORcz8@qcFmcuiFf\4$wzQ $[nrڮ@|$MEU}饀^T !oҚz76 nF/x#tCÀAzZ??sVqaw0˲, ea.0x{oC1{u!y%Z3Y(@5H4KkwFIe)<$vf!Dmy0\)=@oauﻱtȓ}+xivw{hU5kԟrcר0kYo=L/c{ӧcLRӱp蚉{K{o/ ;.<97{.t<EV1竣ѳK[zpOzk1@TyR5Fr}p+7Sx7=QGc xayt=w3ć%s&=<]1W{:j=;@9={v>]#ˈ7Se\|*eKuq}sz0LzWm}]#_\\|̚gU+ֵ˝c ye.{7</KY ;-;ٮ}dX2Opc$;FǸk,-^xȟ/>/^s TzzB:Ogv,>b;Ն\e;L~4U3xX(oˇq7}=AL;Tv6+ <+3lbVE@/'><ǣqWjX2=n亮&>`[Ns ^^ q@cl tݟBXƲv=Kod{oV6{g=:bxxk:#x9,@oi)߃ v bkGt7z__|KY3tȎ^?2hq6s^;9:|G~(9 ޤUv"gV9]v *Z ^Rm5 hO~&[~Ǔ@oe7ɼ^3 C41qv`(<'ZH F?jX?|=27^IzZ+/+GJxg,?F0.qtILZd0 ؟mW ?Y _oab^ʃ2'Vv l/W@`Yh0"~9@K#;Kx܄ȆK0~ׅLPzPU^Gy*QEz#?Xbz'4:;>`Uf7a!?շv\BZFrs|A%Dž|f} !eDϒ&:bg M&ՠ?|?L=rᱼ4?zn#hgFfA@H aʎJhjAw2A|+ fEq,ި6*?( *W^м͕`n"9ɮ 4+ ]o7z,o]r+Xqq o#Y[,c,vULHJȲpۢEOd6EЖ5mux=) B}Ṷv\(w6-6Aɫب9V%Eխt,7u8svL]m\4bC~Y U yAgbNt l'(Gώ׷VX_DɜxKT<Dxw xl[=(o+EJ9 ohg%ze5Mu4%/Zĭw/*;hW.@+ ƎcHx4n݉OV;/2S_DĖ(Y]ykV 1TS*ww ٙ dpWXdLhKf;qob5O{">/=!@ X.Q&!:O. BNӪM Wo_Obwxٙ VTmFwD`cq3&˙vvS箄_E6G yC|:"[ V6PuBxx7h=T$2U#ӗJ9 <h n|\>Э܋J*uS% 4 Dh&״x <I)ί 2B!TlIaZ5 \R$-hvlD3Z MύԧFZ_ƴM"xfHKAI @hS ?^Mt]Ja~ 5'|\, W$jQ> l9.T?C3QЭg'5I2x_nMLBh@fLlzbVKȎj,_*={t?}?Çid5ph e>ZtvnLnKZUSI$'@)59`DLC|3nROi7&K\Y8۽5XMO#! Cr&Qg_݃ے7SĬi~^'躘+b@|=T4JZJDf1".9 eeExLͳ@uUW]/ɂ'dfҳ%zmqHw}`6PWp$7Ў!йG;D Bsmgm,4\EKidj~l 0H"!QXf>7@߀^SM:f4wR?Bl%z+M!Y*t _C9#C ~.@3z @K i s|V:mTIgh >z/o抢#)3=aw2A;3@6V PXۥuc] xoA+:1@s)ɾj&`~@K8 U'O3;:rW=.%IE/?m K 0Vڵ x5l Co2hŅExnvWۚF-\nki֖, vb`<$K$nߢ:|y>Hy\եdZP\,yM.& >۸MA.=_|.'ܓm=B <^||X)WZpø* ^E O\4{ ~#x-v5 $@.Ւ;>N xr|8+լN OR xx( KZ:7&.)W9BP(yѱ\>SYM(jx#& 1m'MxN8Yw9dz?fI1. Z b q9" r?+ ]{լi4t4^P+~ 40UI`)n̋0/bcϔ=8YTPZIbd}BGjm1NyQcz<RN.iE1;|5Ւɕ՛R: 53BF)U^8"06 ^9OǛԷ"_^h{lJrC⸅":؂0 gTEӲc tX!!@|j t߿ɲ" [F獇aq6)ZH\3iAw/nx0_纑+Ua!P|}[aQt\FL7-̚%U'ũhx0>Ĥ7<b͂^X SU!rsNac: c>8fAH@=qzҞ]Ћ [n,98ZYx=1 5/nvdq`&1b ?XcvөG!]N)L*ꁯI#,mMu|pk[4IZ͂j} +>#>=;"^f" $I`lF4 K|Z"`X}긺gp{wv9"Z<9=}GH䂹''BzG鑁o]̳q㎬%59^98zq=wmQ{AG{ľ;H5^PqcRCzE'4:}zC\^{|k}hén`{g{~l<yr,Hh8sCVtҋ 7w6v{rg˧_ݽӭݗ];xr;>݃NwoMz1{p8y*?&D[w{9t:gggvW*%;;;_ܻq;0ӛaMu #aU3I}=ƽ8d 6_߼%ڿ}I֭v^ȥl{l H_MUؼY|fq3z0ՠJ d`w@r?twVyo6YKSNJ z0KWE03 PHGhTR |Aj= tEKhJ&>[`8R! u# dUa|M(J0րh5Xc+ D'StD\ZzB¯Jf?~Ɯ0p=>,2Ĩ'(8B];u|% _IS{຅TsY1] ͿǷp0ĥQ݈}p C/>Pz1U'7" ˗Հ3%)n5;LQwS40 ղf"@:-<0{ `xǫb:BmĮfP;p<&_çs Od$qL&a9Z mՌWך)<<L ==8=紁 ts81Rx3k-֦ eGٶf=#dSkOKNV1{0A pe]4VN/^HW9|<丘ey,[ \wsOLz OTqbelI_-"FYUZov&6 %D‡/@O^R -`W爙ASVO =7mp4$AP+WbΤC\l\FhgU3$ rs]ôbł`8f$I͚Q#*İOsCY?ȀX.[[NX!g؛Z*è$*FNdA|J_bX1 ^ð$ ϊ&S^Ff#VQɴ#c1At$8 $xtkKa@(ST!#) <iȬ /kVE {nEKsRңǔTlMpJd 6#E$\۬)B!ǿ`Ǥ<ǰxNd2OՈAߦ8 6T=f$I o{Oqt#sI8M8ʔLh=nY QGnv*ճ&q? ryy0%ۣDw?vU4ŸPs!7djƗ@&O1IB$2A<Ā0ɕ7g :(NpL65c,OH1 t濶"_dacْPǧEZx2 IUUī3@;<!v*> ^,F<>脧tp8WDOOd9.U"A /vgF[v&.DOؾ&`IR~>,=\D&A`0(|ƹn@{> -?v/mdkj*-,K_0(a`0$Y%$s1FPTH\u-nXXX{v[Vq9g&3dfٓF<VwZm⇹2ۼ(Vr-F~ZWeJ+y]>[V}<ܧK_W/nvt*d%uDuNwʕ+b,S]9{ ϖ+ KzZ}<ߕkڨ _X.#nGA[]^gUڍf#B~mһUJB5][}z=3<\gVaX 1 dp״#羮<F&- x/yt*2\%'vF4#ZQ,=0`,Z"9emL/hH}<6]<W|FrhoׯP:M'mxo4J*IғClFgצS~5BII`g h ٥GN{.p e!:8'zUHFz]׼70עBЈ\^28&#4}7;|h1CR]: [/=O!8^)TlCn봌yck04#T$΀S|?*a ><h =Z <G!V( &Ep|4ZKOIrq17J@G|c5s{mmY%77)g.m4 "ϥefŜ0cMLwA@#HI; a9lHWVWlC/bk|1kznq/Ϳ#cJ_u@LA  ԖrR L@*_ؗ6-lkL "4܅\* 0BzOehz"]P {NmC@/wThB.7n~/{^]?&84۝6i4b 95ˬ-tȦ"J ˠ?q}}s\jP̼#4fg }Ml-@XdrG mԀ)8njďW6WҨѾ<BFhϴ5ܴ,)r)MF KX`dJ[iR)3|X䬃)]{ziYʥ\BrӹLd[Y:d- >/=sH#42sXܧw.ω\Fp<K3n/]&zJۥQS@z+̴A-1]B“M- 5|}#=_K}/^.K\ӈfemy{`]?Yz^S9~aO#T X1ӽxq<-fʭ| ah ]IEE Qz=ަ{4-*@oySnStI@zТW};c؏9mɅD\LD% 5 {s4H{dL)Nm 43l*(^t L`/Ȣ˙jc_RdHӤy0|1ͭ!=9 $zbLiwE/~|/||3VQ8V #~L|tޞ af2ŔPre_mn<A1hfEtwĤh ћ%Ƿs5Eon2x*4~{>ɻw,؉m VON_ $= Cc 3sNwh[xT2Wٞ;%q}vٛ`*ix0(BjU|P8(tFp(_iSj^TM!=2\mn?[~=Z 6R3एp_MFmxًeBΟ:<.u C$Yt?/[$j ANjҗ&z{!9v.)ޖ>T~󕭔fq完E߂0%IOj(.NH|Y|M[X izRB2:F|bS1mEgsF4%axKjLWgzIA|f=e3>L[$Fǡdeö.7נ$=a(nPrl>htT?hH,m1n/H̆eƧ'3==MI/A)],qdPňqBN >V{Do/ |t^ڽTr#xO>-@_R;]:]Ct˭cNue{-/lK~ =qB1w`b򕭔 DDM7KRӪ0Q# q[Ywa6~oyyOKئ?N &O! ?)oU"Q~E{FC|tYQ^R2 Ll"Zhm+yEЏ 7,Zzw* E•H9{钞H.!sTQRO:hoayS\!|Ώ3Rhn/3>7U*Qjϱ#h/=#l"ˍ)ꯅ_B^,|&DQ}-kTi^~v^M\%|4G̖ a>14c !>=vy <\Yzmedo1]"Lwx[kCO^ ='퉸Ev{a?94#\~]Br(6uu{mԄ~b =nY,|;zs Z;AkGoJB,Yv^a<|{*H_6=w~]L-»ND_2XWv]gEO! uzI0hTTDl# W,K6y.Vˀ _Z, 㶮cԝ?BZ1A6E'Y"! yiƠyThDVGj)DF(c{νq<&6Ϸ{9S@!a@w>e) ]`^x{;X5ᣝ*/zx01b8Sx4ќKLJ{CcT'vK{:M%3C_𽚞^3q=)y;<>fʫ 9YrYF!g]NDAquPzW.]H81Um=Ѩ/nBϱ .8gb c;|{uzf~5VVkCz=:@DC1sÕږsImȢCoxAb(.zlek`mui$DTnmfowۢD.afƋv{Y0wqqV-$Z&.iN躌\^A<=|bngt؜N'4M89esc%*Y2^qOiг{h D|}}7M#MǓMGtjSMK/?~'u3eV$'鵷cG>{yK>%Ǜ0w,HkZ4x~<DmA̞G|A@U I}gE&=/PzzH1m{wu0M|)U'Jc>r>赵|}ңg&D_&͢{iލl;Xcscs&Oqn]vQ|)^+MI^N2Bi^~b2yc"|x"g`wzz;HҒy^W],J ς(%+U٬mVK &@67>sFC>sv!W\!,{waA1UFgs4{ W%,Iw(Qbd~bG(<qYw.,嬧 z _o Jz}k}}~E,E4ׂ1q>E|R:s*ѽp'R.z:ozcHPuūt=z'n`=)frƥ(P^~3鳢E@;l~.(_쀹[Yk j)ts]c$ ѓуξfJݹH kWjx*ו0> p\87ȩ4pgc[7K':dCEXM3-=*|3aÚ֭6(B-Ӕ6-=o}li4sE$I(rqg)gqKY> zN0zE0^kWzg>s4Ckr2?s8=A6dΗ,/rTg؆|u¾׈ie,퐼S-z=Gߟ7;NۙEN<Gz?6n$jd?=NHzӳ#щ #iadmױH/Gd4TPvF>ؘ<uϨ^ r1-7)p;*ָ'+o7d;t\HIݸ`hR:N3zr|& SWu$baL0{؍:b߰C }7kx2L!Ž%Aꥫ<M50^^ҖǣkO1XrjNt8O |S|TrPܬ6+BRnju&X*ˋN堐_TV*+aT*|rAO-Vwv*+fъʠSy lHpr|!ʖ"R;Ki7A{޹tpBXIQ.(x4dH5,†P =rg~t^N1@.~g)]|+Jb0̧e:V:e|$jJ;HwLP5fG_YOK f1وB^W ͲUc^Xo:x Жy.*[m\-Or@ /C<mMIJ_]l)d!;Sfxeɇ/\,G©vJ$J9e],3 Bu{Jl@ن߄67U:"Xr 3{ݑX6%OT]'*8jP6-ɋ6mSŝ METLPXBfj0)dK@dR.P*.^58%$ݿvzzh+ھ4(>^ONGUx^+*TU1 Yʊ\JC]/($|;GYe瓾gDz!+TWo8M}!'/ ::ܢR8UKO6%mX 2.ճZ<[ 6HĤ)X ZڦF$+i"["~7tmEs͡}g-  "jDׁݩ̓u JLk<fN:ȱtN|CVDыBo]r_{{pTW\n(GhB%8(~ zC!ᕕx^jD1w֜2e& 3 tUwG>SLG' JfQk!z>c~C_N1?$j=b*b pٚ!eXupK9Jv4Hz¢]TJ7NXB&z߆,§]/'aMˬnORUlǙFҔ% ze)eVf0,\'D`E:FDg"w/c Jr?B/LO)7y*$Gz8Ϊ^m]Ҫ7}z|)Y.\KƖEb:`1Kv4 cDŽKDX;KH msfΌ_Ȯ=F1O</62V؉B A~7"c6V|fu\ |XOI6|!`čG" қ0vi0>Q6 faVzTEU5%M>L{gg-Uw;.>Uo (f=*|]Q8…70<C{OLv2>K;{3%"*pX4xjO. b6s)?ʲΪf|wa,K?̬#zﰞb* kI/kI2CY')$"se|{9 z25Jv!_2T&=mvTb'@:rgᣀ=+>)ݵ-MfB7`W ʣSM*ײQ KYQH|a6nZbHBi5333; @$5 #.pO8="d7yܽOmi W5MurJŐ}r,ǃNXec!qS̓=1c-Lx Dw=a_b[jrUwxun) ?%uh[v_a25f x-_(sHt>cQ>(|73S(ndz#ydķ.79-sG1i\Ukc}}ܑ\e` w3mo÷b?߶ݎYt G Äw"ynﶏ.[xlr,c+<{ڇgKtgX 8XzߨEkg$3Y@~րzdoWh .'ϟ;xcII\rz2? zڤݒW8U9e9zZҫNޖv/yߥxAnmc !6 ^,obYG D ܾfk~&~W{h{-tXb`:==G#x=7$z\X&]M1^IFRvL@첪owݕ1o6.ı<8K~KQj/0=|@-x?Pkң}IqGN 2GS ƌc_#L{o&~e cw.~2? vL fyOh6[fRqp [;B^ ݺ,-U~ݿx3caYBxu1vSgᅇH|{䀧 z-g< Pu[Od/>FgsTkwhEtܛ2=,,iLfmͤbB:E. [,2<3/gLixsCeUfR?zL+\n/!Fy^R[[{f }+0bJm/3c(ˡ i=W6Wilrj׸GŻHUGWBz]+BxX C7"z2/H{Zmܲ_ZqMwGqQ1JI:Wǐ/C}#%GeOO(ƧW=D7-z6*^r]#m=Y㇣=RՒNej-h$tt7+8yb:*gLڡvk o|ēēm)!%zQapާ_%OhWjh0.oKrZr1EqeHR=-z 5Tqf60%ot*.g3ZN~v[FK ?dM%rgmKؼrE-5OF1AʪX0KY U<j`q?Ͱ^'4?_;Bgk686vC -e)t;r](˒A`GcwhXYP@}wARgM'СПf^0Dh3VRj%K~ /Kf72qվ$ޠŔ7zKt"7Zx! [k2Vh]TNnKGS!! .Zj_rusH 5r:GWo.Z!(6k-3\z,k~ #G06s &y5)]C" ": 'K|&\$L*Q+8 ^wbp6Ce }0|hYeW7azm_Mc=M/0|>]|e9L/hkD0;ASF9!F5 Ž L"~Nӛ ^>8i'zL[7\87['&sDSz~Ҟ)PĮ5t;Ӧ<Is9nr%Na>xu^)ɰ?q<NpЃV"Je><qx<U'Q%]< e3@S.;2je $t'73z'4p6e?LuVq1yܽS+d8磏gf@7>_@Bh-Flqa}{mMq+DG"tqd1{kH,0$?_p=:-28\h kPZ< RԲT&j[c`2=e g"ѣH,r9g 4 ujV^/ x@hӞE~i~8Ͼ"c]1_|իVmYk@Hbq$Ք,TK%D^c4=I}>UNw\{&Cl(un7Ç߼yÇNOO߽{ L*jC:JՑZ-ف > IИ#_4_~CM|~n]MWۦ4j*izhcF[,<= G# ,iY*Yl㰾uz9'}͛7׉|?s<x{0yoIdb 2ɩݫWAn \B<L?e .Tz"8ej*z^ݻn( uՁ?;=t@dpEoz SQ7bS@`-aQ˸TOFJ۷ *զJj+I[տL$%`_@ < .)=LCEzbMEEdwT߿~ߠ{oit|~Ӄ[T.tb dCϮHy8DK;ۍJܴ <4+fdj݇o~xarGoz=K:X*|%"Xl"",R4]{m[(kh( ײy^1X0= w;"݃Ite79C/bea/X1` m 7=T?siV!5$7PAMd)R\az=WyŦ)hã= ?®(,9rz`i-Kb7 P`a>( ϙyna-16㬦 (ba_M@($%ZƑ^M;_=21wull`^V@E&,/i>$:7=PEbr _y<!y(sZ%0^deYXOÏ_l% NJ97bjl!@zb8J_Y>@%9˵H@~ \hv97@R|_j@z9G TnPv Z Lg͍D¡؟$fhRZ`MOe CW\AA-ON|* B6(E!Kat> br"S"1b,p҃lh9;j`q7?wdT ~ߠQ@ J?  ?ϦgTUq?g*tpWvVvb +þ >yRW;՝^|W"vIuQq Ѿy>/Ge Bl1_JrD(mYVwbP?_j{1tM9U{0_]uV]H.ϭE?@|6 2"?h=,>}YjnA@1|Ji3Y`}[(tAbN%PW׶PYTO'UuNlUfcI@o\wXf nY8z(HϬ-[{VS3JF @t[bBNяna1x6wsf-Eg]$R\AV<ͥ2Q @=K?H$$^|VJP:[PN ub,%Zt]!|k33F 6gh禳 OD|C]yB8n&~cාS'6ɇs,T<|"ėـMIGx/<!v Õ[H=]D0#773s_h9kwڭboF#L)@y F;KԭDby1"FǞV;t}g0J㞓] ឡ~/5mZQCϗZXt/7MLn "*;w(Ɨw#@J^T՞Nabh-2" v Ƃ-L/͊h|>vz:]O(Dǐׂ%P \PuIsډWNsB'‘h _W;D/2ADŝ]: R?4{ ^Aw> &  _ ٩ u?R0;x";sG]ơq¸2;Lx'i޾7&Kg Kz Zs73q. :>7ŭ*ur˯'VOZ( ^ @.ˎi7b|,x ]CƩ%>RU$q3Z?p7@@`!Kib/VG?lW/{mroXڍO'&l@ģtk,vbl|=C' У/=};^mzTKa[ۻPd4~2v7cR%FukzlEϵmك1<n :;=ձ,iӔj;G&PZ?@x4 7[İR48= >* SG]VģztGvb< l| ##NMNL}ԳҪ<<LJg7gĢw`5:/Ng_C@6/v{MXDxO wBA@c?ov8H\t\4ݳv(e)20:a|gNꃥN99懸y@wcA/4'IZ$)]T:ۇۻ{@=/|$;w*T^giiXh"2Mr7L< ɩۖ'#zʧۧ-eH fO'"U<BؿyK x~|H 覦nLEsTK\ ww%+<~uK/%vB : ;/Ҽۯ(`6{'8>MqƧ=Qez76+'ehHq=r.mdYwI(@mӄJ`UW+bHV3 M `Л7sʏ<$y{O]ח1ϭwrߞ>;葳h$l淧gU~2>3<anE[{n'FUX8&}3<Jo﫫ѣ,g'ӜKNrxSуiG32w>䧅޿$z'`'3KExD[{#|ECǏ7<;A4ƞǧ_?׸Uzc|P @UL =jx-ʯPioGgw_5Q3-j'<1c_~D'1*5$x$v`Fnqo-*^X{7xߏ4 0? Oblž%zWTV~JG}\, _z >֏9'A$? ߞ0x:8a9n{j"g5wb~~a1k3#ڃQGG Q,cC;>>HƇI=+<Qw^z.~7ޘ!U">,|~'Ə{o-JK7ʀy9n/jGzL)w5DOxH-G>D|ci't| =$<|FNI }{V4r0wp@<\]+鍏;'L~TxrT/ iVzpbGG(H=4v[:" ^nhoYM渊XXc)y=Hoz0lhS)#b40)Ӆ XZp>i[#cVξ~(?ׅNS'K5u\ S{ȦĢ~QW Ozx|Rzр%4wm _ ~T0z`^v)@xoOO^ Fmu\zs۸ Ge08#o->$x2>P|=&=<4+UAX°'y-vVï^'oOs[Ҥz`nOnC%ܕ\C*=wb_踀W,]bۍd Rxz8*>[zJe=,Y~fݠւq,C<F}|>k4y疰di!7#'Xښ=5 'D8;qzC)KL޶K`f];. p~%)W*>uZ襬` r\8xMR-\f x;ju=xT#y9+ˢE{Y0Rfayn{ћ2x&(^7ҷ;?nׄ"Gzʳj/az?<_zzEl ?f3A0zI^{4g+9׋^:Ed[W8!Xso~VaԬT >\6+/C^[ߦr+U,uA| =V|~X=0[k>B 81Q=s!^+11PHb< 2h#JN35:}>J=ozX}VbQ!2LmSi -QK⋔z.zۇvCg<klɚTj>}yTw G(fQ+p+/[c//8lj5_VGՕymqY$Vz]mW3zbf E7&hO[w E U 7R"HZ ^ #5{Ky?W%}"b m0Ճ K[cی=0o*T|2w^b'm+-0"L{N[gjm,KuAO]Oqܳhog#kQx.=Jit~Q4$1rk"Tz7Y:'+"Ҿy[w&xbMmÁ[/lYA?]P?FZXi\CFo^J:JozzG-lc|_Z%0|,F9@I~Lƭ{\~|BdHMl+rG6 Q]g$ӣGO2kƖGgmᅢvL FY10#HD~Zs+$/q/!;݁i~O]c5[xQAz<e#&~Af>S#!9<Q zi2ΫVkt;0 7[op~AУ{%QY}r 8Nh#9Mm e5@zNggium_JyOG8@N?A!k-NVVNki mz'XGi$|F~AMaxO._q ?{0p>㇇SZk?k#Et": |)=7~[nF'M}VbTX)jdDžgdjMwO^6݁lqFh,c&9hޑUx& !kܛX]u}͖ w qڴn(8ވ5z^V1I$;`=ۑDɎd zsr+UZ|~:n1͊&8J)q͉4vh9Kvys(M T%S$tĺFM<xk9dq$Ǘ_#08RMXJ(B;&YЉZg7= A1ߦ待*l}S>/ i; Qvtv/~/ӻsҳj<iY HaG>/p2<}Y;O_'^)#<k;BfBuvd *O_?0)$9̴Qq$Bؙ~Y6 s#ajH1~fӸ7}DNѸ)tBصI? 3 [12;m )"ui# +ml3I&cE i XԾ`>=.|Mۿ?EԀr$]l괭0˫]Qqk6V [W9^|B?ߚ'ݵv)=`Y{{:Vr6֑LD ߫)KbQ.ucSi[ OkU[@-Xd;Ns@w墲lDۺoj;]uٟ{MFʱtN3_l-qN%N8[Q?U gj ([onHt/Wӱ `Ydԃhz&/OE(Ґl4V7~8+MwƳQm"pj $0oM]8UĎz< ڃiE0M$=hd7IyyH1$1gt4W w}z7$ƮsspVti2y"򐵬Lɬ[ y;<72 !0 :4h5(u\Wy#5%ws` IcFsWB2b՝10C.53.?]B0&ĆqT-HkI,^Sm9DCnr1 !CĘ1M 7[.- ˢL rU7@FFo #!!0Ĉ4zI e\ؠHADŤ =R# bizw`J xÐ#R<-Hl1+-%eK a~<\LFɃ|"|PlEJIENDB`
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 reverse_words(input_str: str) -> str: """ Reverses words in a given string >>> reverse_words("I love Python") 'Python love I' >>> reverse_words("I Love Python") 'Python Love I' """ return " ".join(input_str.split()[::-1]) if __name__ == "__main__": import doctest doctest.testmod()
def reverse_words(input_str: str) -> str: """ Reverses words in a given string >>> reverse_words("I love Python") 'Python love I' >>> reverse_words("I Love Python") 'Python Love I' """ return " ".join(input_str.split()[::-1]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Program to list all the ways a target string can be constructed from the given list of substrings """ from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: """ returns the list containing all the possible combinations a string(target) can be constructed from the given list of substrings(word_bank) >>> all_construct("hello", ["he", "l", "o"]) [['he', 'l', 'l', 'o']] >>> all_construct("purple",["purp","p","ur","le","purpl"]) [['purp', 'le'], ['p', 'ur', 'p', 'le']] """ word_bank = word_bank or [] # create a table table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for i in range(table_size): table.append([]) # seed value table[0] = [[]] # because empty string has empty combination # iterate through the indices for i in range(table_size): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word] + way for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(word)] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
""" Program to list all the ways a target string can be constructed from the given list of substrings """ from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: """ returns the list containing all the possible combinations a string(target) can be constructed from the given list of substrings(word_bank) >>> all_construct("hello", ["he", "l", "o"]) [['he', 'l', 'l', 'o']] >>> all_construct("purple",["purp","p","ur","le","purpl"]) [['purp', 'le'], ['p', 'ur', 'p', 'le']] """ word_bank = word_bank or [] # create a table table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for i in range(table_size): table.append([]) # seed value table[0] = [[]] # because empty string has empty combination # iterate through the indices for i in range(table_size): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word] + way for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(word)] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-340,495,-153,-910,835,-947 -175,41,-421,-714,574,-645 -547,712,-352,579,951,-786 419,-864,-83,650,-399,171 -429,-89,-357,-930,296,-29 -734,-702,823,-745,-684,-62 -971,762,925,-776,-663,-157 162,570,628,485,-807,-896 641,91,-65,700,887,759 215,-496,46,-931,422,-30 -119,359,668,-609,-358,-494 440,929,968,214,760,-857 -700,785,838,29,-216,411 -770,-458,-325,-53,-505,633 -752,-805,349,776,-799,687 323,5,561,-36,919,-560 -907,358,264,320,204,274 -728,-466,350,969,292,-345 940,836,272,-533,748,185 411,998,813,520,316,-949 -152,326,658,-762,148,-651 330,507,-9,-628,101,174 551,-496,772,-541,-702,-45 -164,-489,-90,322,631,-59 673,366,-4,-143,-606,-704 428,-609,801,-449,740,-269 453,-924,-785,-346,-853,111 -738,555,-181,467,-426,-20 958,-692,784,-343,505,-569 620,27,263,54,-439,-726 804,87,998,859,871,-78 -119,-453,-709,-292,-115,-56 -626,138,-940,-476,-177,-274 -11,160,142,588,446,158 538,727,550,787,330,810 420,-689,854,-546,337,516 872,-998,-607,748,473,-192 653,440,-516,-985,808,-857 374,-158,331,-940,-338,-641 137,-925,-179,771,734,-715 -314,198,-115,29,-641,-39 759,-574,-385,355,590,-603 -189,-63,-168,204,289,305 -182,-524,-715,-621,911,-255 331,-816,-833,471,168,126 -514,581,-855,-220,-731,-507 129,169,576,651,-87,-458 783,-444,-881,658,-266,298 603,-430,-598,585,368,899 43,-724,962,-376,851,409 -610,-646,-883,-261,-482,-881 -117,-237,978,641,101,-747 579,125,-715,-712,208,534 672,-214,-762,372,874,533 -564,965,38,715,367,242 500,951,-700,-981,-61,-178 -382,-224,-959,903,-282,-60 -355,295,426,-331,-591,655 892,128,958,-271,-993,274 -454,-619,302,138,-790,-874 -642,601,-574,159,-290,-318 266,-109,257,-686,54,975 162,628,-478,840,264,-266 466,-280,982,1,904,-810 721,839,730,-807,777,981 -129,-430,748,263,943,96 434,-94,410,-990,249,-704 237,42,122,-732,44,-51 909,-116,-229,545,292,717 824,-768,-807,-370,-262,30 675,58,332,-890,-651,791 363,825,-717,254,684,240 405,-715,900,166,-589,422 -476,686,-830,-319,634,-807 633,837,-971,917,-764,207 -116,-44,-193,-70,908,809 -26,-252,998,408,70,-713 -601,645,-462,842,-644,-591 -160,653,274,113,-138,687 369,-273,-181,925,-167,-693 -338,135,480,-967,-13,-840 -90,-270,-564,695,161,907 607,-430,869,-713,461,-469 919,-165,-776,522,606,-708 -203,465,288,207,-339,-458 -453,-534,-715,975,838,-677 -973,310,-350,934,546,-805 -835,385,708,-337,-594,-772 -14,914,900,-495,-627,594 833,-713,-213,578,-296,699 -27,-748,484,455,915,291 270,889,739,-57,442,-516 119,811,-679,905,184,130 -678,-469,925,553,612,482 101,-571,-732,-842,644,588 -71,-737,566,616,957,-663 -634,-356,90,-207,936,622 598,443,964,-895,-58,529 847,-467,929,-742,91,10 -633,829,-780,-408,222,-30 -818,57,275,-38,-746,198 -722,-825,-549,597,-391,99 -570,908,430,873,-103,-360 342,-681,512,434,542,-528 297,850,479,609,543,-357 9,784,212,548,56,859 -152,560,-240,-969,-18,713 140,-133,34,-635,250,-163 -272,-22,-169,-662,989,-604 471,-765,355,633,-742,-118 -118,146,942,663,547,-376 583,16,162,264,715,-33 -230,-446,997,-838,561,555 372,397,-729,-318,-276,649 92,982,-970,-390,-922,922 -981,713,-951,-337,-669,670 -999,846,-831,-504,7,-128 455,-954,-370,682,-510,45 822,-960,-892,-385,-662,314 -668,-686,-367,-246,530,-341 -723,-720,-926,-836,-142,757 -509,-134,384,-221,-873,-639 -803,-52,-706,-669,373,-339 933,578,631,-616,770,555 741,-564,-33,-605,-576,275 -715,445,-233,-730,734,-704 120,-10,-266,-685,-490,-17 -232,-326,-457,-946,-457,-116 811,52,639,826,-200,147 -329,279,293,612,943,955 -721,-894,-393,-969,-642,453 -688,-826,-352,-75,371,79 -809,-979,407,497,858,-248 -485,-232,-242,-582,-81,849 141,-106,123,-152,806,-596 -428,57,-992,811,-192,478 864,393,122,858,255,-876 -284,-780,240,457,354,-107 956,605,-477,44,26,-678 86,710,-533,-815,439,327 -906,-626,-834,763,426,-48 201,-150,-904,652,475,412 -247,149,81,-199,-531,-148 923,-76,-353,175,-121,-223 427,-674,453,472,-410,585 931,776,-33,85,-962,-865 -655,-908,-902,208,869,792 -316,-102,-45,-436,-222,885 -309,768,-574,653,745,-975 896,27,-226,993,332,198 323,655,-89,260,240,-902 501,-763,-424,793,813,616 993,375,-938,-621,672,-70 -880,-466,-283,770,-824,143 63,-283,886,-142,879,-116 -964,-50,-521,-42,-306,-161 724,-22,866,-871,933,-383 -344,135,282,966,-80,917 -281,-189,420,810,362,-582 -515,455,-588,814,162,332 555,-436,-123,-210,869,-943 589,577,232,286,-554,876 -773,127,-58,-171,-452,125 -428,575,906,-232,-10,-224 437,276,-335,-348,605,878 -964,511,-386,-407,168,-220 307,513,912,-463,-423,-416 -445,539,273,886,-18,760 -396,-585,-670,414,47,364 143,-506,754,906,-971,-203 -544,472,-180,-541,869,-465 -779,-15,-396,890,972,-220 -430,-564,503,182,-119,456 89,-10,-739,399,506,499 954,162,-810,-973,127,870 890,952,-225,158,828,237 -868,952,349,465,574,750 -915,369,-975,-596,-395,-134 -135,-601,575,582,-667,640 413,890,-560,-276,-555,-562 -633,-269,561,-820,-624,499 371,-92,-784,-593,864,-717 -971,655,-439,367,754,-951 172,-347,36,279,-247,-402 633,-301,364,-349,-683,-387 -780,-211,-713,-948,-648,543 72,58,762,-465,-66,462 78,502,781,-832,713,836 -431,-64,-484,-392,208,-343 -64,101,-29,-860,-329,844 398,391,828,-858,700,395 578,-896,-326,-604,314,180 97,-321,-695,185,-357,852 854,839,283,-375,951,-209 194,96,-564,-847,162,524 -354,532,494,621,580,560 419,-678,-450,926,-5,-924 -661,905,519,621,-143,394 -573,268,296,-562,-291,-319 -211,266,-196,158,564,-183 18,-585,-398,777,-581,864 790,-894,-745,-604,-418,70 848,-339,150,773,11,851 -954,-809,-53,-20,-648,-304 658,-336,-658,-905,853,407 -365,-844,350,-625,852,-358 986,-315,-230,-159,21,180 -15,599,45,-286,-941,847 -613,-68,184,639,-987,550 334,675,-56,-861,923,340 -848,-596,960,231,-28,-34 707,-811,-994,-356,-167,-171 -470,-764,72,576,-600,-204 379,189,-542,-576,585,800 440,540,-445,-563,379,-334 -155,64,514,-288,853,106 -304,751,481,-520,-708,-694 -709,132,594,126,-844,63 723,471,421,-138,-962,892 -440,-263,39,513,-672,-954 775,809,-581,330,752,-107 -376,-158,335,-708,-514,578 -343,-769,456,-187,25,413 548,-877,-172,300,-500,928 938,-102,423,-488,-378,-969 -36,564,-55,131,958,-800 -322,511,-413,503,700,-847 -966,547,-88,-17,-359,-67 637,-341,-437,-181,527,-153 -74,449,-28,3,485,189 -997,658,-224,-948,702,-807 -224,736,-896,127,-945,-850 -395,-106,439,-553,-128,124 -841,-445,-758,-572,-489,212 633,-327,13,-512,952,771 -940,-171,-6,-46,-923,-425 -142,-442,-817,-998,843,-695 340,847,-137,-920,-988,-658 -653,217,-679,-257,651,-719 -294,365,-41,342,74,-892 690,-236,-541,494,408,-516 180,-807,225,790,494,59 707,605,-246,656,284,271 65,294,152,824,442,-442 -321,781,-540,341,316,415 420,371,-2,545,995,248 56,-191,-604,971,615,449 -981,-31,510,592,-390,-362 -317,-968,913,365,97,508 832,63,-864,-510,86,202 -483,456,-636,340,-310,676 981,-847,751,-508,-962,-31 -157,99,73,797,63,-172 220,858,872,924,866,-381 996,-169,805,321,-164,971 896,11,-625,-973,-782,76 578,-280,730,-729,307,-905 -580,-749,719,-698,967,603 -821,874,-103,-623,662,-491 -763,117,661,-644,672,-607 592,787,-798,-169,-298,690 296,644,-526,-762,-447,665 534,-818,852,-120,57,-379 -986,-549,-329,294,954,258 -133,352,-660,-77,904,-356 748,343,215,500,317,-277 311,7,910,-896,-809,795 763,-602,-753,313,-352,917 668,619,-474,-597,-650,650 -297,563,-701,-987,486,-902 -461,-740,-657,233,-482,-328 -446,-250,-986,-458,-629,520 542,-49,-327,-469,257,-947 121,-575,-634,-143,-184,521 30,504,455,-645,-229,-945 -12,-295,377,764,771,125 -686,-133,225,-25,-376,-143 -6,-46,338,270,-405,-872 -623,-37,582,467,963,898 -804,869,-477,420,-475,-303 94,41,-842,-193,-768,720 -656,-918,415,645,-357,460 -47,-486,-911,468,-608,-686 -158,251,419,-394,-655,-895 272,-695,979,508,-358,959 -776,650,-918,-467,-690,-534 -85,-309,-626,167,-366,-429 -880,-732,-186,-924,970,-875 517,645,-274,962,-804,544 721,402,104,640,478,-499 198,684,-134,-723,-452,-905 -245,745,239,238,-826,441 -217,206,-32,462,-981,-895 -51,989,526,-173,560,-676 -480,-659,-976,-580,-727,466 -996,-90,-995,158,-239,642 302,288,-194,-294,17,924 -943,969,-326,114,-500,103 -619,163,339,-880,230,421 -344,-601,-795,557,565,-779 590,345,-129,-202,-125,-58 -777,-195,159,674,775,411 -939,312,-665,810,121,855 -971,254,712,815,452,581 442,-9,327,-750,61,757 -342,869,869,-160,390,-772 620,601,565,-169,-69,-183 -25,924,-817,964,321,-970 -64,-6,-133,978,825,-379 601,436,-24,98,-115,940 -97,502,614,-574,922,513 -125,262,-946,695,99,-220 429,-721,719,-694,197,-558 326,689,-70,-908,-673,338 -468,-856,-902,-254,-358,305 -358,530,542,355,-253,-47 -438,-74,-362,963,988,788 137,717,467,622,319,-380 -86,310,-336,851,918,-288 721,395,646,-53,255,-425 255,175,912,84,-209,878 -632,-485,-400,-357,991,-608 235,-559,992,-297,857,-591 87,-71,148,130,647,578 -290,-584,-639,-788,-21,592 386,984,625,-731,-993,-336 -538,634,-209,-828,-150,-774 -754,-387,607,-781,976,-199 412,-798,-664,295,709,-537 -412,932,-880,-232,561,852 -656,-358,-198,-964,-433,-848 -762,-668,-632,186,-673,-11 -876,237,-282,-312,-83,682 403,73,-57,-436,-622,781 -587,873,798,976,-39,329 -369,-622,553,-341,817,794 -108,-616,920,-849,-679,96 290,-974,234,239,-284,-321 -22,394,-417,-419,264,58 -473,-551,69,923,591,-228 -956,662,-113,851,-581,-794 -258,-681,413,-471,-637,-817 -866,926,992,-653,-7,794 556,-350,602,917,831,-610 188,245,-906,361,492,174 -720,384,-818,329,638,-666 -246,846,890,-325,-59,-850 -118,-509,620,-762,-256,15 -787,-536,-452,-338,-399,813 458,560,525,-311,-608,-419 494,-811,-825,-127,-812,894 -801,890,-629,-860,574,925 -709,-193,-213,138,-410,-403 861,91,708,-187,5,-222 789,646,777,154,90,-49 -267,-830,-114,531,591,-698 -126,-82,881,-418,82,652 -894,130,-726,-935,393,-815 -142,563,654,638,-712,-597 -759,60,-23,977,100,-765 -305,595,-570,-809,482,762 -161,-267,53,963,998,-529 -300,-57,798,353,703,486 -990,696,-764,699,-565,719 -232,-205,566,571,977,369 740,865,151,-817,-204,-293 94,445,-768,229,537,-406 861,620,37,-424,-36,656 390,-369,952,733,-464,569 -482,-604,959,554,-705,-626 -396,-615,-991,108,272,-723 143,780,535,142,-917,-147 138,-629,-217,-908,905,115 915,103,-852,64,-468,-642 570,734,-785,-268,-326,-759 738,531,-332,586,-779,24 870,440,-217,473,-383,415 -296,-333,-330,-142,-924,950 118,120,-35,-245,-211,-652 61,634,153,-243,838,789 726,-582,210,105,983,537 -313,-323,758,234,29,848 -847,-172,-593,733,-56,617 54,255,-512,156,-575,675 -873,-956,-148,623,95,200 700,-370,926,649,-978,157 -639,-202,719,130,747,222 194,-33,955,943,505,114 -226,-790,28,-930,827,783 -392,-74,-28,714,218,-612 209,626,-888,-683,-912,495 487,751,614,933,631,445 -348,-34,-411,-106,835,321 -689,872,-29,-800,312,-542 -52,566,827,570,-862,-77 471,992,309,-402,389,912 24,520,-83,-51,555,503 -265,-317,283,-970,-472,690 606,526,137,71,-651,150 217,-518,663,66,-605,-331 -562,232,-76,-503,205,-323 842,-521,546,285,625,-186 997,-927,344,909,-546,974 -677,419,81,121,-705,771 719,-379,-944,-797,784,-155 -378,286,-317,-797,-111,964 -288,-573,784,80,-532,-646 -77,407,-248,-797,769,-816 -24,-637,287,-858,-927,-333 -902,37,894,-823,141,684 125,467,-177,-516,686,399 -321,-542,641,-590,527,-224 -400,-712,-876,-208,632,-543 -676,-429,664,-242,-269,922 -608,-273,-141,930,687,380 786,-12,498,494,310,326 -739,-617,606,-960,804,188 384,-368,-243,-350,-459,31 -550,397,320,-868,328,-279 969,-179,853,864,-110,514 910,793,302,-822,-285,488 -605,-128,218,-283,-17,-227 16,324,667,708,750,3 485,-813,19,585,71,930 -218,816,-687,-97,-732,-360 -497,-151,376,-23,3,315 -412,-989,-610,-813,372,964 -878,-280,87,381,-311,69 -609,-90,-731,-679,150,585 889,27,-162,605,75,-770 448,617,-988,0,-103,-504 -800,-537,-69,627,608,-668 534,686,-664,942,830,920 -238,775,495,932,-793,497 -343,958,-914,-514,-691,651 568,-136,208,359,728,28 286,912,-794,683,556,-102 -638,-629,-484,445,-64,-497 58,505,-801,-110,872,632 -390,777,353,267,976,369 -993,515,105,-133,358,-572 964,996,355,-212,-667,38 -725,-614,-35,365,132,-196 237,-536,-416,-302,312,477 -664,574,-210,224,48,-925 869,-261,-256,-240,-3,-698 712,385,32,-34,916,-315 895,-409,-100,-346,728,-624 -806,327,-450,889,-781,-939 -586,-403,698,318,-939,899 557,-57,-920,659,333,-51 -441,232,-918,-205,246,1 783,167,-797,-595,245,-736 -36,-531,-486,-426,-813,-160 777,-843,817,313,-228,-572 735,866,-309,-564,-81,190 -413,645,101,719,-719,218 -83,164,767,796,-430,-459 122,779,-15,-295,-96,-892 462,379,70,548,834,-312 -630,-534,124,187,-737,114 -299,-604,318,-591,936,826 -879,218,-642,-483,-318,-866 -691,62,-658,761,-895,-854 -822,493,687,569,910,-202 -223,784,304,-5,541,925 -914,541,737,-662,-662,-195 -622,615,414,358,881,-878 339,745,-268,-968,-280,-227 -364,855,148,-709,-827,472 -890,-532,-41,664,-612,577 -702,-859,971,-722,-660,-920 -539,-605,737,149,973,-802 800,42,-448,-811,152,511 -933,377,-110,-105,-374,-937 -766,152,482,120,-308,390 -568,775,-292,899,732,890 -177,-317,-502,-259,328,-511 612,-696,-574,-660,132,31 -119,563,-805,-864,179,-672 425,-627,183,-331,839,318 -711,-976,-749,152,-916,261 181,-63,497,211,262,406 -537,700,-859,-765,-928,77 892,832,231,-749,-82,613 816,216,-642,-216,-669,-912 -6,624,-937,-370,-344,268 737,-710,-869,983,-324,-274 565,952,-547,-158,374,-444 51,-683,645,-845,515,636 -953,-631,114,-377,-764,-144 -8,470,-242,-399,-675,-730 -540,689,-20,47,-607,590 -329,-710,-779,942,-388,979 123,829,674,122,203,563 46,782,396,-33,386,610 872,-846,-523,-122,-55,-190 388,-994,-525,974,127,596 781,-680,796,-34,-959,-62 -749,173,200,-384,-745,-446 379,618,136,-250,-224,970 -58,240,-921,-760,-901,-626 366,-185,565,-100,515,688 489,999,-893,-263,-637,816 838,-496,-316,-513,419,479 107,676,-15,882,98,-397 -999,941,-903,-424,670,-325 171,-979,835,178,169,-984 -609,-607,378,-681,184,402 -316,903,-575,-800,224,983 591,-18,-460,551,-167,918 -756,405,-117,441,163,-320 456,24,6,881,-836,-539 -489,-585,915,651,-892,-382 -177,-122,73,-711,-386,591 181,724,530,686,-131,241 737,288,886,216,233,33 -548,-386,-749,-153,-85,-982 -835,227,904,160,-99,25 -9,-42,-162,728,840,-963 217,-763,870,771,47,-846 -595,808,-491,556,337,-900 -134,281,-724,441,-134,708 -789,-508,651,-962,661,315 -839,-923,339,402,41,-487 300,-790,48,703,-398,-811 955,-51,462,-685,960,-717 910,-880,592,-255,-51,-776 -885,169,-793,368,-565,458 -905,940,-492,-630,-535,-988 245,797,763,869,-82,550 -310,38,-933,-367,-650,824 -95,32,-83,337,226,990 -218,-975,-191,-208,-785,-293 -672,-953,517,-901,-247,465 681,-148,261,-857,544,-923 640,341,446,-618,195,769 384,398,-846,365,671,815 578,576,-911,907,762,-859 548,-428,144,-630,-759,-146 710,-73,-700,983,-97,-889 -46,898,-973,-362,-817,-717 151,-81,-125,-900,-478,-154 483,615,-537,-932,181,-68 786,-223,518,25,-306,-12 -422,268,-809,-683,635,468 983,-734,-694,-608,-110,4 -786,-196,749,-354,137,-8 -181,36,668,-200,691,-973 -629,-838,692,-736,437,-871 -208,-536,-159,-596,8,197 -3,370,-686,170,913,-376 44,-998,-149,-993,-200,512 -519,136,859,497,536,434 77,-985,972,-340,-705,-837 -381,947,250,360,344,322 -26,131,699,750,707,384 -914,655,299,193,406,955 -883,-921,220,595,-546,794 -599,577,-569,-404,-704,489 -594,-963,-624,-460,880,-760 -603,88,-99,681,55,-328 976,472,139,-453,-531,-860 192,-290,513,-89,666,432 417,487,575,293,567,-668 655,711,-162,449,-980,972 -505,664,-685,-239,603,-592 -625,-802,-67,996,384,-636 365,-593,522,-666,-200,-431 -868,708,560,-860,-630,-355 -702,785,-637,-611,-597,960 -137,-696,-93,-803,408,406 891,-123,-26,-609,-610,518 133,-832,-198,555,708,-110 791,617,-69,487,696,315 -900,694,-565,517,-269,-416 914,135,-781,600,-71,-600 991,-915,-422,-351,-837,313 -840,-398,-302,21,590,146 62,-558,-702,-384,-625,831 -363,-426,-924,-496,792,-908 73,361,-817,-466,400,922 -626,-164,-626,860,-524,286 255,26,-944,809,-606,986 -457,-256,-103,50,-867,-871 -223,803,196,480,612,136 -820,-928,700,780,-977,721 717,332,53,-933,-128,793 -602,-648,562,593,890,702 -469,-875,-527,911,-475,-222 110,-281,-552,-536,-816,596 -981,654,413,-981,-75,-95 -754,-742,-515,894,-220,-344 795,-52,156,408,-603,76 474,-157,423,-499,-807,-791 260,688,40,-52,702,-122 -584,-517,-390,-881,302,-504 61,797,665,708,14,668 366,166,458,-614,564,-983 72,539,-378,796,381,-824 -485,201,-588,842,736,379 -149,-894,-298,705,-303,-406 660,-935,-580,521,93,633 -382,-282,-375,-841,-828,171 -567,743,-100,43,144,122 -281,-786,-749,-551,296,304 11,-426,-792,212,857,-175 594,143,-699,289,315,137 341,596,-390,107,-631,-804 -751,-636,-424,-854,193,651 -145,384,749,675,-786,517 224,-865,-323,96,-916,258 -309,403,-388,826,35,-270 -942,709,222,158,-699,-103 -589,842,-997,29,-195,-210 264,426,566,145,-217,623 217,965,507,-601,-453,507 -206,307,-982,4,64,-292 676,-49,-38,-701,550,883 5,-850,-438,659,745,-773 933,238,-574,-570,91,-33 -866,121,-928,358,459,-843 -568,-631,-352,-580,-349,189 -737,849,-963,-486,-662,970 135,334,-967,-71,-365,-792 789,21,-227,51,990,-275 240,412,-886,230,591,256 -609,472,-853,-754,959,661 401,521,521,314,929,982 -499,784,-208,71,-302,296 -557,-948,-553,-526,-864,793 270,-626,828,44,37,14 -412,224,617,-593,502,699 41,-908,81,562,-849,163 165,917,761,-197,331,-341 -687,314,799,755,-969,648 -164,25,578,439,-334,-576 213,535,874,-177,-551,24 -689,291,-795,-225,-496,-125 465,461,558,-118,-568,-909 567,660,-810,46,-485,878 -147,606,685,-690,-774,984 568,-886,-43,854,-738,616 -800,386,-614,585,764,-226 -518,23,-225,-732,-79,440 -173,-291,-689,636,642,-447 -598,-16,227,410,496,211 -474,-930,-656,-321,-420,36 -435,165,-819,555,540,144 -969,149,828,568,394,648 65,-848,257,720,-625,-851 981,899,275,635,465,-877 80,290,792,760,-191,-321 -605,-858,594,33,706,593 585,-472,318,-35,354,-927 -365,664,803,581,-965,-814 -427,-238,-480,146,-55,-606 879,-193,250,-890,336,117 -226,-322,-286,-765,-836,-218 -913,564,-667,-698,937,283 872,-901,810,-623,-52,-709 473,171,717,38,-429,-644 225,824,-219,-475,-180,234 -530,-797,-948,238,851,-623 85,975,-363,529,598,28 -799,166,-804,210,-769,851 -687,-158,885,736,-381,-461 447,592,928,-514,-515,-661 -399,-777,-493,80,-544,-78 -884,631,171,-825,-333,551 191,268,-577,676,137,-33 212,-853,709,798,583,-56 -908,-172,-540,-84,-135,-56 303,311,406,-360,-240,811 798,-708,824,59,234,-57 491,693,-74,585,-85,877 509,-65,-936,329,-51,722 -122,858,-52,467,-77,-609 850,760,547,-495,-953,-952 -460,-541,890,910,286,724 -914,843,-579,-983,-387,-460 989,-171,-877,-326,-899,458 846,175,-915,540,-1000,-982 -852,-920,-306,496,530,-18 338,-991,160,85,-455,-661 -186,-311,-460,-563,-231,-414 -932,-302,959,597,793,748 -366,-402,-788,-279,514,53 -940,-956,447,-956,211,-285 564,806,-911,-914,934,754 575,-858,-277,15,409,-714 848,462,100,-381,135,242 330,718,-24,-190,860,-78 479,458,941,108,-866,-653 212,980,962,-962,115,841 -827,-474,-206,881,323,765 506,-45,-30,-293,524,-133 832,-173,547,-852,-561,-842 -397,-661,-708,819,-545,-228 521,51,-489,852,36,-258 227,-164,189,465,-987,-882 -73,-997,641,-995,449,-615 151,-995,-638,415,257,-400 -663,-297,-748,537,-734,198 -585,-401,-81,-782,-80,-105 99,-21,238,-365,-704,-368 45,416,849,-211,-371,-1 -404,-443,795,-406,36,-933 272,-363,981,-491,-380,77 713,-342,-366,-849,643,911 -748,671,-537,813,961,-200 -194,-909,703,-662,-601,188 281,500,724,286,267,197 -832,847,-595,820,-316,637 520,521,-54,261,923,-10 4,-808,-682,-258,441,-695 -793,-107,-969,905,798,446 -108,-739,-590,69,-855,-365 380,-623,-930,817,468,713 759,-849,-236,433,-723,-931 95,-320,-686,124,-69,-329 -655,518,-210,-523,284,-866 144,303,639,70,-171,269 173,-333,947,-304,55,40 274,878,-482,-888,-835,375 -982,-854,-36,-218,-114,-230 905,-979,488,-485,-479,114 877,-157,553,-530,-47,-321 350,664,-881,442,-220,-284 434,-423,-365,878,-726,584 535,909,-517,-447,-660,-141 -966,191,50,353,182,-642 -785,-634,123,-907,-162,511 146,-850,-214,814,-704,25 692,1,521,492,-637,274 -662,-372,-313,597,983,-647 -962,-526,68,-549,-819,231 740,-890,-318,797,-666,948 -190,-12,-468,-455,948,284 16,478,-506,-888,628,-154 272,630,-976,308,433,3 -169,-391,-132,189,302,-388 109,-784,474,-167,-265,-31 -177,-532,283,464,421,-73 650,635,592,-138,1,-387 -932,703,-827,-492,-355,686 586,-311,340,-618,645,-434 -951,736,647,-127,-303,590 188,444,903,718,-931,500 -872,-642,-296,-571,337,241 23,65,152,125,880,470 512,823,-42,217,823,-263 180,-831,-380,886,607,762 722,443,-149,-216,-115,759 -19,660,-36,901,923,231 562,-322,-626,-968,194,-825 204,-920,938,784,362,150 -410,-266,-715,559,-672,124 -198,446,-140,454,-461,-447 83,-346,830,-493,-759,-382 -881,601,581,234,-134,-925 -494,914,-42,899,235,629 -390,50,956,437,774,-700 -514,514,44,-512,-576,-313 63,-688,808,-534,-570,-399 -726,572,-896,102,-294,-28 -688,757,401,406,955,-511 -283,423,-485,480,-767,908 -541,952,-594,116,-854,451 -273,-796,236,625,-626,257 -407,-493,373,826,-309,297 -750,955,-476,641,-809,713 8,415,695,226,-111,2 733,209,152,-920,401,995 921,-103,-919,66,871,-947 -907,89,-869,-214,851,-559 -307,748,524,-755,314,-711 188,897,-72,-763,482,103 545,-821,-232,-596,-334,-754 -217,-788,-820,388,-200,-662 779,160,-723,-975,-142,-998 -978,-519,-78,-981,842,904 -504,-736,-295,21,-472,-482 391,115,-705,574,652,-446 813,-988,865,830,-263,487 194,80,774,-493,-761,-872 -415,-284,-803,7,-810,670 -484,-4,881,-872,55,-852 -379,822,-266,324,-48,748 -304,-278,406,-60,959,-89 404,756,577,-643,-332,658 291,460,125,491,-312,83 311,-734,-141,582,282,-557 -450,-661,-981,710,-177,794 328,264,-787,971,-743,-407 -622,518,993,-241,-738,229 273,-826,-254,-917,-710,-111 809,770,96,368,-818,725 -488,773,502,-342,534,745 -28,-414,236,-315,-484,363 179,-466,-566,713,-683,56 560,-240,-597,619,916,-940 893,473,872,-868,-642,-461 799,489,383,-321,-776,-833 980,490,-508,764,-512,-426 917,961,-16,-675,440,559 -812,212,784,-987,-132,554 -886,454,747,806,190,231 910,341,21,-66,708,725 29,929,-831,-494,-303,389 -103,492,-271,-174,-515,529 -292,119,419,788,247,-951 483,543,-347,-673,664,-549 -926,-871,-437,337,162,-877 299,472,-771,5,-88,-643 -103,525,-725,-998,264,22 -505,708,550,-545,823,347 -738,931,59,147,-156,-259 456,968,-162,889,132,-911 535,120,968,-517,-864,-541 24,-395,-593,-766,-565,-332 834,611,825,-576,280,629 211,-548,140,-278,-592,929 -999,-240,-63,-78,793,573 -573,160,450,987,529,322 63,353,315,-187,-461,577 189,-950,-247,656,289,241 209,-297,397,664,-805,484 -655,452,435,-556,917,874 253,-756,262,-888,-778,-214 793,-451,323,-251,-401,-458 -396,619,-651,-287,-668,-781 698,720,-349,742,-807,546 738,280,680,279,-540,858 -789,387,530,-36,-551,-491 162,579,-427,-272,228,710 689,356,917,-580,729,217 -115,-638,866,424,-82,-194 411,-338,-917,172,227,-29 -612,63,630,-976,-64,-204 -200,911,583,-571,682,-579 91,298,396,-183,788,-955 141,-873,-277,149,-396,916 321,958,-136,573,541,-777 797,-909,-469,-877,988,-653 784,-198,129,883,-203,399 -68,-810,223,-423,-467,-512 531,-445,-603,-997,-841,641 -274,-242,174,261,-636,-158 -574,494,-796,-798,-798,99 95,-82,-613,-954,-753,986 -883,-448,-864,-401,938,-392 913,930,-542,-988,310,410 506,-99,43,512,790,-222 724,31,49,-950,260,-134 -287,-947,-234,-700,56,588 -33,782,-144,948,105,-791 548,-546,-652,-293,881,-520 691,-91,76,991,-631,742 -520,-429,-244,-296,724,-48 778,646,377,50,-188,56 -895,-507,-898,-165,-674,652 654,584,-634,177,-349,-620 114,-980,355,62,182,975 516,9,-442,-298,274,-579 -238,262,-431,-896,506,-850 47,748,846,821,-537,-293 839,726,593,285,-297,840 634,-486,468,-304,-887,-567 -864,914,296,-124,335,233 88,-253,-523,-956,-554,803 -587,417,281,-62,-409,-363 -136,-39,-292,-768,-264,876 -127,506,-891,-331,-744,-430 778,584,-750,-129,-479,-94 -876,-771,-987,-757,180,-641 -777,-694,411,-87,329,190 -347,-999,-882,158,-754,232 -105,918,188,237,-110,-591 -209,703,-838,77,838,909 -995,-339,-762,750,860,472 185,271,-289,173,811,-300 2,65,-656,-22,36,-139 765,-210,883,974,961,-905 -212,295,-615,-840,77,474 211,-910,-440,703,-11,859 -559,-4,-196,841,-277,969 -73,-159,-887,126,978,-371 -569,633,-423,-33,512,-393 503,143,-383,-109,-649,-998 -663,339,-317,-523,-2,596 690,-380,570,378,-652,132 72,-744,-930,399,-525,935 865,-983,115,37,995,826 594,-621,-872,443,188,-241 -1000,291,754,234,-435,-869 -868,901,654,-907,59,181 -868,-793,-431,596,-446,-564 900,-944,-680,-796,902,-366 331,430,943,853,-851,-942 315,-538,-354,-909,139,721 170,-884,-225,-818,-808,-657 -279,-34,-533,-871,-972,552 691,-986,-800,-950,654,-747 603,988,899,841,-630,591 876,-949,809,562,602,-536 -693,363,-189,495,738,-1000 -383,431,-633,297,665,959 -740,686,-207,-803,188,-520 -820,226,31,-339,10,121 -312,-844,624,-516,483,621 -822,-529,69,-278,800,328 834,-82,-759,420,811,-264 -960,-240,-921,561,173,46 -324,909,-790,-814,-2,-785 976,334,-290,-891,704,-581 150,-798,689,-823,237,-639 -551,-320,876,-502,-622,-628 -136,845,904,595,-702,-261 -857,-377,-522,-101,-943,-805 -682,-787,-888,-459,-752,-985 -571,-81,623,-133,447,643 -375,-158,72,-387,-324,-696 -660,-650,340,188,569,526 727,-218,16,-7,-595,-988 -966,-684,802,-783,-272,-194 115,-566,-888,47,712,180 -237,-69,45,-272,981,-812 48,897,439,417,50,325 348,616,180,254,104,-784 -730,811,-548,612,-736,790 138,-810,123,930,65,865 -768,-299,-49,-895,-692,-418 487,-531,802,-159,-12,634 808,-179,552,-73,470,717 720,-644,886,-141,625,144 -485,-505,-347,-244,-916,66 600,-565,995,-5,324,227 -771,-35,904,-482,753,-303 -701,65,426,-763,-504,-479 409,733,-823,475,64,718 865,975,368,893,-413,-433 812,-597,-970,819,813,624 193,-642,-381,-560,545,398 711,28,-316,771,717,-865 -509,462,809,-136,786,635 618,-49,484,169,635,547 -747,685,-882,-496,-332,82 -501,-851,870,563,290,570 -279,-829,-509,397,457,816 -508,80,850,-188,483,-326 860,-100,360,119,-205,787 -870,21,-39,-827,-185,932 826,284,-136,-866,-330,-97 -944,-82,745,899,-97,365 929,262,564,632,-115,632 244,-276,713,330,-897,-214 -890,-109,664,876,-974,-907 716,249,816,489,723,141 -96,-560,-272,45,-70,645 762,-503,414,-828,-254,-646 909,-13,903,-422,-344,-10 658,-486,743,545,50,674 -241,507,-367,18,-48,-241 886,-268,884,-762,120,-486 -412,-528,879,-647,223,-393 851,810,234,937,-726,797 -999,942,839,-134,-996,-189 100,979,-527,-521,378,800 544,-844,-832,-530,-77,-641 43,889,31,442,-934,-503 -330,-370,-309,-439,173,547 169,945,62,-753,-542,-597 208,751,-372,-647,-520,70 765,-840,907,-257,379,918 334,-135,-689,730,-427,618 137,-508,66,-695,78,169 -962,-123,400,-417,151,969 328,689,666,427,-555,-642 -907,343,605,-341,-647,582 -667,-363,-571,818,-265,-399 525,-938,904,898,725,692 -176,-802,-858,-9,780,275 580,170,-740,287,691,-97 365,557,-375,361,-288,859 193,737,842,-808,520,282 -871,65,-799,836,179,-720 958,-144,744,-789,797,-48 122,582,662,912,68,757 595,241,-801,513,388,186 -103,-677,-259,-731,-281,-857 921,319,-696,683,-88,-997 775,200,78,858,648,768 316,821,-763,68,-290,-741 564,664,691,504,760,787 694,-119,973,-385,309,-760 777,-947,-57,990,74,19 971,626,-496,-781,-602,-239 -651,433,11,-339,939,294 -965,-728,560,569,-708,-247
-340,495,-153,-910,835,-947 -175,41,-421,-714,574,-645 -547,712,-352,579,951,-786 419,-864,-83,650,-399,171 -429,-89,-357,-930,296,-29 -734,-702,823,-745,-684,-62 -971,762,925,-776,-663,-157 162,570,628,485,-807,-896 641,91,-65,700,887,759 215,-496,46,-931,422,-30 -119,359,668,-609,-358,-494 440,929,968,214,760,-857 -700,785,838,29,-216,411 -770,-458,-325,-53,-505,633 -752,-805,349,776,-799,687 323,5,561,-36,919,-560 -907,358,264,320,204,274 -728,-466,350,969,292,-345 940,836,272,-533,748,185 411,998,813,520,316,-949 -152,326,658,-762,148,-651 330,507,-9,-628,101,174 551,-496,772,-541,-702,-45 -164,-489,-90,322,631,-59 673,366,-4,-143,-606,-704 428,-609,801,-449,740,-269 453,-924,-785,-346,-853,111 -738,555,-181,467,-426,-20 958,-692,784,-343,505,-569 620,27,263,54,-439,-726 804,87,998,859,871,-78 -119,-453,-709,-292,-115,-56 -626,138,-940,-476,-177,-274 -11,160,142,588,446,158 538,727,550,787,330,810 420,-689,854,-546,337,516 872,-998,-607,748,473,-192 653,440,-516,-985,808,-857 374,-158,331,-940,-338,-641 137,-925,-179,771,734,-715 -314,198,-115,29,-641,-39 759,-574,-385,355,590,-603 -189,-63,-168,204,289,305 -182,-524,-715,-621,911,-255 331,-816,-833,471,168,126 -514,581,-855,-220,-731,-507 129,169,576,651,-87,-458 783,-444,-881,658,-266,298 603,-430,-598,585,368,899 43,-724,962,-376,851,409 -610,-646,-883,-261,-482,-881 -117,-237,978,641,101,-747 579,125,-715,-712,208,534 672,-214,-762,372,874,533 -564,965,38,715,367,242 500,951,-700,-981,-61,-178 -382,-224,-959,903,-282,-60 -355,295,426,-331,-591,655 892,128,958,-271,-993,274 -454,-619,302,138,-790,-874 -642,601,-574,159,-290,-318 266,-109,257,-686,54,975 162,628,-478,840,264,-266 466,-280,982,1,904,-810 721,839,730,-807,777,981 -129,-430,748,263,943,96 434,-94,410,-990,249,-704 237,42,122,-732,44,-51 909,-116,-229,545,292,717 824,-768,-807,-370,-262,30 675,58,332,-890,-651,791 363,825,-717,254,684,240 405,-715,900,166,-589,422 -476,686,-830,-319,634,-807 633,837,-971,917,-764,207 -116,-44,-193,-70,908,809 -26,-252,998,408,70,-713 -601,645,-462,842,-644,-591 -160,653,274,113,-138,687 369,-273,-181,925,-167,-693 -338,135,480,-967,-13,-840 -90,-270,-564,695,161,907 607,-430,869,-713,461,-469 919,-165,-776,522,606,-708 -203,465,288,207,-339,-458 -453,-534,-715,975,838,-677 -973,310,-350,934,546,-805 -835,385,708,-337,-594,-772 -14,914,900,-495,-627,594 833,-713,-213,578,-296,699 -27,-748,484,455,915,291 270,889,739,-57,442,-516 119,811,-679,905,184,130 -678,-469,925,553,612,482 101,-571,-732,-842,644,588 -71,-737,566,616,957,-663 -634,-356,90,-207,936,622 598,443,964,-895,-58,529 847,-467,929,-742,91,10 -633,829,-780,-408,222,-30 -818,57,275,-38,-746,198 -722,-825,-549,597,-391,99 -570,908,430,873,-103,-360 342,-681,512,434,542,-528 297,850,479,609,543,-357 9,784,212,548,56,859 -152,560,-240,-969,-18,713 140,-133,34,-635,250,-163 -272,-22,-169,-662,989,-604 471,-765,355,633,-742,-118 -118,146,942,663,547,-376 583,16,162,264,715,-33 -230,-446,997,-838,561,555 372,397,-729,-318,-276,649 92,982,-970,-390,-922,922 -981,713,-951,-337,-669,670 -999,846,-831,-504,7,-128 455,-954,-370,682,-510,45 822,-960,-892,-385,-662,314 -668,-686,-367,-246,530,-341 -723,-720,-926,-836,-142,757 -509,-134,384,-221,-873,-639 -803,-52,-706,-669,373,-339 933,578,631,-616,770,555 741,-564,-33,-605,-576,275 -715,445,-233,-730,734,-704 120,-10,-266,-685,-490,-17 -232,-326,-457,-946,-457,-116 811,52,639,826,-200,147 -329,279,293,612,943,955 -721,-894,-393,-969,-642,453 -688,-826,-352,-75,371,79 -809,-979,407,497,858,-248 -485,-232,-242,-582,-81,849 141,-106,123,-152,806,-596 -428,57,-992,811,-192,478 864,393,122,858,255,-876 -284,-780,240,457,354,-107 956,605,-477,44,26,-678 86,710,-533,-815,439,327 -906,-626,-834,763,426,-48 201,-150,-904,652,475,412 -247,149,81,-199,-531,-148 923,-76,-353,175,-121,-223 427,-674,453,472,-410,585 931,776,-33,85,-962,-865 -655,-908,-902,208,869,792 -316,-102,-45,-436,-222,885 -309,768,-574,653,745,-975 896,27,-226,993,332,198 323,655,-89,260,240,-902 501,-763,-424,793,813,616 993,375,-938,-621,672,-70 -880,-466,-283,770,-824,143 63,-283,886,-142,879,-116 -964,-50,-521,-42,-306,-161 724,-22,866,-871,933,-383 -344,135,282,966,-80,917 -281,-189,420,810,362,-582 -515,455,-588,814,162,332 555,-436,-123,-210,869,-943 589,577,232,286,-554,876 -773,127,-58,-171,-452,125 -428,575,906,-232,-10,-224 437,276,-335,-348,605,878 -964,511,-386,-407,168,-220 307,513,912,-463,-423,-416 -445,539,273,886,-18,760 -396,-585,-670,414,47,364 143,-506,754,906,-971,-203 -544,472,-180,-541,869,-465 -779,-15,-396,890,972,-220 -430,-564,503,182,-119,456 89,-10,-739,399,506,499 954,162,-810,-973,127,870 890,952,-225,158,828,237 -868,952,349,465,574,750 -915,369,-975,-596,-395,-134 -135,-601,575,582,-667,640 413,890,-560,-276,-555,-562 -633,-269,561,-820,-624,499 371,-92,-784,-593,864,-717 -971,655,-439,367,754,-951 172,-347,36,279,-247,-402 633,-301,364,-349,-683,-387 -780,-211,-713,-948,-648,543 72,58,762,-465,-66,462 78,502,781,-832,713,836 -431,-64,-484,-392,208,-343 -64,101,-29,-860,-329,844 398,391,828,-858,700,395 578,-896,-326,-604,314,180 97,-321,-695,185,-357,852 854,839,283,-375,951,-209 194,96,-564,-847,162,524 -354,532,494,621,580,560 419,-678,-450,926,-5,-924 -661,905,519,621,-143,394 -573,268,296,-562,-291,-319 -211,266,-196,158,564,-183 18,-585,-398,777,-581,864 790,-894,-745,-604,-418,70 848,-339,150,773,11,851 -954,-809,-53,-20,-648,-304 658,-336,-658,-905,853,407 -365,-844,350,-625,852,-358 986,-315,-230,-159,21,180 -15,599,45,-286,-941,847 -613,-68,184,639,-987,550 334,675,-56,-861,923,340 -848,-596,960,231,-28,-34 707,-811,-994,-356,-167,-171 -470,-764,72,576,-600,-204 379,189,-542,-576,585,800 440,540,-445,-563,379,-334 -155,64,514,-288,853,106 -304,751,481,-520,-708,-694 -709,132,594,126,-844,63 723,471,421,-138,-962,892 -440,-263,39,513,-672,-954 775,809,-581,330,752,-107 -376,-158,335,-708,-514,578 -343,-769,456,-187,25,413 548,-877,-172,300,-500,928 938,-102,423,-488,-378,-969 -36,564,-55,131,958,-800 -322,511,-413,503,700,-847 -966,547,-88,-17,-359,-67 637,-341,-437,-181,527,-153 -74,449,-28,3,485,189 -997,658,-224,-948,702,-807 -224,736,-896,127,-945,-850 -395,-106,439,-553,-128,124 -841,-445,-758,-572,-489,212 633,-327,13,-512,952,771 -940,-171,-6,-46,-923,-425 -142,-442,-817,-998,843,-695 340,847,-137,-920,-988,-658 -653,217,-679,-257,651,-719 -294,365,-41,342,74,-892 690,-236,-541,494,408,-516 180,-807,225,790,494,59 707,605,-246,656,284,271 65,294,152,824,442,-442 -321,781,-540,341,316,415 420,371,-2,545,995,248 56,-191,-604,971,615,449 -981,-31,510,592,-390,-362 -317,-968,913,365,97,508 832,63,-864,-510,86,202 -483,456,-636,340,-310,676 981,-847,751,-508,-962,-31 -157,99,73,797,63,-172 220,858,872,924,866,-381 996,-169,805,321,-164,971 896,11,-625,-973,-782,76 578,-280,730,-729,307,-905 -580,-749,719,-698,967,603 -821,874,-103,-623,662,-491 -763,117,661,-644,672,-607 592,787,-798,-169,-298,690 296,644,-526,-762,-447,665 534,-818,852,-120,57,-379 -986,-549,-329,294,954,258 -133,352,-660,-77,904,-356 748,343,215,500,317,-277 311,7,910,-896,-809,795 763,-602,-753,313,-352,917 668,619,-474,-597,-650,650 -297,563,-701,-987,486,-902 -461,-740,-657,233,-482,-328 -446,-250,-986,-458,-629,520 542,-49,-327,-469,257,-947 121,-575,-634,-143,-184,521 30,504,455,-645,-229,-945 -12,-295,377,764,771,125 -686,-133,225,-25,-376,-143 -6,-46,338,270,-405,-872 -623,-37,582,467,963,898 -804,869,-477,420,-475,-303 94,41,-842,-193,-768,720 -656,-918,415,645,-357,460 -47,-486,-911,468,-608,-686 -158,251,419,-394,-655,-895 272,-695,979,508,-358,959 -776,650,-918,-467,-690,-534 -85,-309,-626,167,-366,-429 -880,-732,-186,-924,970,-875 517,645,-274,962,-804,544 721,402,104,640,478,-499 198,684,-134,-723,-452,-905 -245,745,239,238,-826,441 -217,206,-32,462,-981,-895 -51,989,526,-173,560,-676 -480,-659,-976,-580,-727,466 -996,-90,-995,158,-239,642 302,288,-194,-294,17,924 -943,969,-326,114,-500,103 -619,163,339,-880,230,421 -344,-601,-795,557,565,-779 590,345,-129,-202,-125,-58 -777,-195,159,674,775,411 -939,312,-665,810,121,855 -971,254,712,815,452,581 442,-9,327,-750,61,757 -342,869,869,-160,390,-772 620,601,565,-169,-69,-183 -25,924,-817,964,321,-970 -64,-6,-133,978,825,-379 601,436,-24,98,-115,940 -97,502,614,-574,922,513 -125,262,-946,695,99,-220 429,-721,719,-694,197,-558 326,689,-70,-908,-673,338 -468,-856,-902,-254,-358,305 -358,530,542,355,-253,-47 -438,-74,-362,963,988,788 137,717,467,622,319,-380 -86,310,-336,851,918,-288 721,395,646,-53,255,-425 255,175,912,84,-209,878 -632,-485,-400,-357,991,-608 235,-559,992,-297,857,-591 87,-71,148,130,647,578 -290,-584,-639,-788,-21,592 386,984,625,-731,-993,-336 -538,634,-209,-828,-150,-774 -754,-387,607,-781,976,-199 412,-798,-664,295,709,-537 -412,932,-880,-232,561,852 -656,-358,-198,-964,-433,-848 -762,-668,-632,186,-673,-11 -876,237,-282,-312,-83,682 403,73,-57,-436,-622,781 -587,873,798,976,-39,329 -369,-622,553,-341,817,794 -108,-616,920,-849,-679,96 290,-974,234,239,-284,-321 -22,394,-417,-419,264,58 -473,-551,69,923,591,-228 -956,662,-113,851,-581,-794 -258,-681,413,-471,-637,-817 -866,926,992,-653,-7,794 556,-350,602,917,831,-610 188,245,-906,361,492,174 -720,384,-818,329,638,-666 -246,846,890,-325,-59,-850 -118,-509,620,-762,-256,15 -787,-536,-452,-338,-399,813 458,560,525,-311,-608,-419 494,-811,-825,-127,-812,894 -801,890,-629,-860,574,925 -709,-193,-213,138,-410,-403 861,91,708,-187,5,-222 789,646,777,154,90,-49 -267,-830,-114,531,591,-698 -126,-82,881,-418,82,652 -894,130,-726,-935,393,-815 -142,563,654,638,-712,-597 -759,60,-23,977,100,-765 -305,595,-570,-809,482,762 -161,-267,53,963,998,-529 -300,-57,798,353,703,486 -990,696,-764,699,-565,719 -232,-205,566,571,977,369 740,865,151,-817,-204,-293 94,445,-768,229,537,-406 861,620,37,-424,-36,656 390,-369,952,733,-464,569 -482,-604,959,554,-705,-626 -396,-615,-991,108,272,-723 143,780,535,142,-917,-147 138,-629,-217,-908,905,115 915,103,-852,64,-468,-642 570,734,-785,-268,-326,-759 738,531,-332,586,-779,24 870,440,-217,473,-383,415 -296,-333,-330,-142,-924,950 118,120,-35,-245,-211,-652 61,634,153,-243,838,789 726,-582,210,105,983,537 -313,-323,758,234,29,848 -847,-172,-593,733,-56,617 54,255,-512,156,-575,675 -873,-956,-148,623,95,200 700,-370,926,649,-978,157 -639,-202,719,130,747,222 194,-33,955,943,505,114 -226,-790,28,-930,827,783 -392,-74,-28,714,218,-612 209,626,-888,-683,-912,495 487,751,614,933,631,445 -348,-34,-411,-106,835,321 -689,872,-29,-800,312,-542 -52,566,827,570,-862,-77 471,992,309,-402,389,912 24,520,-83,-51,555,503 -265,-317,283,-970,-472,690 606,526,137,71,-651,150 217,-518,663,66,-605,-331 -562,232,-76,-503,205,-323 842,-521,546,285,625,-186 997,-927,344,909,-546,974 -677,419,81,121,-705,771 719,-379,-944,-797,784,-155 -378,286,-317,-797,-111,964 -288,-573,784,80,-532,-646 -77,407,-248,-797,769,-816 -24,-637,287,-858,-927,-333 -902,37,894,-823,141,684 125,467,-177,-516,686,399 -321,-542,641,-590,527,-224 -400,-712,-876,-208,632,-543 -676,-429,664,-242,-269,922 -608,-273,-141,930,687,380 786,-12,498,494,310,326 -739,-617,606,-960,804,188 384,-368,-243,-350,-459,31 -550,397,320,-868,328,-279 969,-179,853,864,-110,514 910,793,302,-822,-285,488 -605,-128,218,-283,-17,-227 16,324,667,708,750,3 485,-813,19,585,71,930 -218,816,-687,-97,-732,-360 -497,-151,376,-23,3,315 -412,-989,-610,-813,372,964 -878,-280,87,381,-311,69 -609,-90,-731,-679,150,585 889,27,-162,605,75,-770 448,617,-988,0,-103,-504 -800,-537,-69,627,608,-668 534,686,-664,942,830,920 -238,775,495,932,-793,497 -343,958,-914,-514,-691,651 568,-136,208,359,728,28 286,912,-794,683,556,-102 -638,-629,-484,445,-64,-497 58,505,-801,-110,872,632 -390,777,353,267,976,369 -993,515,105,-133,358,-572 964,996,355,-212,-667,38 -725,-614,-35,365,132,-196 237,-536,-416,-302,312,477 -664,574,-210,224,48,-925 869,-261,-256,-240,-3,-698 712,385,32,-34,916,-315 895,-409,-100,-346,728,-624 -806,327,-450,889,-781,-939 -586,-403,698,318,-939,899 557,-57,-920,659,333,-51 -441,232,-918,-205,246,1 783,167,-797,-595,245,-736 -36,-531,-486,-426,-813,-160 777,-843,817,313,-228,-572 735,866,-309,-564,-81,190 -413,645,101,719,-719,218 -83,164,767,796,-430,-459 122,779,-15,-295,-96,-892 462,379,70,548,834,-312 -630,-534,124,187,-737,114 -299,-604,318,-591,936,826 -879,218,-642,-483,-318,-866 -691,62,-658,761,-895,-854 -822,493,687,569,910,-202 -223,784,304,-5,541,925 -914,541,737,-662,-662,-195 -622,615,414,358,881,-878 339,745,-268,-968,-280,-227 -364,855,148,-709,-827,472 -890,-532,-41,664,-612,577 -702,-859,971,-722,-660,-920 -539,-605,737,149,973,-802 800,42,-448,-811,152,511 -933,377,-110,-105,-374,-937 -766,152,482,120,-308,390 -568,775,-292,899,732,890 -177,-317,-502,-259,328,-511 612,-696,-574,-660,132,31 -119,563,-805,-864,179,-672 425,-627,183,-331,839,318 -711,-976,-749,152,-916,261 181,-63,497,211,262,406 -537,700,-859,-765,-928,77 892,832,231,-749,-82,613 816,216,-642,-216,-669,-912 -6,624,-937,-370,-344,268 737,-710,-869,983,-324,-274 565,952,-547,-158,374,-444 51,-683,645,-845,515,636 -953,-631,114,-377,-764,-144 -8,470,-242,-399,-675,-730 -540,689,-20,47,-607,590 -329,-710,-779,942,-388,979 123,829,674,122,203,563 46,782,396,-33,386,610 872,-846,-523,-122,-55,-190 388,-994,-525,974,127,596 781,-680,796,-34,-959,-62 -749,173,200,-384,-745,-446 379,618,136,-250,-224,970 -58,240,-921,-760,-901,-626 366,-185,565,-100,515,688 489,999,-893,-263,-637,816 838,-496,-316,-513,419,479 107,676,-15,882,98,-397 -999,941,-903,-424,670,-325 171,-979,835,178,169,-984 -609,-607,378,-681,184,402 -316,903,-575,-800,224,983 591,-18,-460,551,-167,918 -756,405,-117,441,163,-320 456,24,6,881,-836,-539 -489,-585,915,651,-892,-382 -177,-122,73,-711,-386,591 181,724,530,686,-131,241 737,288,886,216,233,33 -548,-386,-749,-153,-85,-982 -835,227,904,160,-99,25 -9,-42,-162,728,840,-963 217,-763,870,771,47,-846 -595,808,-491,556,337,-900 -134,281,-724,441,-134,708 -789,-508,651,-962,661,315 -839,-923,339,402,41,-487 300,-790,48,703,-398,-811 955,-51,462,-685,960,-717 910,-880,592,-255,-51,-776 -885,169,-793,368,-565,458 -905,940,-492,-630,-535,-988 245,797,763,869,-82,550 -310,38,-933,-367,-650,824 -95,32,-83,337,226,990 -218,-975,-191,-208,-785,-293 -672,-953,517,-901,-247,465 681,-148,261,-857,544,-923 640,341,446,-618,195,769 384,398,-846,365,671,815 578,576,-911,907,762,-859 548,-428,144,-630,-759,-146 710,-73,-700,983,-97,-889 -46,898,-973,-362,-817,-717 151,-81,-125,-900,-478,-154 483,615,-537,-932,181,-68 786,-223,518,25,-306,-12 -422,268,-809,-683,635,468 983,-734,-694,-608,-110,4 -786,-196,749,-354,137,-8 -181,36,668,-200,691,-973 -629,-838,692,-736,437,-871 -208,-536,-159,-596,8,197 -3,370,-686,170,913,-376 44,-998,-149,-993,-200,512 -519,136,859,497,536,434 77,-985,972,-340,-705,-837 -381,947,250,360,344,322 -26,131,699,750,707,384 -914,655,299,193,406,955 -883,-921,220,595,-546,794 -599,577,-569,-404,-704,489 -594,-963,-624,-460,880,-760 -603,88,-99,681,55,-328 976,472,139,-453,-531,-860 192,-290,513,-89,666,432 417,487,575,293,567,-668 655,711,-162,449,-980,972 -505,664,-685,-239,603,-592 -625,-802,-67,996,384,-636 365,-593,522,-666,-200,-431 -868,708,560,-860,-630,-355 -702,785,-637,-611,-597,960 -137,-696,-93,-803,408,406 891,-123,-26,-609,-610,518 133,-832,-198,555,708,-110 791,617,-69,487,696,315 -900,694,-565,517,-269,-416 914,135,-781,600,-71,-600 991,-915,-422,-351,-837,313 -840,-398,-302,21,590,146 62,-558,-702,-384,-625,831 -363,-426,-924,-496,792,-908 73,361,-817,-466,400,922 -626,-164,-626,860,-524,286 255,26,-944,809,-606,986 -457,-256,-103,50,-867,-871 -223,803,196,480,612,136 -820,-928,700,780,-977,721 717,332,53,-933,-128,793 -602,-648,562,593,890,702 -469,-875,-527,911,-475,-222 110,-281,-552,-536,-816,596 -981,654,413,-981,-75,-95 -754,-742,-515,894,-220,-344 795,-52,156,408,-603,76 474,-157,423,-499,-807,-791 260,688,40,-52,702,-122 -584,-517,-390,-881,302,-504 61,797,665,708,14,668 366,166,458,-614,564,-983 72,539,-378,796,381,-824 -485,201,-588,842,736,379 -149,-894,-298,705,-303,-406 660,-935,-580,521,93,633 -382,-282,-375,-841,-828,171 -567,743,-100,43,144,122 -281,-786,-749,-551,296,304 11,-426,-792,212,857,-175 594,143,-699,289,315,137 341,596,-390,107,-631,-804 -751,-636,-424,-854,193,651 -145,384,749,675,-786,517 224,-865,-323,96,-916,258 -309,403,-388,826,35,-270 -942,709,222,158,-699,-103 -589,842,-997,29,-195,-210 264,426,566,145,-217,623 217,965,507,-601,-453,507 -206,307,-982,4,64,-292 676,-49,-38,-701,550,883 5,-850,-438,659,745,-773 933,238,-574,-570,91,-33 -866,121,-928,358,459,-843 -568,-631,-352,-580,-349,189 -737,849,-963,-486,-662,970 135,334,-967,-71,-365,-792 789,21,-227,51,990,-275 240,412,-886,230,591,256 -609,472,-853,-754,959,661 401,521,521,314,929,982 -499,784,-208,71,-302,296 -557,-948,-553,-526,-864,793 270,-626,828,44,37,14 -412,224,617,-593,502,699 41,-908,81,562,-849,163 165,917,761,-197,331,-341 -687,314,799,755,-969,648 -164,25,578,439,-334,-576 213,535,874,-177,-551,24 -689,291,-795,-225,-496,-125 465,461,558,-118,-568,-909 567,660,-810,46,-485,878 -147,606,685,-690,-774,984 568,-886,-43,854,-738,616 -800,386,-614,585,764,-226 -518,23,-225,-732,-79,440 -173,-291,-689,636,642,-447 -598,-16,227,410,496,211 -474,-930,-656,-321,-420,36 -435,165,-819,555,540,144 -969,149,828,568,394,648 65,-848,257,720,-625,-851 981,899,275,635,465,-877 80,290,792,760,-191,-321 -605,-858,594,33,706,593 585,-472,318,-35,354,-927 -365,664,803,581,-965,-814 -427,-238,-480,146,-55,-606 879,-193,250,-890,336,117 -226,-322,-286,-765,-836,-218 -913,564,-667,-698,937,283 872,-901,810,-623,-52,-709 473,171,717,38,-429,-644 225,824,-219,-475,-180,234 -530,-797,-948,238,851,-623 85,975,-363,529,598,28 -799,166,-804,210,-769,851 -687,-158,885,736,-381,-461 447,592,928,-514,-515,-661 -399,-777,-493,80,-544,-78 -884,631,171,-825,-333,551 191,268,-577,676,137,-33 212,-853,709,798,583,-56 -908,-172,-540,-84,-135,-56 303,311,406,-360,-240,811 798,-708,824,59,234,-57 491,693,-74,585,-85,877 509,-65,-936,329,-51,722 -122,858,-52,467,-77,-609 850,760,547,-495,-953,-952 -460,-541,890,910,286,724 -914,843,-579,-983,-387,-460 989,-171,-877,-326,-899,458 846,175,-915,540,-1000,-982 -852,-920,-306,496,530,-18 338,-991,160,85,-455,-661 -186,-311,-460,-563,-231,-414 -932,-302,959,597,793,748 -366,-402,-788,-279,514,53 -940,-956,447,-956,211,-285 564,806,-911,-914,934,754 575,-858,-277,15,409,-714 848,462,100,-381,135,242 330,718,-24,-190,860,-78 479,458,941,108,-866,-653 212,980,962,-962,115,841 -827,-474,-206,881,323,765 506,-45,-30,-293,524,-133 832,-173,547,-852,-561,-842 -397,-661,-708,819,-545,-228 521,51,-489,852,36,-258 227,-164,189,465,-987,-882 -73,-997,641,-995,449,-615 151,-995,-638,415,257,-400 -663,-297,-748,537,-734,198 -585,-401,-81,-782,-80,-105 99,-21,238,-365,-704,-368 45,416,849,-211,-371,-1 -404,-443,795,-406,36,-933 272,-363,981,-491,-380,77 713,-342,-366,-849,643,911 -748,671,-537,813,961,-200 -194,-909,703,-662,-601,188 281,500,724,286,267,197 -832,847,-595,820,-316,637 520,521,-54,261,923,-10 4,-808,-682,-258,441,-695 -793,-107,-969,905,798,446 -108,-739,-590,69,-855,-365 380,-623,-930,817,468,713 759,-849,-236,433,-723,-931 95,-320,-686,124,-69,-329 -655,518,-210,-523,284,-866 144,303,639,70,-171,269 173,-333,947,-304,55,40 274,878,-482,-888,-835,375 -982,-854,-36,-218,-114,-230 905,-979,488,-485,-479,114 877,-157,553,-530,-47,-321 350,664,-881,442,-220,-284 434,-423,-365,878,-726,584 535,909,-517,-447,-660,-141 -966,191,50,353,182,-642 -785,-634,123,-907,-162,511 146,-850,-214,814,-704,25 692,1,521,492,-637,274 -662,-372,-313,597,983,-647 -962,-526,68,-549,-819,231 740,-890,-318,797,-666,948 -190,-12,-468,-455,948,284 16,478,-506,-888,628,-154 272,630,-976,308,433,3 -169,-391,-132,189,302,-388 109,-784,474,-167,-265,-31 -177,-532,283,464,421,-73 650,635,592,-138,1,-387 -932,703,-827,-492,-355,686 586,-311,340,-618,645,-434 -951,736,647,-127,-303,590 188,444,903,718,-931,500 -872,-642,-296,-571,337,241 23,65,152,125,880,470 512,823,-42,217,823,-263 180,-831,-380,886,607,762 722,443,-149,-216,-115,759 -19,660,-36,901,923,231 562,-322,-626,-968,194,-825 204,-920,938,784,362,150 -410,-266,-715,559,-672,124 -198,446,-140,454,-461,-447 83,-346,830,-493,-759,-382 -881,601,581,234,-134,-925 -494,914,-42,899,235,629 -390,50,956,437,774,-700 -514,514,44,-512,-576,-313 63,-688,808,-534,-570,-399 -726,572,-896,102,-294,-28 -688,757,401,406,955,-511 -283,423,-485,480,-767,908 -541,952,-594,116,-854,451 -273,-796,236,625,-626,257 -407,-493,373,826,-309,297 -750,955,-476,641,-809,713 8,415,695,226,-111,2 733,209,152,-920,401,995 921,-103,-919,66,871,-947 -907,89,-869,-214,851,-559 -307,748,524,-755,314,-711 188,897,-72,-763,482,103 545,-821,-232,-596,-334,-754 -217,-788,-820,388,-200,-662 779,160,-723,-975,-142,-998 -978,-519,-78,-981,842,904 -504,-736,-295,21,-472,-482 391,115,-705,574,652,-446 813,-988,865,830,-263,487 194,80,774,-493,-761,-872 -415,-284,-803,7,-810,670 -484,-4,881,-872,55,-852 -379,822,-266,324,-48,748 -304,-278,406,-60,959,-89 404,756,577,-643,-332,658 291,460,125,491,-312,83 311,-734,-141,582,282,-557 -450,-661,-981,710,-177,794 328,264,-787,971,-743,-407 -622,518,993,-241,-738,229 273,-826,-254,-917,-710,-111 809,770,96,368,-818,725 -488,773,502,-342,534,745 -28,-414,236,-315,-484,363 179,-466,-566,713,-683,56 560,-240,-597,619,916,-940 893,473,872,-868,-642,-461 799,489,383,-321,-776,-833 980,490,-508,764,-512,-426 917,961,-16,-675,440,559 -812,212,784,-987,-132,554 -886,454,747,806,190,231 910,341,21,-66,708,725 29,929,-831,-494,-303,389 -103,492,-271,-174,-515,529 -292,119,419,788,247,-951 483,543,-347,-673,664,-549 -926,-871,-437,337,162,-877 299,472,-771,5,-88,-643 -103,525,-725,-998,264,22 -505,708,550,-545,823,347 -738,931,59,147,-156,-259 456,968,-162,889,132,-911 535,120,968,-517,-864,-541 24,-395,-593,-766,-565,-332 834,611,825,-576,280,629 211,-548,140,-278,-592,929 -999,-240,-63,-78,793,573 -573,160,450,987,529,322 63,353,315,-187,-461,577 189,-950,-247,656,289,241 209,-297,397,664,-805,484 -655,452,435,-556,917,874 253,-756,262,-888,-778,-214 793,-451,323,-251,-401,-458 -396,619,-651,-287,-668,-781 698,720,-349,742,-807,546 738,280,680,279,-540,858 -789,387,530,-36,-551,-491 162,579,-427,-272,228,710 689,356,917,-580,729,217 -115,-638,866,424,-82,-194 411,-338,-917,172,227,-29 -612,63,630,-976,-64,-204 -200,911,583,-571,682,-579 91,298,396,-183,788,-955 141,-873,-277,149,-396,916 321,958,-136,573,541,-777 797,-909,-469,-877,988,-653 784,-198,129,883,-203,399 -68,-810,223,-423,-467,-512 531,-445,-603,-997,-841,641 -274,-242,174,261,-636,-158 -574,494,-796,-798,-798,99 95,-82,-613,-954,-753,986 -883,-448,-864,-401,938,-392 913,930,-542,-988,310,410 506,-99,43,512,790,-222 724,31,49,-950,260,-134 -287,-947,-234,-700,56,588 -33,782,-144,948,105,-791 548,-546,-652,-293,881,-520 691,-91,76,991,-631,742 -520,-429,-244,-296,724,-48 778,646,377,50,-188,56 -895,-507,-898,-165,-674,652 654,584,-634,177,-349,-620 114,-980,355,62,182,975 516,9,-442,-298,274,-579 -238,262,-431,-896,506,-850 47,748,846,821,-537,-293 839,726,593,285,-297,840 634,-486,468,-304,-887,-567 -864,914,296,-124,335,233 88,-253,-523,-956,-554,803 -587,417,281,-62,-409,-363 -136,-39,-292,-768,-264,876 -127,506,-891,-331,-744,-430 778,584,-750,-129,-479,-94 -876,-771,-987,-757,180,-641 -777,-694,411,-87,329,190 -347,-999,-882,158,-754,232 -105,918,188,237,-110,-591 -209,703,-838,77,838,909 -995,-339,-762,750,860,472 185,271,-289,173,811,-300 2,65,-656,-22,36,-139 765,-210,883,974,961,-905 -212,295,-615,-840,77,474 211,-910,-440,703,-11,859 -559,-4,-196,841,-277,969 -73,-159,-887,126,978,-371 -569,633,-423,-33,512,-393 503,143,-383,-109,-649,-998 -663,339,-317,-523,-2,596 690,-380,570,378,-652,132 72,-744,-930,399,-525,935 865,-983,115,37,995,826 594,-621,-872,443,188,-241 -1000,291,754,234,-435,-869 -868,901,654,-907,59,181 -868,-793,-431,596,-446,-564 900,-944,-680,-796,902,-366 331,430,943,853,-851,-942 315,-538,-354,-909,139,721 170,-884,-225,-818,-808,-657 -279,-34,-533,-871,-972,552 691,-986,-800,-950,654,-747 603,988,899,841,-630,591 876,-949,809,562,602,-536 -693,363,-189,495,738,-1000 -383,431,-633,297,665,959 -740,686,-207,-803,188,-520 -820,226,31,-339,10,121 -312,-844,624,-516,483,621 -822,-529,69,-278,800,328 834,-82,-759,420,811,-264 -960,-240,-921,561,173,46 -324,909,-790,-814,-2,-785 976,334,-290,-891,704,-581 150,-798,689,-823,237,-639 -551,-320,876,-502,-622,-628 -136,845,904,595,-702,-261 -857,-377,-522,-101,-943,-805 -682,-787,-888,-459,-752,-985 -571,-81,623,-133,447,643 -375,-158,72,-387,-324,-696 -660,-650,340,188,569,526 727,-218,16,-7,-595,-988 -966,-684,802,-783,-272,-194 115,-566,-888,47,712,180 -237,-69,45,-272,981,-812 48,897,439,417,50,325 348,616,180,254,104,-784 -730,811,-548,612,-736,790 138,-810,123,930,65,865 -768,-299,-49,-895,-692,-418 487,-531,802,-159,-12,634 808,-179,552,-73,470,717 720,-644,886,-141,625,144 -485,-505,-347,-244,-916,66 600,-565,995,-5,324,227 -771,-35,904,-482,753,-303 -701,65,426,-763,-504,-479 409,733,-823,475,64,718 865,975,368,893,-413,-433 812,-597,-970,819,813,624 193,-642,-381,-560,545,398 711,28,-316,771,717,-865 -509,462,809,-136,786,635 618,-49,484,169,635,547 -747,685,-882,-496,-332,82 -501,-851,870,563,290,570 -279,-829,-509,397,457,816 -508,80,850,-188,483,-326 860,-100,360,119,-205,787 -870,21,-39,-827,-185,932 826,284,-136,-866,-330,-97 -944,-82,745,899,-97,365 929,262,564,632,-115,632 244,-276,713,330,-897,-214 -890,-109,664,876,-974,-907 716,249,816,489,723,141 -96,-560,-272,45,-70,645 762,-503,414,-828,-254,-646 909,-13,903,-422,-344,-10 658,-486,743,545,50,674 -241,507,-367,18,-48,-241 886,-268,884,-762,120,-486 -412,-528,879,-647,223,-393 851,810,234,937,-726,797 -999,942,839,-134,-996,-189 100,979,-527,-521,378,800 544,-844,-832,-530,-77,-641 43,889,31,442,-934,-503 -330,-370,-309,-439,173,547 169,945,62,-753,-542,-597 208,751,-372,-647,-520,70 765,-840,907,-257,379,918 334,-135,-689,730,-427,618 137,-508,66,-695,78,169 -962,-123,400,-417,151,969 328,689,666,427,-555,-642 -907,343,605,-341,-647,582 -667,-363,-571,818,-265,-399 525,-938,904,898,725,692 -176,-802,-858,-9,780,275 580,170,-740,287,691,-97 365,557,-375,361,-288,859 193,737,842,-808,520,282 -871,65,-799,836,179,-720 958,-144,744,-789,797,-48 122,582,662,912,68,757 595,241,-801,513,388,186 -103,-677,-259,-731,-281,-857 921,319,-696,683,-88,-997 775,200,78,858,648,768 316,821,-763,68,-290,-741 564,664,691,504,760,787 694,-119,973,-385,309,-760 777,-947,-57,990,74,19 971,626,-496,-781,-602,-239 -651,433,11,-339,939,294 -965,-728,560,569,-708,-247
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: """ Implement a popular pi-digit-extraction algorithm known as the Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi. Wikipedia page: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula @param digit_position: a positive integer representing the position of the digit to extract. The digit immediately after the decimal point is located at position 1. @param precision: number of terms in the second summation to calculate. A higher number reduces the chance of an error but increases the runtime. @return: a hexadecimal digit representing the digit at the nth position in pi's decimal expansion. >>> "".join(bailey_borwein_plouffe(i) for i in range(1, 11)) '243f6a8885' >>> bailey_borwein_plouffe(5, 10000) '6' >>> bailey_borwein_plouffe(-10) Traceback (most recent call last): ... ValueError: Digit position must be a positive integer >>> bailey_borwein_plouffe(0) Traceback (most recent call last): ... ValueError: Digit position must be a positive integer >>> bailey_borwein_plouffe(1.7) Traceback (most recent call last): ... ValueError: Digit position must be a positive integer >>> bailey_borwein_plouffe(2, -10) Traceback (most recent call last): ... ValueError: Precision must be a nonnegative integer >>> bailey_borwein_plouffe(2, 1.6) Traceback (most recent call last): ... ValueError: Precision must be a nonnegative integer """ if (not isinstance(digit_position, int)) or (digit_position <= 0): raise ValueError("Digit position must be a positive integer") elif (not isinstance(precision, int)) or (precision < 0): raise ValueError("Precision must be a nonnegative integer") # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly # accurate sum_result = ( 4 * _subsum(digit_position, 1, precision) - 2 * _subsum(digit_position, 4, precision) - _subsum(digit_position, 5, precision) - _subsum(digit_position, 6, precision) ) # return the first hex digit of the fractional part of the result return hex(int((sum_result % 1) * 16))[2:] def _subsum( digit_pos_to_extract: int, denominator_addend: int, precision: int ) -> float: # only care about first digit of fractional part; don't need decimal """ Private helper function to implement the summation functionality. @param digit_pos_to_extract: digit position to extract @param denominator_addend: added to denominator of fractions in the formula @param precision: same as precision in main function @return: floating-point number whose integer part is not important """ sum = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend if sum_index < digit_pos_to_extract: # if the exponential term is an integer and we mod it by the denominator # before dividing, only the integer part of the sum will change; # the fractional part will not exponential_term = pow( 16, digit_pos_to_extract - 1 - sum_index, denominator ) else: exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) sum += exponential_term / denominator return sum if __name__ == "__main__": import doctest doctest.testmod()
def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: """ Implement a popular pi-digit-extraction algorithm known as the Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi. Wikipedia page: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula @param digit_position: a positive integer representing the position of the digit to extract. The digit immediately after the decimal point is located at position 1. @param precision: number of terms in the second summation to calculate. A higher number reduces the chance of an error but increases the runtime. @return: a hexadecimal digit representing the digit at the nth position in pi's decimal expansion. >>> "".join(bailey_borwein_plouffe(i) for i in range(1, 11)) '243f6a8885' >>> bailey_borwein_plouffe(5, 10000) '6' >>> bailey_borwein_plouffe(-10) Traceback (most recent call last): ... ValueError: Digit position must be a positive integer >>> bailey_borwein_plouffe(0) Traceback (most recent call last): ... ValueError: Digit position must be a positive integer >>> bailey_borwein_plouffe(1.7) Traceback (most recent call last): ... ValueError: Digit position must be a positive integer >>> bailey_borwein_plouffe(2, -10) Traceback (most recent call last): ... ValueError: Precision must be a nonnegative integer >>> bailey_borwein_plouffe(2, 1.6) Traceback (most recent call last): ... ValueError: Precision must be a nonnegative integer """ if (not isinstance(digit_position, int)) or (digit_position <= 0): raise ValueError("Digit position must be a positive integer") elif (not isinstance(precision, int)) or (precision < 0): raise ValueError("Precision must be a nonnegative integer") # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly # accurate sum_result = ( 4 * _subsum(digit_position, 1, precision) - 2 * _subsum(digit_position, 4, precision) - _subsum(digit_position, 5, precision) - _subsum(digit_position, 6, precision) ) # return the first hex digit of the fractional part of the result return hex(int((sum_result % 1) * 16))[2:] def _subsum( digit_pos_to_extract: int, denominator_addend: int, precision: int ) -> float: # only care about first digit of fractional part; don't need decimal """ Private helper function to implement the summation functionality. @param digit_pos_to_extract: digit position to extract @param denominator_addend: added to denominator of fractions in the formula @param precision: same as precision in main function @return: floating-point number whose integer part is not important """ sum = 0.0 for sum_index in range(digit_pos_to_extract + precision): denominator = 8 * sum_index + denominator_addend if sum_index < digit_pos_to_extract: # if the exponential term is an integer and we mod it by the denominator # before dividing, only the integer part of the sum will change; # the fractional part will not exponential_term = pow( 16, digit_pos_to_extract - 1 - sum_index, denominator ) else: exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) sum += exponential_term / denominator return sum if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 bubble_sort(collection): """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) True >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5]) True >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> bubble_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> bubble_sort(collection) == sorted(collection) True """ length = len(collection) for i in range(length - 1): swapped = False for j in range(length - 1 - i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break # Stop iteration if the collection is sorted. return collection if __name__ == "__main__": import doctest import time doctest.testmod() user_input = input("Enter numbers separated by a comma:").strip() unsorted = [int(item) for item in user_input.split(",")] start = time.process_time() print(*bubble_sort(unsorted), sep=",") print(f"Processing time: {time.process_time() - start}")
def bubble_sort(collection): """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) True >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5]) True >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> bubble_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> bubble_sort(collection) == sorted(collection) True """ length = len(collection) for i in range(length - 1): swapped = False for j in range(length - 1 - i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break # Stop iteration if the collection is sorted. return collection if __name__ == "__main__": import doctest import time doctest.testmod() user_input = input("Enter numbers separated by a comma:").strip() unsorted = [int(item) for item in user_input.split(",")] start = time.process_time() print(*bubble_sort(unsorted), sep=",") print(f"Processing time: {time.process_time() - start}")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""For reference https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort """ def odd_even_sort(input_list: list) -> list: """this algorithm uses the same idea of bubblesort, but by first dividing in two phase (odd and even). Originally developed for use on parallel processors with local interconnections. :param collection: mutable ordered sequence of elements :return: same collection in ascending order Examples: >>> odd_even_sort([5 , 4 ,3 ,2 ,1]) [1, 2, 3, 4, 5] >>> odd_even_sort([]) [] >>> odd_even_sort([-10 ,-1 ,10 ,2]) [-10, -1, 2, 10] >>> odd_even_sort([1 ,2 ,3 ,4]) [1, 2, 3, 4] """ sorted = False while sorted is False: # Until all the indices are traversed keep looping sorted = True for i in range(0, len(input_list) - 1, 2): # iterating over all even indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order sorted = False for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order sorted = False return input_list if __name__ == "__main__": print("Enter list to be sorted") input_list = [int(x) for x in input().split()] # inputing elements of the list in one line sorted_list = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
"""For reference https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort """ def odd_even_sort(input_list: list) -> list: """this algorithm uses the same idea of bubblesort, but by first dividing in two phase (odd and even). Originally developed for use on parallel processors with local interconnections. :param collection: mutable ordered sequence of elements :return: same collection in ascending order Examples: >>> odd_even_sort([5 , 4 ,3 ,2 ,1]) [1, 2, 3, 4, 5] >>> odd_even_sort([]) [] >>> odd_even_sort([-10 ,-1 ,10 ,2]) [-10, -1, 2, 10] >>> odd_even_sort([1 ,2 ,3 ,4]) [1, 2, 3, 4] """ sorted = False while sorted is False: # Until all the indices are traversed keep looping sorted = True for i in range(0, len(input_list) - 1, 2): # iterating over all even indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order sorted = False for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order sorted = False return input_list if __name__ == "__main__": print("Enter list to be sorted") input_list = [int(x) for x in input().split()] # inputing elements of the list in one line sorted_list = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The frequency # of the node is defined as how many time the node is being searched. # The search cost of binary search tree is given by this formula: # # cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq) # # where n is number of nodes in the BST. The characteristic of low-cost # BSTs is having a faster overall search time than other implementations. # The reason for their fast search time is that the nodes with high # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. import sys from random import randint class Node: """Binary Search Tree Node""" def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): """ >>> str(Node(1, 2)) 'Node(key=1, freq=2)' """ return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): """ Recursive function to print a BST from a root table. >>> key = [3, 8, 9, 10, 17, 21] >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] >>> print_binary_search_tree(root, key, 0, 5, -1, False) 8 is the root of the binary search tree. 3 is the left child of key 8. 10 is the right child of key 8. 9 is the left child of key 10. 21 is the right child of key 10. 17 is the left child of key 21. """ if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): """ This function calculates and prints the optimal binary search tree. The dynamic programming algorithm below runs in O(n^2) time. Implemented from CLRS (Introduction to Algorithms) book. https://en.wikipedia.org/wiki/Introduction_to_Algorithms >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \ Node(42, 3), Node(25, 40), Node(37, 30)]) Binary search tree nodes: Node(key=10, freq=34) Node(key=12, freq=8) Node(key=20, freq=50) Node(key=25, freq=40) Node(key=37, freq=30) Node(key=42, freq=3) <BLANKLINE> The cost of optimal BST for given tree nodes is 324. 20 is the root of the binary search tree. 10 is the left child of key 20. 12 is the right child of key 10. 25 is the right child of key 20. 37 is the right child of key 25. 42 is the right child of key 37. """ # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] # This 2D array stores the overall tree cost (which's as minimized as possible); # for a single key, cost is equal to frequency of the key. dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array sum = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" sum[i][j] = sum[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree cost = left + sum[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
#!/usr/bin/env python3 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The frequency # of the node is defined as how many time the node is being searched. # The search cost of binary search tree is given by this formula: # # cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq) # # where n is number of nodes in the BST. The characteristic of low-cost # BSTs is having a faster overall search time than other implementations. # The reason for their fast search time is that the nodes with high # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. import sys from random import randint class Node: """Binary Search Tree Node""" def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): """ >>> str(Node(1, 2)) 'Node(key=1, freq=2)' """ return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): """ Recursive function to print a BST from a root table. >>> key = [3, 8, 9, 10, 17, 21] >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] >>> print_binary_search_tree(root, key, 0, 5, -1, False) 8 is the root of the binary search tree. 3 is the left child of key 8. 10 is the right child of key 8. 9 is the left child of key 10. 21 is the right child of key 10. 17 is the left child of key 21. """ if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): """ This function calculates and prints the optimal binary search tree. The dynamic programming algorithm below runs in O(n^2) time. Implemented from CLRS (Introduction to Algorithms) book. https://en.wikipedia.org/wiki/Introduction_to_Algorithms >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \ Node(42, 3), Node(25, 40), Node(37, 30)]) Binary search tree nodes: Node(key=10, freq=34) Node(key=12, freq=8) Node(key=20, freq=50) Node(key=25, freq=40) Node(key=37, freq=30) Node(key=42, freq=3) <BLANKLINE> The cost of optimal BST for given tree nodes is 324. 20 is the root of the binary search tree. 10 is the left child of key 20. 12 is the right child of key 10. 25 is the right child of key 20. 37 is the right child of key 25. 42 is the right child of key 37. """ # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] # This 2D array stores the overall tree cost (which's as minimized as possible); # for a single key, cost is equal to frequency of the key. dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array sum = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" sum[i][j] = sum[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree cost = left + sum[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
from __future__ import annotations def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 Heap: """ A generic Heap class, can be used as min or max by passing the key function accordingly. """ def __init__(self, key=None): # Stores actual heap items. self.arr = list() # Stores indexes of each item for supporting updates and deletion. self.pos_map = {} # Stores current size of heap. self.size = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. self.key = key or (lambda x: x) def _parent(self, i): """Returns parent index of given index if exists else None""" return int((i - 1) / 2) if i > 0 else None def _left(self, i): """Returns left-child-index of given index if exists else None""" left = int(2 * i + 1) return left if 0 < left < self.size else None def _right(self, i): """Returns right-child-index of given index if exists else None""" right = int(2 * i + 2) return right if 0 < right < self.size else None def _swap(self, i, j): """Performs changes required for swapping two elements in the heap""" # First update the indexes of the items in index map. self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. self.arr[i], self.arr[j] = self.arr[j], self.arr[i] def _cmp(self, i, j): """Compares the two items using default comparison""" return self.arr[i][1] < self.arr[j][1] def _get_valid_parent(self, i): """ Returns index of valid parent as per desired ordering among given index and both it's children """ left = self._left(i) right = self._right(i) valid_parent = i if left is not None and not self._cmp(left, valid_parent): valid_parent = left if right is not None and not self._cmp(right, valid_parent): valid_parent = right return valid_parent def _heapify_up(self, index): """Fixes the heap in upward direction of given index""" parent = self._parent(index) while parent is not None and not self._cmp(index, parent): self._swap(index, parent) index, parent = parent, self._parent(parent) def _heapify_down(self, index): """Fixes the heap in downward direction of given index""" valid_parent = self._get_valid_parent(index) while valid_parent != index: self._swap(index, valid_parent) index, valid_parent = valid_parent, self._get_valid_parent(valid_parent) def update_item(self, item, item_value): """Updates given item value in heap if present""" if item not in self.pos_map: return index = self.pos_map[item] self.arr[index] = [item, self.key(item_value)] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(index) self._heapify_down(index) def delete_item(self, item): """Deletes given item from heap if present""" if item not in self.pos_map: return index = self.pos_map[item] del self.pos_map[item] self.arr[index] = self.arr[self.size - 1] self.pos_map[self.arr[self.size - 1][0]] = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(index) self._heapify_down(index) def insert_item(self, item, item_value): """Inserts given item with given value in heap""" arr_len = len(self.arr) if arr_len == self.size: self.arr.append([item, self.key(item_value)]) else: self.arr[self.size] = [item, self.key(item_value)] self.pos_map[item] = self.size self.size += 1 self._heapify_up(self.size - 1) def get_top(self): """Returns top item tuple (Calculated value, item) from heap if present""" return self.arr[0] if self.size else None def extract_top(self): """ Return top item tuple (Calculated value, item) from heap and removes it as well if present """ top_item_tuple = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0]) return top_item_tuple def test_heap() -> None: """ >>> h = Heap() # Max-heap >>> h.insert_item(5, 34) >>> h.insert_item(6, 31) >>> h.insert_item(7, 37) >>> h.get_top() [7, 37] >>> h.extract_top() [7, 37] >>> h.extract_top() [5, 34] >>> h.extract_top() [6, 31] >>> h = Heap(key=lambda x: -x) # Min heap >>> h.insert_item(5, 34) >>> h.insert_item(6, 31) >>> h.insert_item(7, 37) >>> h.get_top() [6, -31] >>> h.extract_top() [6, -31] >>> h.extract_top() [5, -34] >>> h.extract_top() [7, -37] >>> h.insert_item(8, 45) >>> h.insert_item(9, 40) >>> h.insert_item(10, 50) >>> h.get_top() [9, -40] >>> h.update_item(10, 30) >>> h.get_top() [10, -30] >>> h.delete_item(10) >>> h.get_top() [9, -40] """ pass if __name__ == "__main__": import doctest doctest.testmod()
class Heap: """ A generic Heap class, can be used as min or max by passing the key function accordingly. """ def __init__(self, key=None): # Stores actual heap items. self.arr = list() # Stores indexes of each item for supporting updates and deletion. self.pos_map = {} # Stores current size of heap. self.size = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. self.key = key or (lambda x: x) def _parent(self, i): """Returns parent index of given index if exists else None""" return int((i - 1) / 2) if i > 0 else None def _left(self, i): """Returns left-child-index of given index if exists else None""" left = int(2 * i + 1) return left if 0 < left < self.size else None def _right(self, i): """Returns right-child-index of given index if exists else None""" right = int(2 * i + 2) return right if 0 < right < self.size else None def _swap(self, i, j): """Performs changes required for swapping two elements in the heap""" # First update the indexes of the items in index map. self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. self.arr[i], self.arr[j] = self.arr[j], self.arr[i] def _cmp(self, i, j): """Compares the two items using default comparison""" return self.arr[i][1] < self.arr[j][1] def _get_valid_parent(self, i): """ Returns index of valid parent as per desired ordering among given index and both it's children """ left = self._left(i) right = self._right(i) valid_parent = i if left is not None and not self._cmp(left, valid_parent): valid_parent = left if right is not None and not self._cmp(right, valid_parent): valid_parent = right return valid_parent def _heapify_up(self, index): """Fixes the heap in upward direction of given index""" parent = self._parent(index) while parent is not None and not self._cmp(index, parent): self._swap(index, parent) index, parent = parent, self._parent(parent) def _heapify_down(self, index): """Fixes the heap in downward direction of given index""" valid_parent = self._get_valid_parent(index) while valid_parent != index: self._swap(index, valid_parent) index, valid_parent = valid_parent, self._get_valid_parent(valid_parent) def update_item(self, item, item_value): """Updates given item value in heap if present""" if item not in self.pos_map: return index = self.pos_map[item] self.arr[index] = [item, self.key(item_value)] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(index) self._heapify_down(index) def delete_item(self, item): """Deletes given item from heap if present""" if item not in self.pos_map: return index = self.pos_map[item] del self.pos_map[item] self.arr[index] = self.arr[self.size - 1] self.pos_map[self.arr[self.size - 1][0]] = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(index) self._heapify_down(index) def insert_item(self, item, item_value): """Inserts given item with given value in heap""" arr_len = len(self.arr) if arr_len == self.size: self.arr.append([item, self.key(item_value)]) else: self.arr[self.size] = [item, self.key(item_value)] self.pos_map[item] = self.size self.size += 1 self._heapify_up(self.size - 1) def get_top(self): """Returns top item tuple (Calculated value, item) from heap if present""" return self.arr[0] if self.size else None def extract_top(self): """ Return top item tuple (Calculated value, item) from heap and removes it as well if present """ top_item_tuple = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0]) return top_item_tuple def test_heap() -> None: """ >>> h = Heap() # Max-heap >>> h.insert_item(5, 34) >>> h.insert_item(6, 31) >>> h.insert_item(7, 37) >>> h.get_top() [7, 37] >>> h.extract_top() [7, 37] >>> h.extract_top() [5, 34] >>> h.extract_top() [6, 31] >>> h = Heap(key=lambda x: -x) # Min heap >>> h.insert_item(5, 34) >>> h.insert_item(6, 31) >>> h.insert_item(7, 37) >>> h.get_top() [6, -31] >>> h.extract_top() [6, -31] >>> h.extract_top() [5, -34] >>> h.extract_top() [7, -37] >>> h.insert_item(8, 45) >>> h.insert_item(9, 40) >>> h.insert_item(10, 50) >>> h.get_top() [9, -40] >>> h.update_item(10, 30) >>> h.get_top() [10, -30] >>> h.delete_item(10) >>> h.get_top() [9, -40] """ pass if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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: P Shreyas Shetty Implementation of Newton-Raphson method for solving equations of kind f(x) = 0. It is an iterative method where solution is found by the expression x[n+1] = x[n] + f(x[n])/f'(x[n]) If no solution exists, then either the solution will not be found when iteration limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception is raised. If iteration limit is reached, try increasing maxiter. """ import math as m def calc_derivative(f, a, h=0.001): """ Calculates derivative at point a for function f using finite difference method """ return (f(a + h) - f(a - h)) / (2 * h) def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False): a = x0 # set the initial guess steps = [a] error = abs(f(a)) f1 = lambda x: calc_derivative(f, x, h=step) # noqa: E731 Derivative of f(x) for _ in range(maxiter): if f1(a) == 0: raise ValueError("No converging solution found") a = a - f(a) / f1(a) # Calculate the next estimate if logsteps: steps.append(a) if error < maxerror: break else: raise ValueError("Iteration limit reached, no converging solution found") if logsteps: # If logstep is true, then log intermediate steps return a, error, steps return a, error if __name__ == "__main__": from matplotlib import pyplot as plt f = lambda x: m.tanh(x) ** 2 - m.exp(3 * x) # noqa: E731 solution, error, steps = newton_raphson( f, x0=10, maxiter=1000, step=1e-6, logsteps=True ) plt.plot([abs(f(x)) for x in steps]) plt.xlabel("step") plt.ylabel("error") plt.show() print(f"solution = {{{solution:f}}}, error = {{{error:f}}}")
""" Author: P Shreyas Shetty Implementation of Newton-Raphson method for solving equations of kind f(x) = 0. It is an iterative method where solution is found by the expression x[n+1] = x[n] + f(x[n])/f'(x[n]) If no solution exists, then either the solution will not be found when iteration limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception is raised. If iteration limit is reached, try increasing maxiter. """ import math as m def calc_derivative(f, a, h=0.001): """ Calculates derivative at point a for function f using finite difference method """ return (f(a + h) - f(a - h)) / (2 * h) def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False): a = x0 # set the initial guess steps = [a] error = abs(f(a)) f1 = lambda x: calc_derivative(f, x, h=step) # noqa: E731 Derivative of f(x) for _ in range(maxiter): if f1(a) == 0: raise ValueError("No converging solution found") a = a - f(a) / f1(a) # Calculate the next estimate if logsteps: steps.append(a) if error < maxerror: break else: raise ValueError("Iteration limit reached, no converging solution found") if logsteps: # If logstep is true, then log intermediate steps return a, error, steps return a, error if __name__ == "__main__": from matplotlib import pyplot as plt f = lambda x: m.tanh(x) ** 2 - m.exp(3 * x) # noqa: E731 solution, error, steps = newton_raphson( f, x0=10, maxiter=1000, step=1e-6, logsteps=True ) plt.plot([abs(f(x)) for x in steps]) plt.xlabel("step") plt.ylabel("error") plt.show() print(f"solution = {{{solution:f}}}, error = {{{error:f}}}")
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Hey, we are going to find an exciting number called Catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes. We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i) Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number """ """ Our Contribution: Basically we Create the 2 function: 1. catalan_number(node_count: int) -> int Returns the number of possible binary search trees for n nodes. 2. binary_tree_count(node_count: int) -> int Returns the number of possible binary trees for n nodes. """ def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, 2) 6 """ result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): k = n - k # Calculate C(n,k) for i in range(k): result *= n - i result //= i + 1 return result def catalan_number(node_count: int) -> int: """ We can find Catalan number many ways but here we use Binomial Coefficient because it does the job in O(n) return the Catalan number of n using 2nCn/(n+1). :param n: number of nodes :return: Catalan number of n nodes >>> catalan_number(5) 42 >>> catalan_number(6) 132 """ return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: """ Return the factorial of a number. :param n: Number to find the Factorial of. :return: Factorial of n. >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(10)) True >>> factorial(-5) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result def binary_tree_count(node_count: int) -> int: """ Return the number of possible of binary trees. :param n: number of nodes :return: Number of possible binary trees >>> binary_tree_count(5) 5040 >>> binary_tree_count(6) 95040 """ return catalan_number(node_count) * factorial(node_count) if __name__ == "__main__": node_count = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." )
""" Hey, we are going to find an exciting number called Catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes. We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i) Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number """ """ Our Contribution: Basically we Create the 2 function: 1. catalan_number(node_count: int) -> int Returns the number of possible binary search trees for n nodes. 2. binary_tree_count(node_count: int) -> int Returns the number of possible binary trees for n nodes. """ def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, 2) 6 """ result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): k = n - k # Calculate C(n,k) for i in range(k): result *= n - i result //= i + 1 return result def catalan_number(node_count: int) -> int: """ We can find Catalan number many ways but here we use Binomial Coefficient because it does the job in O(n) return the Catalan number of n using 2nCn/(n+1). :param n: number of nodes :return: Catalan number of n nodes >>> catalan_number(5) 42 >>> catalan_number(6) 132 """ return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: """ Return the factorial of a number. :param n: Number to find the Factorial of. :return: Factorial of n. >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(10)) True >>> factorial(-5) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result def binary_tree_count(node_count: int) -> int: """ Return the number of possible of binary trees. :param n: number of nodes :return: Number of possible binary trees >>> binary_tree_count(5) 5040 >>> binary_tree_count(6) 95040 """ return catalan_number(node_count) * factorial(node_count) if __name__ == "__main__": node_count = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." )
-1
TheAlgorithms/Python
5,817
Add missing type annotations for `strings` directory
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Rohanrbharadwaj
"2021-11-11T11:21:24Z"
"2022-05-13T05:55:54Z"
bbb88bb5c261085ff23bce2b3c17266ebfa7b087
e95ecfaf27c545391bdb7a2d1d8948943a40f828
Add missing type annotations for `strings` directory. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/Best-first_search#Greedy_BFS """ from __future__ import annotations Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class Node: """ >>> k = Node(0, 0, 4, 5, 0, None) >>> k.calculate_heuristic() 9 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, g_cost: float, parent: Node | None, ): self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.g_cost = g_cost self.parent = parent self.f_cost = self.calculate_heuristic() def calculate_heuristic(self) -> float: """ The heuristic here is the Manhattan Distance Could elaborate to offer more than one choice """ dy = abs(self.pos_x - self.goal_x) dx = abs(self.pos_y - self.goal_y) return dx + dy def __lt__(self, other) -> bool: return self.f_cost < other.f_cost class GreedyBestFirst: """ >>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> [x.pos for x in gbf.get_successors(gbf.start)] [(1, 0), (0, 1)] >>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1]) (0, 1) >>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1]) (1, 0) >>> gbf.retrace_path(gbf.start) [(0, 0)] >>> gbf.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)] """ def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False def search(self) -> Path | None: """ Search for the path, if a path is not found, only the starting position is returned """ while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: self.reached = True return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) if not self.reached: return [self.start.pos] return None def get_successors(self, parent: Node) -> list[Node]: """ Returns a list of successors (both in the grid and free spaces) """ successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors def retrace_path(self, node: Node | None) -> Path: """ Retrace the path from parents to parents until start node """ current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path if __name__ == "__main__": init = (0, 0) goal = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("------") greedy_bf = GreedyBestFirst(init, goal) path = greedy_bf.search() if path: for pos_x, pos_y in path: grid[pos_x][pos_y] = 2 for elem in grid: print(elem)
""" https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS """ from __future__ import annotations Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class Node: """ >>> k = Node(0, 0, 4, 5, 0, None) >>> k.calculate_heuristic() 9 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, g_cost: float, parent: Node | None, ): self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.g_cost = g_cost self.parent = parent self.f_cost = self.calculate_heuristic() def calculate_heuristic(self) -> float: """ The heuristic here is the Manhattan Distance Could elaborate to offer more than one choice """ dy = abs(self.pos_x - self.goal_x) dx = abs(self.pos_y - self.goal_y) return dx + dy def __lt__(self, other) -> bool: return self.f_cost < other.f_cost class GreedyBestFirst: """ >>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> [x.pos for x in gbf.get_successors(gbf.start)] [(1, 0), (0, 1)] >>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1]) (0, 1) >>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1]) (1, 0) >>> gbf.retrace_path(gbf.start) [(0, 0)] >>> gbf.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)] """ def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False def search(self) -> Path | None: """ Search for the path, if a path is not found, only the starting position is returned """ while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: self.reached = True return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) if not self.reached: return [self.start.pos] return None def get_successors(self, parent: Node) -> list[Node]: """ Returns a list of successors (both in the grid and free spaces) """ successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors def retrace_path(self, node: Node | None) -> Path: """ Retrace the path from parents to parents until start node """ current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path if __name__ == "__main__": init = (0, 0) goal = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("------") greedy_bf = GreedyBestFirst(init, goal) path = greedy_bf.search() if path: for pos_x, pos_y in path: grid[pos_x][pos_y] = 2 for elem in grid: print(elem)
-1