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
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley ([email protected]), [email protected]", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. [Source] Wikipedia [Credit] Rosetta Code C implementation helped very much. (https://rosettacode.org/wiki/Banker%27s_algorithm) """ from __future__ import annotations import time import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: """ :param claim_vector: A nxn/nxm list depicting the amount of each resources (eg. memory, interface, semaphores, etc.) available. :param allocated_resources_table: A nxn/nxm list depicting the amount of each resource each process is currently holding :param maximum_claim_table: A nxn/nxm list depicting how much of each resource the system currently has available """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: """ Check for allocated resources in line with each resource in the claim vector """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: """ Check for available resources in line with each resource in the claim vector """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: """ Implement safety checker that calculates the needs by ensuring that max_claim[i][j] - alloc_table[i][j] <= avail[j] """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: """ This function builds an index control dictionary to track original ids/indices of processes when altered during execution of method "main" Return: {0: [a: int, b: int], 1: [c: int, d: int]} >>> (BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table)._BankersAlgorithm__need_index_manager() ... ) # doctest: +NORMALIZE_WHITESPACE {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], 4: [2, 0, 0, 3]} """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: """ Utilize various methods in this class to simulate the Banker's algorithm Return: None >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table).main(describe=True) Allocated Resource Table P1 2 0 1 1 <BLANKLINE> P2 0 1 2 1 <BLANKLINE> P3 4 0 0 3 <BLANKLINE> P4 0 2 1 0 <BLANKLINE> P5 1 0 3 0 <BLANKLINE> System Resource Table P1 3 2 1 4 <BLANKLINE> P2 0 2 5 2 <BLANKLINE> P3 5 1 0 5 <BLANKLINE> P4 1 5 3 0 <BLANKLINE> P5 3 0 3 3 <BLANKLINE> Current Usage by Active Processes: 8 5 9 7 Initial Available Resources: 1 2 2 2 __________________________________________________ <BLANKLINE> Process 3 is executing. Updated available resource stack for processes: 5 2 2 5 The process is in a safe state. <BLANKLINE> Process 1 is executing. Updated available resource stack for processes: 7 2 3 6 The process is in a safe state. <BLANKLINE> Process 2 is executing. Updated available resource stack for processes: 7 3 5 7 The process is in a safe state. <BLANKLINE> Process 4 is executing. Updated available resource stack for processes: 7 5 6 7 The process is in a safe state. <BLANKLINE> Process 5 is executing. Updated available resource stack for processes: 8 5 9 7 The process is in a safe state. <BLANKLINE> """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): """ Properly align display of the algorithm's solution """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley ([email protected]), [email protected]", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. [Source] Wikipedia [Credit] Rosetta Code C implementation helped very much. (https://rosettacode.org/wiki/Banker%27s_algorithm) """ from __future__ import annotations import time import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: """ :param claim_vector: A nxn/nxm list depicting the amount of each resources (eg. memory, interface, semaphores, etc.) available. :param allocated_resources_table: A nxn/nxm list depicting the amount of each resource each process is currently holding :param maximum_claim_table: A nxn/nxm list depicting how much of each resource the system currently has available """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: """ Check for allocated resources in line with each resource in the claim vector """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: """ Check for available resources in line with each resource in the claim vector """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: """ Implement safety checker that calculates the needs by ensuring that max_claim[i][j] - alloc_table[i][j] <= avail[j] """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: """ This function builds an index control dictionary to track original ids/indices of processes when altered during execution of method "main" Return: {0: [a: int, b: int], 1: [c: int, d: int]} >>> (BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table)._BankersAlgorithm__need_index_manager() ... ) # doctest: +NORMALIZE_WHITESPACE {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], 4: [2, 0, 0, 3]} """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: """ Utilize various methods in this class to simulate the Banker's algorithm Return: None >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table).main(describe=True) Allocated Resource Table P1 2 0 1 1 <BLANKLINE> P2 0 1 2 1 <BLANKLINE> P3 4 0 0 3 <BLANKLINE> P4 0 2 1 0 <BLANKLINE> P5 1 0 3 0 <BLANKLINE> System Resource Table P1 3 2 1 4 <BLANKLINE> P2 0 2 5 2 <BLANKLINE> P3 5 1 0 5 <BLANKLINE> P4 1 5 3 0 <BLANKLINE> P5 3 0 3 3 <BLANKLINE> Current Usage by Active Processes: 8 5 9 7 Initial Available Resources: 1 2 2 2 __________________________________________________ <BLANKLINE> Process 3 is executing. Updated available resource stack for processes: 5 2 2 5 The process is in a safe state. <BLANKLINE> Process 1 is executing. Updated available resource stack for processes: 7 2 3 6 The process is in a safe state. <BLANKLINE> Process 2 is executing. Updated available resource stack for processes: 7 3 5 7 The process is in a safe state. <BLANKLINE> Process 4 is executing. Updated available resource stack for processes: 7 5 6 7 The process is in a safe state. <BLANKLINE> Process 5 is executing. Updated available resource stack for processes: 8 5 9 7 The process is in a safe state. <BLANKLINE> """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): """ Properly align display of the algorithm's solution """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
-1
TheAlgorithms/Python
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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 is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 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(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 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
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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 : Syed Faizan ( 3rd Year IIIT Pune ) Github : faizan2700 Purpose : You have one function f(x) which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpsons in 1743 is one way to calculate integration. ( read article : https://cp-algorithms.com/num_methods/simpson-integration.html ) simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and returns the integration of function in given limit. """ # constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: """ Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integration precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer >>> simpson_integration(lambda x : x*x,1,2,3) 2.333 >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) Traceback (most recent call last): ... AssertionError: a should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) Traceback (most recent call last): ... AssertionError: b should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : wrong_input >>> simpson_integration('wrong_input',2,3,4) Traceback (most recent call last): ... AssertionError: the function(object) passed should be callable your input : ... >>> simpson_integration(lambda x : x*x,3.45,3.2,1) -2.8 >>> simpson_integration(lambda x : x*x,3.45,3.2,0) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : 0 >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : -1 """ assert callable( function ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" assert ( isinstance(precision, int) and precision > 0 ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Syed Faizan ( 3rd Year IIIT Pune ) Github : faizan2700 Purpose : You have one function f(x) which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpsons in 1743 is one way to calculate integration. ( read article : https://cp-algorithms.com/num_methods/simpson-integration.html ) simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and returns the integration of function in given limit. """ # constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: """ Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integration precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer >>> simpson_integration(lambda x : x*x,1,2,3) 2.333 >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) Traceback (most recent call last): ... AssertionError: a should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) Traceback (most recent call last): ... AssertionError: b should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : wrong_input >>> simpson_integration('wrong_input',2,3,4) Traceback (most recent call last): ... AssertionError: the function(object) passed should be callable your input : ... >>> simpson_integration(lambda x : x*x,3.45,3.2,1) -2.8 >>> simpson_integration(lambda x : x*x,3.45,3.2,0) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : 0 >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : -1 """ assert callable( function ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" assert ( isinstance(precision, int) and precision > 0 ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Check whether Graph is Bipartite or Not using BFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. from queue import Queue def check_bipartite(graph): queue = Queue() visited = [False] * len(graph) color = [-1] * len(graph) def bfs(): while not queue.empty(): u = queue.get() visited[u] = True for neighbour in graph[u]: if neighbour == u: return False if color[neighbour] == -1: color[neighbour] = 1 - color[u] queue.put(neighbour) elif color[neighbour] == color[u]: return False return True for i in range(len(graph)): if not visited[i]: queue.put(i) color[i] = 0 if bfs() is False: return False return True if __name__ == "__main__": # Adjacency List of graph print(check_bipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))
# Check whether Graph is Bipartite or Not using BFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. from queue import Queue def check_bipartite(graph): queue = Queue() visited = [False] * len(graph) color = [-1] * len(graph) def bfs(): while not queue.empty(): u = queue.get() visited[u] = True for neighbour in graph[u]: if neighbour == u: return False if color[neighbour] == -1: color[neighbour] = 1 - color[u] queue.put(neighbour) elif color[neighbour] == color[u]: return False return True for i in range(len(graph)): if not visited[i]: queue.put(i) color[i] = 0 if bfs() is False: return False return True if __name__ == "__main__": # Adjacency List of graph print(check_bipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))
-1
TheAlgorithms/Python
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Newton's Method.""" # Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method from collections.abc import Callable RealFunc = Callable[[float], float] # type alias for a real -> real function # function is the f(x) and derivative is the f'(x) def newton( function: RealFunc, derivative: RealFunc, starting_int: int, ) -> float: """ >>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3) 2.0945514815423474 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2) 1.0 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4) 1.0000000000000102 >>> import math >>> newton(math.sin, math.cos, 1) 0.0 >>> newton(math.sin, math.cos, 2) 3.141592653589793 >>> newton(math.cos, lambda x: -math.sin(x), 2) 1.5707963267948966 >>> newton(math.cos, lambda x: -math.sin(x), 0) Traceback (most recent call last): ... ZeroDivisionError: Could not find root """ prev_guess = float(starting_int) while True: try: next_guess = prev_guess - function(prev_guess) / derivative(prev_guess) except ZeroDivisionError: raise ZeroDivisionError("Could not find root") from None if abs(prev_guess - next_guess) < 10**-5: return next_guess prev_guess = next_guess def f(x: float) -> float: return (x**3) - (2 * x) - 5 def f1(x: float) -> float: return 3 * (x**2) - 2 if __name__ == "__main__": print(newton(f, f1, 3))
"""Newton's Method.""" # Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method from collections.abc import Callable RealFunc = Callable[[float], float] # type alias for a real -> real function # function is the f(x) and derivative is the f'(x) def newton( function: RealFunc, derivative: RealFunc, starting_int: int, ) -> float: """ >>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3) 2.0945514815423474 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2) 1.0 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4) 1.0000000000000102 >>> import math >>> newton(math.sin, math.cos, 1) 0.0 >>> newton(math.sin, math.cos, 2) 3.141592653589793 >>> newton(math.cos, lambda x: -math.sin(x), 2) 1.5707963267948966 >>> newton(math.cos, lambda x: -math.sin(x), 0) Traceback (most recent call last): ... ZeroDivisionError: Could not find root """ prev_guess = float(starting_int) while True: try: next_guess = prev_guess - function(prev_guess) / derivative(prev_guess) except ZeroDivisionError: raise ZeroDivisionError("Could not find root") from None if abs(prev_guess - next_guess) < 10**-5: return next_guess prev_guess = next_guess def f(x: float) -> float: return (x**3) - (2 * x) - 5 def f1(x: float) -> float: return 3 * (x**2) - 2 if __name__ == "__main__": print(newton(f, f1, 3))
-1
TheAlgorithms/Python
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,591
Test on Python 3.11
### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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
"2022-10-03T07:32:25Z"
"2022-10-31T13:50:03Z"
b2165a65fcf1a087236d2a1527b10b64a12f69e6
a31edd4477af958adb840dadd568c38eecc9567b
Test on Python 3.11. ### Describe your change: Problem deps are qiskit, statsmodels, and tensorflow: * https://github.com/Qiskit/qiskit-terra/issues/9028 * ~https://github.com/symengine/symengine.py/issues/422~ * https://github.com/statsmodels/statsmodels/issues/8287 * https://github.com/tensorflow/tensorflow/releases * [ ] Try a new Python * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points 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 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
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" 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(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 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
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(num: int) -> bool: """ Determines whether the given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True >>> is_prime(0) False """ if num == 2: return True elif num % 2 == 0: return False else: sq = int(sqrt(num)) + 1 for i in range(3, sq, 2): if num % i == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ count = 0 number = 1 while count != nth and number < 3: number += 1 if is_prime(number): count += 1 while count != nth: number += 2 if is_prime(number): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ count = 0 number = 1 while count != nth and number < 3: number += 1 if is_prime(number): count += 1 while count != nth: number += 2 if is_prime(number): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ def is_prime(number: int) -> bool: """ Determines whether the given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True """ for i in range(2, int(number**0.5) + 1): if number % i == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. """ try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes: list[int] = [] num = 2 while len(primes) < nth: if is_prime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. """ try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes: list[int] = [] num = 2 while len(primes) < nth: if is_prime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def is_prime(number: int) -> bool: """ Determines whether a given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ from math import sqrt def is_prime(n: int) -> bool: """ Returns boolean representing primality of given number num. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True """ if 1 < n < 4: return True elif n < 2 or not n % 2: return False return not any(not n % i for i in range(3, int(sqrt(n) + 1), 2)) def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0 if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ import math from collections.abc import Iterator from itertools import takewhile def is_prime(number: 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 """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator() -> Iterator[int]: """ Generate a list sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(takewhile(lambda x: x < n, prime_generator())) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number """ import math from collections.abc import Iterator from itertools import takewhile def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def prime_generator() -> Iterator[int]: """ Generate a list sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(takewhile(lambda x: x < n, prime_generator())) if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(k: int) -> bool: """ Determine if a number is prime >>> is_prime(10) False >>> is_prime(11) True """ if k < 2 or k % 2 == 0: return False elif k == 2: return True else: for x in range(3, int(math.sqrt(k) + 1), 2): if k % x == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(-10) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations seive = [True] * 1000001 seive[1] = False i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise, for 1 <= n <= 1000000 >>> is_prime(87) False >>> is_prime(1) False >>> is_prime(25363) False """ return seive[n] def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Pandigital prime Problem 41: https://projecteuler.net/problem=41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3. So we will check only 7 digit pandigital numbers to obtain the largest possible pandigital prime. """ from __future__ import annotations from itertools import permutations from math import sqrt def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise. >>> is_prime(67483) False >>> is_prime(563) True >>> is_prime(87) False """ if n % 2 == 0: return False for i in range(3, int(sqrt(n) + 1), 2): if n % i == 0: return False return True def solution(n: int = 7) -> int: """ Returns the maximum pandigital prime number of length n. If there are none, then it will return 0. >>> solution(2) 0 >>> solution(4) 4231 >>> solution(7) 7652413 """ pandigital_str = "".join(str(i) for i in range(1, n + 1)) perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)] pandigitals = [num for num in perm_list if is_prime(num)] return max(pandigitals) if pandigitals else 0 if __name__ == "__main__": print(f"{solution() = }")
""" Pandigital prime Problem 41: https://projecteuler.net/problem=41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3. So we will check only 7 digit pandigital numbers to obtain the largest possible pandigital prime. """ from __future__ import annotations import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(n: int = 7) -> int: """ Returns the maximum pandigital prime number of length n. If there are none, then it will return 0. >>> solution(2) 0 >>> solution(4) 4231 >>> solution(7) 7652413 """ pandigital_str = "".join(str(i) for i in range(1, n + 1)) perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)] pandigitals = [num for num in perm_list if is_prime(num)] return max(pandigitals) if pandigitals else 0 if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Problem 46: https://projecteuler.net/problem=46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2 × 12 15 = 7 + 2 × 22 21 = 3 + 2 × 32 25 = 7 + 2 × 32 27 = 19 + 2 × 22 33 = 31 + 2 × 12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ from __future__ import annotations seive = [True] * 100001 i = 2 while i * i <= 100000: if seive[i]: for j in range(i * i, 100001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise, for 2 <= n <= 100000 >>> is_prime(87) False >>> is_prime(23) True >>> is_prime(25363) False """ return seive[n] odd_composites = [num for num in range(3, len(seive), 2) if not is_prime(num)] def compute_nums(n: int) -> list[int]: """ Returns a list of first n odd composite numbers which do not follow the conjecture. >>> compute_nums(1) [5777] >>> compute_nums(2) [5777, 5993] >>> compute_nums(0) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> compute_nums("a") Traceback (most recent call last): ... ValueError: n must be an integer >>> compute_nums(1.1) Traceback (most recent call last): ... ValueError: n must be an integer """ if not isinstance(n, int): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") list_nums = [] for num in range(len(odd_composites)): i = 0 while 2 * i * i <= odd_composites[num]: rem = odd_composites[num] - 2 * i * i if is_prime(rem): break i += 1 else: list_nums.append(odd_composites[num]) if len(list_nums) == n: return list_nums return [] def solution() -> int: """Return the solution to the problem""" return compute_nums(1)[0] if __name__ == "__main__": print(f"{solution() = }")
""" Problem 46: https://projecteuler.net/problem=46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2 × 12 15 = 7 + 2 × 22 21 = 3 + 2 × 32 25 = 7 + 2 × 32 27 = 19 + 2 × 22 33 = 31 + 2 × 12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)] def compute_nums(n: int) -> list[int]: """ Returns a list of first n odd composite numbers which do not follow the conjecture. >>> compute_nums(1) [5777] >>> compute_nums(2) [5777, 5993] >>> compute_nums(0) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> compute_nums("a") Traceback (most recent call last): ... ValueError: n must be an integer >>> compute_nums(1.1) Traceback (most recent call last): ... ValueError: n must be an integer """ if not isinstance(n, int): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") list_nums = [] for num in range(len(odd_composites)): i = 0 while 2 * i * i <= odd_composites[num]: rem = odd_composites[num] - 2 * i * i if is_prime(rem): break i += 1 else: list_nums.append(odd_composites[num]) if len(list_nums) == n: return list_nums return [] def solution() -> int: """Return the solution to the problem""" return compute_nums(1)[0] if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" 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. """ import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 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
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ from math import isqrt def is_prime(number: int) -> int: """ Returns whether the given number is prime or not >>> is_prime(1) 0 >>> is_prime(17) 1 >>> is_prime(10000) 0 """ if number == 1: return 0 if number % 2 == 0 and number > 2: return 0 for i in range(3, isqrt(number) + 1, 2): if number % i == 0: return 0 return 1 def solution(ratio: float = 0.1) -> int: """ Returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(ratio: float = 0.1) -> int: """ Returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
if __name__ == "__main__": import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) print(f"{data = }") if not data: break out_file.write(data) # Write data to a file print("Successfully got the file") sock.close() print("Connection closed")
if __name__ == "__main__": import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) print(f"{data = }") if not data: break out_file.write(data) # Write data to a file print("Successfully got the file") sock.close() print("Connection closed")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 65: https://projecteuler.net/problem=65 The square root of 2 can be written as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))) The infinite continued fraction can be written, sqrt(2) = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for sqrt(2). 1 + 1 / 2 = 3/2 1 + 1 / (2 + 1 / 2) = 7/5 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17/12 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/29 Hence the sequence of the first ten convergents for sqrt(2) are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10th convergent is 1 + 4 + 5 + 7 = 17. Find the sum of the digits in the numerator of the 100th convergent of the continued fraction for e. ----- The solution mostly comes down to finding an equation that will generate the numerator of the continued fraction. For the i-th numerator, the pattern is: n_i = m_i * n_(i-1) + n_(i-2) for m_i = the i-th index of the continued fraction representation of e, n_0 = 1, and n_1 = 2 as the first 2 numbers of the representation. For example: n_9 = 6 * 193 + 106 = 1264 1 + 2 + 6 + 4 = 13 n_10 = 1 * 193 + 1264 = 1457 1 + 4 + 5 + 7 = 17 """ def sum_digits(num: int) -> int: """ Returns the sum of every digit in num. >>> sum_digits(1) 1 >>> sum_digits(12345) 15 >>> sum_digits(999001) 28 """ digit_sum = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def solution(max: int = 100) -> int: """ Returns the sum of the digits in the numerator of the max-th convergent of the continued fraction for e. >>> solution(9) 13 >>> solution(10) 17 >>> solution(50) 91 """ pre_numerator = 1 cur_numerator = 2 for i in range(2, max + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator cur_numerator = e_cont * pre_numerator + temp return sum_digits(cur_numerator) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 65: https://projecteuler.net/problem=65 The square root of 2 can be written as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))) The infinite continued fraction can be written, sqrt(2) = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for sqrt(2). 1 + 1 / 2 = 3/2 1 + 1 / (2 + 1 / 2) = 7/5 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17/12 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/29 Hence the sequence of the first ten convergents for sqrt(2) are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10th convergent is 1 + 4 + 5 + 7 = 17. Find the sum of the digits in the numerator of the 100th convergent of the continued fraction for e. ----- The solution mostly comes down to finding an equation that will generate the numerator of the continued fraction. For the i-th numerator, the pattern is: n_i = m_i * n_(i-1) + n_(i-2) for m_i = the i-th index of the continued fraction representation of e, n_0 = 1, and n_1 = 2 as the first 2 numbers of the representation. For example: n_9 = 6 * 193 + 106 = 1264 1 + 2 + 6 + 4 = 13 n_10 = 1 * 193 + 1264 = 1457 1 + 4 + 5 + 7 = 17 """ def sum_digits(num: int) -> int: """ Returns the sum of every digit in num. >>> sum_digits(1) 1 >>> sum_digits(12345) 15 >>> sum_digits(999001) 28 """ digit_sum = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def solution(max: int = 100) -> int: """ Returns the sum of the digits in the numerator of the max-th convergent of the continued fraction for e. >>> solution(9) 13 >>> solution(10) 17 >>> solution(50) 91 """ pre_numerator = 1 cur_numerator = 2 for i in range(2, max + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator cur_numerator = e_cont * pre_numerator + temp return sum_digits(cur_numerator) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 135: https://projecteuler.net/problem=135 Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 − y2 − z2 = n, has exactly two solutions is n = 27: 342 − 272 − 202 = 122 − 92 − 62 = 27 It turns out that n = 1155 is the least value which has exactly ten solutions. How many values of n less than one million have exactly ten distinct solutions? Taking x,y,z of the form a+d,a,a-d respectively, the given equation reduces to a*(4d-a)=n. Calculating no of solutions for every n till 1 million by fixing a ,and n must be multiple of a. Total no of steps=n*(1/1+1/2+1/3+1/4..+1/n) ,so roughly O(nlogn) time complexity. """ def solution(limit: int = 1000000) -> int: """ returns the values of n less than or equal to the limit have exactly ten distinct solutions. >>> solution(100) 0 >>> solution(10000) 45 >>> solution(50050) 292 """ limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): for n in range(first_term, limit, first_term): common_difference = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a count = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 135: https://projecteuler.net/problem=135 Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 − y2 − z2 = n, has exactly two solutions is n = 27: 342 − 272 − 202 = 122 − 92 − 62 = 27 It turns out that n = 1155 is the least value which has exactly ten solutions. How many values of n less than one million have exactly ten distinct solutions? Taking x,y,z of the form a+d,a,a-d respectively, the given equation reduces to a*(4d-a)=n. Calculating no of solutions for every n till 1 million by fixing a ,and n must be multiple of a. Total no of steps=n*(1/1+1/2+1/3+1/4..+1/n) ,so roughly O(nlogn) time complexity. """ def solution(limit: int = 1000000) -> int: """ returns the values of n less than or equal to the limit have exactly ten distinct solutions. >>> solution(100) 0 >>> solution(10000) 45 >>> solution(50050) 292 """ limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): for n in range(first_term, limit, first_term): common_difference = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a count = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
from math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trailing_zeros(16) 4 >>> binary_count_trailing_zeros(58) 1 >>> binary_count_trailing_zeros(4294967296) 32 >>> binary_count_trailing_zeros(0) 0 >>> binary_count_trailing_zeros(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_trailing_zeros(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_trailing_zeros("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if (a == 0) else int(log2(a & -a)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" python/black : true flake8 : passed """ from __future__ import annotations from collections.abc import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: """Test if two trees are equal.""" if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
""" python/black : true flake8 : passed """ from __future__ import annotations from collections.abc import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: """Test if two trees are equal.""" if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, polyA=None, polyB=None): # Input as list self.polyA = list(polyA or [0])[:] self.polyB = list(polyB or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.C_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.C_max_length: self.polyA.append(0) while len(self.polyB) < self.C_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.C_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __DFT(self, which): if which == "A": dft = [[x] for x in self.polyA] else: dft = [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.C_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.C_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.C_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dftA = self.__DFT("A") dftB = self.__DFT("B") inverseC = [[dftA[i] * dftB[i] for i in range(self.C_max_length)]] del dftA del dftB # Corner Case if len(inverseC[0]) <= 1: return inverseC[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.C_max_length: new_inverseC = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.C_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverseC[i].append( ( inverseC[i][j] + inverseC[i][j + self.C_max_length // next_ncol] ) / 2 ) # Odd positions new_inverseC[i + next_ncol // 2].append( ( inverseC[i][j] - inverseC[i][j + self.C_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverseC = new_inverseC next_ncol *= 2 # Unpack inverseC = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverseC] # Remove leading 0's while inverseC[-1] == 0: inverseC.pop() return inverseC # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): A = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) B = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) C = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return "\n".join((A, B, C)) # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, polyA=None, polyB=None): # Input as list self.polyA = list(polyA or [0])[:] self.polyB = list(polyB or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.C_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.C_max_length: self.polyA.append(0) while len(self.polyB) < self.C_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.C_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __DFT(self, which): if which == "A": dft = [[x] for x in self.polyA] else: dft = [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.C_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.C_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.C_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dftA = self.__DFT("A") dftB = self.__DFT("B") inverseC = [[dftA[i] * dftB[i] for i in range(self.C_max_length)]] del dftA del dftB # Corner Case if len(inverseC[0]) <= 1: return inverseC[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.C_max_length: new_inverseC = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.C_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverseC[i].append( ( inverseC[i][j] + inverseC[i][j + self.C_max_length // next_ncol] ) / 2 ) # Odd positions new_inverseC[i + next_ncol // 2].append( ( inverseC[i][j] - inverseC[i][j + self.C_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverseC = new_inverseC next_ncol *= 2 # Unpack inverseC = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverseC] # Remove leading 0's while inverseC[-1] == 0: inverseC.pop() return inverseC # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): A = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) B = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) C = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return "\n".join((A, B, C)) # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
# Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: """ Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 6 >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 7 """ # preprocessing the first row for i in range(1, len(matrix[0])): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(matrix)): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
# Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: """ Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 6 >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 7 """ # preprocessing the first row for i in range(1, len(matrix[0])): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(matrix)): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for i in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for i in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
# flake8: noqa """ This is pure Python implementation of tree traversal algorithms """ from __future__ import annotations import queue class TreeNode: def __init__(self, data): self.data = data self.right = None self.left = None def build_tree(): print("\n********Press N to stop entering at any point of time********\n") check = input("Enter the value of the root node: ").strip().lower() or "n" if check == "n": return None q: queue.Queue = queue.Queue() tree_node = TreeNode(int(check)) q.put(tree_node) while not q.empty(): node_found = q.get() msg = f"Enter the left node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node left_node = TreeNode(int(check)) node_found.left = left_node q.put(left_node) msg = f"Enter the right node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node right_node = TreeNode(int(check)) node_found.right = right_node q.put(right_node) def pre_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return print(node.data, end=",") pre_order(node.left) pre_order(node.right) def in_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return in_order(node.left) print(node.data, end=",") in_order(node.right) def post_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return post_order(node.left) post_order(node.right) print(node.data, end=",") def level_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order(root) 1,2,3,4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: q.put(node_dequeued.left) if node_dequeued.right: q.put(node_dequeued.right) def level_order_actual(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order_actual(root) 1, 2,3, 4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): list = [] while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: list.append(node_dequeued.left) if node_dequeued.right: list.append(node_dequeued.right) print() for node in list: q.put(node) # iteration version def pre_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order_iter(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: # start from root node, find its left child print(n.data, end=",") stack.append(n) n = n.left # end of while means current node doesn't have left child n = stack.pop() # start to traverse its right child n = n.right def in_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order_iter(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: stack.append(n) n = n.left n = stack.pop() print(n.data, end=",") n = n.right def post_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order_iter(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return stack1, stack2 = [], [] n = node stack1.append(n) while stack1: # to find the reversed order of post order, store it in stack2 n = stack1.pop() if n.left: stack1.append(n.left) if n.right: stack1.append(n.right) stack2.append(n) while stack2: # pop up from stack2 will be the post order print(stack2.pop().data, end=",") def prompt(s: str = "", width=50, char="*") -> str: if not s: return "\n" + width * char left, extra = divmod(width - len(s) - 2, 2) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt("Binary Tree Traversals")) node = build_tree() print(prompt("Pre Order Traversal")) pre_order(node) print(prompt() + "\n") print(prompt("In Order Traversal")) in_order(node) print(prompt() + "\n") print(prompt("Post Order Traversal")) post_order(node) print(prompt() + "\n") print(prompt("Level Order Traversal")) level_order(node) print(prompt() + "\n") print(prompt("Actual Level Order Traversal")) level_order_actual(node) print("*" * 50 + "\n") print(prompt("Pre Order Traversal - Iteration Version")) pre_order_iter(node) print(prompt() + "\n") print(prompt("In Order Traversal - Iteration Version")) in_order_iter(node) print(prompt() + "\n") print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) print(prompt())
# flake8: noqa """ This is pure Python implementation of tree traversal algorithms """ from __future__ import annotations import queue class TreeNode: def __init__(self, data): self.data = data self.right = None self.left = None def build_tree(): print("\n********Press N to stop entering at any point of time********\n") check = input("Enter the value of the root node: ").strip().lower() or "n" if check == "n": return None q: queue.Queue = queue.Queue() tree_node = TreeNode(int(check)) q.put(tree_node) while not q.empty(): node_found = q.get() msg = f"Enter the left node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node left_node = TreeNode(int(check)) node_found.left = left_node q.put(left_node) msg = f"Enter the right node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node right_node = TreeNode(int(check)) node_found.right = right_node q.put(right_node) def pre_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return print(node.data, end=",") pre_order(node.left) pre_order(node.right) def in_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return in_order(node.left) print(node.data, end=",") in_order(node.right) def post_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return post_order(node.left) post_order(node.right) print(node.data, end=",") def level_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order(root) 1,2,3,4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: q.put(node_dequeued.left) if node_dequeued.right: q.put(node_dequeued.right) def level_order_actual(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order_actual(root) 1, 2,3, 4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): list = [] while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: list.append(node_dequeued.left) if node_dequeued.right: list.append(node_dequeued.right) print() for node in list: q.put(node) # iteration version def pre_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order_iter(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: # start from root node, find its left child print(n.data, end=",") stack.append(n) n = n.left # end of while means current node doesn't have left child n = stack.pop() # start to traverse its right child n = n.right def in_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order_iter(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: stack.append(n) n = n.left n = stack.pop() print(n.data, end=",") n = n.right def post_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order_iter(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return stack1, stack2 = [], [] n = node stack1.append(n) while stack1: # to find the reversed order of post order, store it in stack2 n = stack1.pop() if n.left: stack1.append(n.left) if n.right: stack1.append(n.right) stack2.append(n) while stack2: # pop up from stack2 will be the post order print(stack2.pop().data, end=",") def prompt(s: str = "", width=50, char="*") -> str: if not s: return "\n" + width * char left, extra = divmod(width - len(s) - 2, 2) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt("Binary Tree Traversals")) node = build_tree() print(prompt("Pre Order Traversal")) pre_order(node) print(prompt() + "\n") print(prompt("In Order Traversal")) in_order(node) print(prompt() + "\n") print(prompt("Post Order Traversal")) post_order(node) print(prompt() + "\n") print(prompt("Level Order Traversal")) level_order(node) print(prompt() + "\n") print(prompt("Actual Level Order Traversal")) level_order_actual(node) print("*" * 50 + "\n") print(prompt("Pre Order Traversal - Iteration Version")) pre_order_iter(node) print(prompt() + "\n") print(prompt("In Order Traversal - Iteration Version")) in_order_iter(node) print(prompt() + "\n") print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) print(prompt())
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" References: wikipedia:square free number python/black : True flake8 : True """ from __future__ import annotations def is_square_free(factors: list[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should return some value it simply checks for repition in the numbers. >>> is_square_free([1, 3, 4, 'sd', 0.0]) True >>> is_square_free([1, 0.5, 2, 0.0]) True >>> is_square_free([1, 2, 2, 5]) False >>> is_square_free('asd') True >>> is_square_free(24) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
""" References: wikipedia:square free number python/black : True flake8 : True """ from __future__ import annotations def is_square_free(factors: list[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should return some value it simply checks for repition in the numbers. >>> is_square_free([1, 3, 4, 'sd', 0.0]) True >>> is_square_free([1, 0.5, 2, 0.0]) True >>> is_square_free([1, 2, 2, 5]) False >>> is_square_free('asd') True >>> is_square_free(24) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
import math from collections.abc import Generator def slow_primes(max: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(slow_primes(0)) [] >>> list(slow_primes(-1)) [] >>> list(slow_primes(-10)) [] >>> list(slow_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(slow_primes(11)) [2, 3, 5, 7, 11] >>> list(slow_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(slow_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: break else: yield i def primes(max: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(primes(0)) [] >>> list(primes(-1)) [] >>> list(primes(-10)) [] >>> list(primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(primes(11)) [2, 3, 5, 7, 11] >>> list(primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 for j in range(2, bound): if (i % j) == 0: break else: yield i def fast_primes(max: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(fast_primes(0)) [] >>> list(fast_primes(-1)) [] >>> list(fast_primes(-10)) [] >>> list(fast_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(fast_primes(11)) [2, 3, 5, 7, 11] >>> list(fast_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(fast_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max + 1), 2)) # It's useless to test even numbers as they will not be prime if max > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): # As we removed the even numbers, we don't need them now if (i % j) == 0: break else: yield i if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) # Let's benchmark them side-by-side... from timeit import timeit print( timeit( "slow_primes(1_000_000_000_000)", setup="from __main__ import slow_primes", number=1_000_000, ) ) print( timeit( "primes(1_000_000_000_000)", setup="from __main__ import primes", number=1_000_000, ) ) print( timeit( "fast_primes(1_000_000_000_000)", setup="from __main__ import fast_primes", number=1_000_000, ) )
import math from collections.abc import Generator def slow_primes(max: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(slow_primes(0)) [] >>> list(slow_primes(-1)) [] >>> list(slow_primes(-10)) [] >>> list(slow_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(slow_primes(11)) [2, 3, 5, 7, 11] >>> list(slow_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(slow_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: break else: yield i def primes(max: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(primes(0)) [] >>> list(primes(-1)) [] >>> list(primes(-10)) [] >>> list(primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(primes(11)) [2, 3, 5, 7, 11] >>> list(primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 for j in range(2, bound): if (i % j) == 0: break else: yield i def fast_primes(max: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(fast_primes(0)) [] >>> list(fast_primes(-1)) [] >>> list(fast_primes(-10)) [] >>> list(fast_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(fast_primes(11)) [2, 3, 5, 7, 11] >>> list(fast_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(fast_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max + 1), 2)) # It's useless to test even numbers as they will not be prime if max > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): # As we removed the even numbers, we don't need them now if (i % j) == 0: break else: yield i if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) # Let's benchmark them side-by-side... from timeit import timeit print( timeit( "slow_primes(1_000_000_000_000)", setup="from __main__ import slow_primes", number=1_000_000, ) ) print( timeit( "primes(1_000_000_000_000)", setup="from __main__ import primes", number=1_000_000, ) ) print( timeit( "fast_primes(1_000_000_000_000)", setup="from __main__ import fast_primes", number=1_000_000, ) )
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there'] >>> split("11/22/63",separator = '/') ['11', '22', '63'] >>> split("12:43:39",separator = ":") ['12', '43', '39'] """ split_words = [] last_index = 0 for index, char in enumerate(string): if char == separator: split_words.append(string[last_index:index]) last_index = index + 1 elif index + 1 == len(string): split_words.append(string[last_index : index + 1]) return split_words if __name__ == "__main__": from doctest import testmod testmod()
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there'] >>> split("11/22/63",separator = '/') ['11', '22', '63'] >>> split("12:43:39",separator = ":") ['12', '43', '39'] """ split_words = [] last_index = 0 for index, char in enumerate(string): if char == separator: split_words.append(string[last_index:index]) last_index = index + 1 elif index + 1 == len(string): split_words.append(string[last_index : index + 1]) return split_words if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
#!/usr/bin/env python3 """ Build a half-adder quantum circuit that takes two bits as input, encodes them into qubits, then runs the half-adder circuit calculating the sum and carry qubits, observed over 1000 runs of the experiment . References: https://en.wikipedia.org/wiki/Adder_(electronics) https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add- """ import qiskit as q def half_adder(bit0: int, bit1: int) -> q.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") qc_ha = q.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = q.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(qc_ha) if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}")
#!/usr/bin/env python3 """ Build a half-adder quantum circuit that takes two bits as input, encodes them into qubits, then runs the half-adder circuit calculating the sum and carry qubits, observed over 1000 runs of the experiment . References: https://en.wikipedia.org/wiki/Adder_(electronics) https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add- """ import qiskit as q def half_adder(bit0: int, bit1: int) -> q.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") qc_ha = q.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = q.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(qc_ha) if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = map(lambda x: x.rstrip("\r\n").split(" "), triangle) a = list(map(lambda x: list(map(int, x)), a)) for i in range(1, len(a)): for j in range(len(a[i])): if j != len(a[i - 1]): number1 = a[i - 1][j] else: number1 = 0 if j > 0: number2 = a[i - 1][j - 1] else: number2 = 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = map(lambda x: x.rstrip("\r\n").split(" "), triangle) a = list(map(lambda x: list(map(int, x)), a)) for i in range(1, len(a)): for j in range(len(a[i])): if j != len(a[i - 1]): number1 = a[i - 1][j] else: number1 = 0 if j > 0: number2 = a[i - 1][j - 1] else: number2 = 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" 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
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ from __future__ import annotations def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]: """ Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) ['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) ['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04'] >>> p_series("", 1000) [''] >>> p_series(0, 0) [] >>> p_series(1, 1) ['1'] """ if nth_term == "": return [""] nth_term = int(nth_term) power = int(power) series: list[str] = [] for temp in range(int(nth_term)): series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1") return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ from __future__ import annotations def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]: """ Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) ['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) ['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04'] >>> p_series("", 1000) [''] >>> p_series(0, 0) [] >>> p_series(1, 1) ['1'] """ if nth_term == "": return [""] nth_term = int(nth_term) power = int(power) series: list[str] = [] for temp in range(int(nth_term)): series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1") return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
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
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
# https://en.wikipedia.org/wiki/Tree_traversal from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class Node: data: int left: Node | None = None right: Node | None = None def make_tree() -> Node | None: return Node(1, Node(2, Node(4), Node(5)), Node(3)) def preorder(root: Node | None) -> list[int]: """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node | None) -> list[int]: """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node | None) -> list[int]: """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node | None) -> int: """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order(root: Node | None) -> Sequence[Node | None]: """ Returns a list of nodes value from a whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ output: list[Any] = [] if root is None: return output process_queue = deque([root]) while process_queue: node = process_queue.popleft() output.append(node.data) if node.left: process_queue.append(node.left) if node.right: process_queue.append(node.right) return output def get_nodes_from_left_to_right( root: Node | None, level: int ) -> Sequence[Node | None]: """ Returns a list of nodes value from a particular level: Left to right direction of the binary tree. """ output: list[Any] = [] def populate_output(root: Node | None, level: int) -> None: if not root: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.left, level - 1) populate_output(root.right, level - 1) populate_output(root, level) return output def get_nodes_from_right_to_left( root: Node | None, level: int ) -> Sequence[Node | None]: """ Returns a list of nodes value from a particular level: Right to left direction of the binary tree. """ output: list[Any] = [] def populate_output(root: Node | None, level: int) -> None: if root is None: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.right, level - 1) populate_output(root.left, level - 1) populate_output(root, level) return output def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]: """ ZigZag traverse: Returns a list of nodes value from left to right and right to left, alternatively. """ if root is None: return [] output: list[Sequence[Node | None]] = [] flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if not flag: output.append(get_nodes_from_left_to_right(root, h)) flag = 1 else: output.append(get_nodes_from_right_to_left(root, h)) flag = 0 return output def main() -> None: # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f"In-order Traversal: {inorder(root)}") print(f"Pre-order Traversal: {preorder(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n") print(f"Height of Tree: {height(root)}", "\n") print("Complete Level Order Traversal: ") print(level_order(root), "\n") print("Level-wise order Traversal: ") for level in range(1, height(root) + 1): print(f"Level {level}:", get_nodes_from_left_to_right(root, level=level)) print("\nZigZag order Traversal: ") print(zigzag(root)) if __name__ == "__main__": import doctest doctest.testmod() main()
# https://en.wikipedia.org/wiki/Tree_traversal from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class Node: data: int left: Node | None = None right: Node | None = None def make_tree() -> Node | None: return Node(1, Node(2, Node(4), Node(5)), Node(3)) def preorder(root: Node | None) -> list[int]: """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node | None) -> list[int]: """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node | None) -> list[int]: """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node | None) -> int: """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order(root: Node | None) -> Sequence[Node | None]: """ Returns a list of nodes value from a whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ output: list[Any] = [] if root is None: return output process_queue = deque([root]) while process_queue: node = process_queue.popleft() output.append(node.data) if node.left: process_queue.append(node.left) if node.right: process_queue.append(node.right) return output def get_nodes_from_left_to_right( root: Node | None, level: int ) -> Sequence[Node | None]: """ Returns a list of nodes value from a particular level: Left to right direction of the binary tree. """ output: list[Any] = [] def populate_output(root: Node | None, level: int) -> None: if not root: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.left, level - 1) populate_output(root.right, level - 1) populate_output(root, level) return output def get_nodes_from_right_to_left( root: Node | None, level: int ) -> Sequence[Node | None]: """ Returns a list of nodes value from a particular level: Right to left direction of the binary tree. """ output: list[Any] = [] def populate_output(root: Node | None, level: int) -> None: if root is None: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.right, level - 1) populate_output(root.left, level - 1) populate_output(root, level) return output def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]: """ ZigZag traverse: Returns a list of nodes value from left to right and right to left, alternatively. """ if root is None: return [] output: list[Sequence[Node | None]] = [] flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if not flag: output.append(get_nodes_from_left_to_right(root, h)) flag = 1 else: output.append(get_nodes_from_right_to_left(root, h)) flag = 0 return output def main() -> None: # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f"In-order Traversal: {inorder(root)}") print(f"Pre-order Traversal: {preorder(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n") print(f"Height of Tree: {height(root)}", "\n") print("Complete Level Order Traversal: ") print(level_order(root), "\n") print("Level-wise order Traversal: ") for level in range(1, height(root) + 1): print(f"Level {level}:", get_nodes_from_left_to_right(root, level=level)) print("\nZigZag order Traversal: ") print(zigzag(root)) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 """ def solution(): """Returns >>> solution() 210 """ constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
""" Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 """ def solution(): """Returns >>> solution() 210 """ constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
def average_absolute_deviation(nums: list[int]) -> float: """ Return the average absolute deviation of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation >>> average_absolute_deviation([0]) 0.0 >>> average_absolute_deviation([4, 1, 3, 2]) 1.0 >>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0]) 20.0 >>> average_absolute_deviation([-20, 0, 30, 15]) 16.25 >>> average_absolute_deviation([]) Traceback (most recent call last): ... ValueError: List is empty """ if not nums: # Makes sure that the list is not empty raise ValueError("List is empty") average = sum(nums) / len(nums) # Calculate the average return sum(abs(x - average) for x in nums) / len(nums) if __name__ == "__main__": import doctest doctest.testmod()
def average_absolute_deviation(nums: list[int]) -> float: """ Return the average absolute deviation of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation >>> average_absolute_deviation([0]) 0.0 >>> average_absolute_deviation([4, 1, 3, 2]) 1.0 >>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0]) 20.0 >>> average_absolute_deviation([-20, 0, 30, 15]) 16.25 >>> average_absolute_deviation([]) Traceback (most recent call last): ... ValueError: List is empty """ if not nums: # Makes sure that the list is not empty raise ValueError("List is empty") average = sum(nums) / len(nums) # Calculate the average return sum(abs(x - average) for x in nums) / len(nums) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: """ >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) Traceback (most recent call last): ... ValueError: root 5 is not present in the binary_tree >>> binary_tree_mirror({}, 5) Traceback (most recent call last): ... ValueError: binary tree cannot be empty """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: raise ValueError(f"root {root} is not present in the binary_tree") binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: """ >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) Traceback (most recent call last): ... ValueError: root 5 is not present in the binary_tree >>> binary_tree_mirror({}, 5) Traceback (most recent call last): ... ValueError: binary tree cannot be empty """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: raise ValueError(f"root {root} is not present in the binary_tree") binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" https://en.wikipedia.org/wiki/Atbash """ import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: """ >>> atbash("ABCDEFG") 'ZYXWVUT' >>> atbash("aW;;123BX") 'zD;;123YC' """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: """Let's benchmark them side-by-side...""" from timeit import timeit print("Running performance benchmarks...") print( "> atbash_slow()", timeit( "atbash_slow(printable)", setup="from string import printable ; from __main__ import atbash_slow", ), "seconds", ) print( "> atbash()", timeit( "atbash(printable)", setup="from string import printable ; from __main__ import atbash", ), "seconds", ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
""" https://en.wikipedia.org/wiki/Atbash """ import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: """ >>> atbash("ABCDEFG") 'ZYXWVUT' >>> atbash("aW;;123BX") 'zD;;123YC' """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: """Let's benchmark them side-by-side...""" from timeit import timeit print("Running performance benchmarks...") print( "> atbash_slow()", timeit( "atbash_slow(printable)", setup="from string import printable ; from __main__ import atbash_slow", ), "seconds", ) print( "> atbash()", timeit( "atbash(printable)", setup="from string import printable ; from __main__ import atbash", ), "seconds", ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" == Raise base to the power of exponent using recursion == Input --> Enter the base: 3 Enter the exponent: 4 Output --> 3 to the power of 4 is 81 Input --> Enter the base: 2 Enter the exponent: 0 Output --> 2 to the power of 0 is 1 """ def power(base: int, exponent: int) -> float: """ power(3, 4) 81 >>> power(2, 0) 1 >>> all(power(base, exponent) == pow(base, exponent) ... for base in range(-10, 10) for exponent in range(10)) True """ return base * power(base, (exponent - 1)) if exponent else 1 if __name__ == "__main__": print("Raise base to the power of exponent using recursion...") base = int(input("Enter the base: ").strip()) exponent = int(input("Enter the exponent: ").strip()) result = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents result = 1 / result print(f"{base} to the power of {exponent} is {result}")
""" == Raise base to the power of exponent using recursion == Input --> Enter the base: 3 Enter the exponent: 4 Output --> 3 to the power of 4 is 81 Input --> Enter the base: 2 Enter the exponent: 0 Output --> 2 to the power of 0 is 1 """ def power(base: int, exponent: int) -> float: """ power(3, 4) 81 >>> power(2, 0) 1 >>> all(power(base, exponent) == pow(base, exponent) ... for base in range(-10, 10) for exponent in range(10)) True """ return base * power(base, (exponent - 1)) if exponent else 1 if __name__ == "__main__": print("Raise base to the power of exponent using recursion...") base = int(input("Enter the base: ").strip()) exponent = int(input("Enter the exponent: ").strip()) result = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents result = 1 / result print(f"{base} to the power of {exponent} is {result}")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Geometric Mean Reference : https://en.wikipedia.org/wiki/Geometric_mean Geometric series Reference: https://en.wikipedia.org/wiki/Geometric_series """ def is_geometric_series(series: list) -> bool: """ checking whether the input series is geometric series or not >>> is_geometric_series([2, 4, 8]) True >>> is_geometric_series([3, 6, 12, 24]) True >>> is_geometric_series([1, 2, 3]) False >>> is_geometric_series([0, 0, 3]) False >>> is_geometric_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list >>> is_geometric_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True try: common_ratio = series[1] / series[0] for index in range(len(series) - 1): if series[index + 1] / series[index] != common_ratio: return False except ZeroDivisionError: return False return True def geometric_mean(series: list) -> float: """ return the geometric mean of series >>> geometric_mean([2, 4, 8]) 3.9999999999999996 >>> geometric_mean([3, 6, 12, 24]) 8.48528137423857 >>> geometric_mean([4, 8, 16]) 7.999999999999999 >>> geometric_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] >>> geometric_mean([1, 2, 3]) 1.8171205928321397 >>> geometric_mean([0, 2, 3]) 0.0 >>> geometric_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 1 for value in series: answer *= value return pow(answer, 1 / len(series)) if __name__ == "__main__": import doctest doctest.testmod()
""" Geometric Mean Reference : https://en.wikipedia.org/wiki/Geometric_mean Geometric series Reference: https://en.wikipedia.org/wiki/Geometric_series """ def is_geometric_series(series: list) -> bool: """ checking whether the input series is geometric series or not >>> is_geometric_series([2, 4, 8]) True >>> is_geometric_series([3, 6, 12, 24]) True >>> is_geometric_series([1, 2, 3]) False >>> is_geometric_series([0, 0, 3]) False >>> is_geometric_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list >>> is_geometric_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True try: common_ratio = series[1] / series[0] for index in range(len(series) - 1): if series[index + 1] / series[index] != common_ratio: return False except ZeroDivisionError: return False return True def geometric_mean(series: list) -> float: """ return the geometric mean of series >>> geometric_mean([2, 4, 8]) 3.9999999999999996 >>> geometric_mean([3, 6, 12, 24]) 8.48528137423857 >>> geometric_mean([4, 8, 16]) 7.999999999999999 >>> geometric_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] >>> geometric_mean([1, 2, 3]) 1.8171205928321397 >>> geometric_mean([0, 2, 3]) 0.0 >>> geometric_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 1 for value in series: answer *= value return pow(answer, 1 / len(series)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Tree_sort algorithm. Build a BST and in order traverse. """ class node: # BST data structure def __init__(self, val): self.val = val self.left = None self.right = None def insert(self, val): if self.val: if val < self.val: if self.left is None: self.left = node(val) else: self.left.insert(val) elif val > self.val: if self.right is None: self.right = node(val) else: self.right.insert(val) else: self.val = val def inorder(root, res): # Recursive traversal if root: inorder(root.left, res) res.append(root.val) inorder(root.right, res) def tree_sort(arr): # Build BST if len(arr) == 0: return arr root = node(arr[0]) for i in range(1, len(arr)): root.insert(arr[i]) # Traverse BST in order. res = [] inorder(root, res) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
""" Tree_sort algorithm. Build a BST and in order traverse. """ class node: # BST data structure def __init__(self, val): self.val = val self.left = None self.right = None def insert(self, val): if self.val: if val < self.val: if self.left is None: self.left = node(val) else: self.left.insert(val) elif val > self.val: if self.right is None: self.right = node(val) else: self.right.insert(val) else: self.val = val def inorder(root, res): # Recursive traversal if root: inorder(root.left, res) res.append(root.val) inorder(root.right, res) def tree_sort(arr): # Build BST if len(arr) == 0: return arr root = node(arr[0]) for i in range(1, len(arr)): root.insert(arr[i]) # Traverse BST in order. res = [] inorder(root, res) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __str__(self): return f"val: {self.val}, start: {self.start}, end: {self.end}" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> for node in num_arr.traverse(): ... print(node) ... val: 15, start: 0, end: 4 val: 8, start: 0, end: 2 val: 7, start: 3, end: 4 val: 3, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> num_arr.update(1, 5) >>> for node in num_arr.traverse(): ... print(node) ... val: 19, start: 0, end: 4 val: 12, start: 0, end: 2 val: 7, start: 3, end: 4 val: 7, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 5, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... val: 1, start: 0, end: 4 val: 1, start: 0, end: 2 val: 3, start: 3, end: 4 val: 1, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... val: 2, start: 0, end: 4 val: 2, start: 0, end: 2 val: 3, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __str__(self): return f"val: {self.val}, start: {self.start}, end: {self.end}" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> for node in num_arr.traverse(): ... print(node) ... val: 15, start: 0, end: 4 val: 8, start: 0, end: 2 val: 7, start: 3, end: 4 val: 3, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> num_arr.update(1, 5) >>> for node in num_arr.traverse(): ... print(node) ... val: 19, start: 0, end: 4 val: 12, start: 0, end: 2 val: 7, start: 3, end: 4 val: 7, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 5, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... val: 1, start: 0, end: 4 val: 1, start: 0, end: 2 val: 3, start: 3, end: 4 val: 1, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... val: 2, start: 0, end: 4 val: 2, start: 0, end: 2 val: 3, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Greedy Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://cs.stackexchange.com/questions/129017/greedy-algorithm-for-vertex-cover """ import heapq def greedy_min_vertex_cover(graph: dict) -> set[int]: """ Greedy APX Algorithm for min Vertex Cover @input: graph (graph stored in an adjacency list where each vertex is represented with an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> greedy_min_vertex_cover(graph) {0, 1, 2, 4} """ # queue used to store nodes and their rank queue: list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(queue, [-1 * len(value), (key, value)]) # chosen_vertices = set of chosen vertices chosen_vertices = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices argmax = heapq.heappop(queue)[1][0] chosen_vertices.add(argmax) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: index = elem[1][1].index(argmax) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(queue) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f"Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}")
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Greedy Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://cs.stackexchange.com/questions/129017/greedy-algorithm-for-vertex-cover """ import heapq def greedy_min_vertex_cover(graph: dict) -> set[int]: """ Greedy APX Algorithm for min Vertex Cover @input: graph (graph stored in an adjacency list where each vertex is represented with an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> greedy_min_vertex_cover(graph) {0, 1, 2, 4} """ # queue used to store nodes and their rank queue: list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(queue, [-1 * len(value), (key, value)]) # chosen_vertices = set of chosen vertices chosen_vertices = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices argmax = heapq.heappop(queue)[1][0] chosen_vertices.add(argmax) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: index = elem[1][1].index(argmax) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(queue) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f"Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
#!/usr/bin/env python3 """ A Polybius Square is a table that allows someone to translate letters into numbers. https://www.braingle.com/brainteasers/codes/polybius.php """ import numpy as np class PolybiusCipher: def __init__(self) -> None: SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(self.SQUARE == letter) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> PolybiusCipher().numbers_to_letter(4, 5) == "u" True >>> PolybiusCipher().numbers_to_letter(1, 1) == "a" True """ return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> PolybiusCipher().encode("test message") == "44154344 32154343112215" True >>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215" True """ message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> PolybiusCipher().decode("44154344 32154343112215") == "test message" True >>> PolybiusCipher().decode("4415434432154343112215") == "testmessage" True """ message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): if message[numbers_index * 2] != " ": index1 = message[numbers_index * 2] index2 = message[numbers_index * 2 + 1] letter = self.numbers_to_letter(int(index1), int(index2)) decoded_message = decoded_message + letter elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " return decoded_message
#!/usr/bin/env python3 """ A Polybius Square is a table that allows someone to translate letters into numbers. https://www.braingle.com/brainteasers/codes/polybius.php """ import numpy as np class PolybiusCipher: def __init__(self) -> None: SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(self.SQUARE == letter) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> PolybiusCipher().numbers_to_letter(4, 5) == "u" True >>> PolybiusCipher().numbers_to_letter(1, 1) == "a" True """ return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> PolybiusCipher().encode("test message") == "44154344 32154343112215" True >>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215" True """ message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> PolybiusCipher().decode("44154344 32154343112215") == "test message" True >>> PolybiusCipher().decode("4415434432154343112215") == "testmessage" True """ message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): if message[numbers_index * 2] != " ": index1 = message[numbers_index * 2] index2 = message[numbers_index * 2 + 1] letter = self.numbers_to_letter(int(index1), int(index2)) decoded_message = decoded_message + letter elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " return decoded_message
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" The Horn-Schunck method estimates the optical flow for every single pixel of a sequence of images. It works by assuming brightness constancy between two consecutive frames and smoothness in the optical flow. Useful resources: Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Schunck_method Paper: http://image.diku.dk/imagecanon/material/HornSchunckOptical_Flow.pdf """ from typing import SupportsIndex import numpy as np from scipy.ndimage.filters import convolve def warp( image: np.ndarray, horizontal_flow: np.ndarray, vertical_flow: np.ndarray ) -> np.ndarray: """ Warps the pixels of an image into a new image using the horizontal and vertical flows. Pixels that are warped from an invalid location are set to 0. Parameters: image: Grayscale image horizontal_flow: Horizontal flow vertical_flow: Vertical flow Returns: Warped image >>> warp(np.array([[0, 1, 2], [0, 3, 0], [2, 2, 2]]), \ np.array([[0, 1, -1], [-1, 0, 0], [1, 1, 1]]), \ np.array([[0, 0, 0], [0, 1, 0], [0, 0, 1]])) array([[0, 0, 0], [3, 1, 0], [0, 2, 3]]) """ flow = np.stack((horizontal_flow, vertical_flow), 2) # Create a grid of all pixel coordinates and subtract the flow to get the # target pixels coordinates grid = np.stack( np.meshgrid(np.arange(0, image.shape[1]), np.arange(0, image.shape[0])), 2 ) grid = np.round(grid - flow).astype(np.int32) # Find the locations outside of the original image invalid = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]])) grid[invalid] = 0 warped = image[grid[:, :, 1], grid[:, :, 0]] # Set pixels at invalid locations to 0 warped[invalid[:, :, 0] | invalid[:, :, 1]] = 0 return warped def horn_schunck( image0: np.ndarray, image1: np.ndarray, num_iter: SupportsIndex, alpha: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: """ This function performs the Horn-Schunck algorithm and returns the estimated optical flow. It is assumed that the input images are grayscale and normalized to be in [0, 1]. Parameters: image0: First image of the sequence image1: Second image of the sequence alpha: Regularization constant num_iter: Number of iterations performed Returns: estimated horizontal & vertical flow >>> np.round(horn_schunck(np.array([[0, 0, 2], [0, 0, 2]]), \ np.array([[0, 2, 0], [0, 2, 0]]), alpha=0.1, num_iter=110)).\ astype(np.int32) array([[[ 0, -1, -1], [ 0, -1, -1]], <BLANKLINE> [[ 0, 0, 0], [ 0, 0, 0]]], dtype=int32) """ if alpha is None: alpha = 0.1 # Initialize flow horizontal_flow = np.zeros_like(image0) vertical_flow = np.zeros_like(image0) # Prepare kernels for the calculation of the derivatives and the average velocity kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.25 kernel_y = np.array([[-1, -1], [1, 1]]) * 0.25 kernel_t = np.array([[1, 1], [1, 1]]) * 0.25 kernel_laplacian = np.array( [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]] ) # Iteratively refine the flow for _ in range(num_iter): warped_image = warp(image0, horizontal_flow, vertical_flow) derivative_x = convolve(warped_image, kernel_x) + convolve(image1, kernel_x) derivative_y = convolve(warped_image, kernel_y) + convolve(image1, kernel_y) derivative_t = convolve(warped_image, kernel_t) + convolve(image1, -kernel_t) avg_horizontal_velocity = convolve(horizontal_flow, kernel_laplacian) avg_vertical_velocity = convolve(vertical_flow, kernel_laplacian) # This updates the flow as proposed in the paper (Step 12) update = ( derivative_x * avg_horizontal_velocity + derivative_y * avg_vertical_velocity + derivative_t ) update = update / (alpha**2 + derivative_x**2 + derivative_y**2) horizontal_flow = avg_horizontal_velocity - derivative_x * update vertical_flow = avg_vertical_velocity - derivative_y * update return horizontal_flow, vertical_flow if __name__ == "__main__": import doctest doctest.testmod()
""" The Horn-Schunck method estimates the optical flow for every single pixel of a sequence of images. It works by assuming brightness constancy between two consecutive frames and smoothness in the optical flow. Useful resources: Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Schunck_method Paper: http://image.diku.dk/imagecanon/material/HornSchunckOptical_Flow.pdf """ from typing import SupportsIndex import numpy as np from scipy.ndimage.filters import convolve def warp( image: np.ndarray, horizontal_flow: np.ndarray, vertical_flow: np.ndarray ) -> np.ndarray: """ Warps the pixels of an image into a new image using the horizontal and vertical flows. Pixels that are warped from an invalid location are set to 0. Parameters: image: Grayscale image horizontal_flow: Horizontal flow vertical_flow: Vertical flow Returns: Warped image >>> warp(np.array([[0, 1, 2], [0, 3, 0], [2, 2, 2]]), \ np.array([[0, 1, -1], [-1, 0, 0], [1, 1, 1]]), \ np.array([[0, 0, 0], [0, 1, 0], [0, 0, 1]])) array([[0, 0, 0], [3, 1, 0], [0, 2, 3]]) """ flow = np.stack((horizontal_flow, vertical_flow), 2) # Create a grid of all pixel coordinates and subtract the flow to get the # target pixels coordinates grid = np.stack( np.meshgrid(np.arange(0, image.shape[1]), np.arange(0, image.shape[0])), 2 ) grid = np.round(grid - flow).astype(np.int32) # Find the locations outside of the original image invalid = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]])) grid[invalid] = 0 warped = image[grid[:, :, 1], grid[:, :, 0]] # Set pixels at invalid locations to 0 warped[invalid[:, :, 0] | invalid[:, :, 1]] = 0 return warped def horn_schunck( image0: np.ndarray, image1: np.ndarray, num_iter: SupportsIndex, alpha: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: """ This function performs the Horn-Schunck algorithm and returns the estimated optical flow. It is assumed that the input images are grayscale and normalized to be in [0, 1]. Parameters: image0: First image of the sequence image1: Second image of the sequence alpha: Regularization constant num_iter: Number of iterations performed Returns: estimated horizontal & vertical flow >>> np.round(horn_schunck(np.array([[0, 0, 2], [0, 0, 2]]), \ np.array([[0, 2, 0], [0, 2, 0]]), alpha=0.1, num_iter=110)).\ astype(np.int32) array([[[ 0, -1, -1], [ 0, -1, -1]], <BLANKLINE> [[ 0, 0, 0], [ 0, 0, 0]]], dtype=int32) """ if alpha is None: alpha = 0.1 # Initialize flow horizontal_flow = np.zeros_like(image0) vertical_flow = np.zeros_like(image0) # Prepare kernels for the calculation of the derivatives and the average velocity kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.25 kernel_y = np.array([[-1, -1], [1, 1]]) * 0.25 kernel_t = np.array([[1, 1], [1, 1]]) * 0.25 kernel_laplacian = np.array( [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]] ) # Iteratively refine the flow for _ in range(num_iter): warped_image = warp(image0, horizontal_flow, vertical_flow) derivative_x = convolve(warped_image, kernel_x) + convolve(image1, kernel_x) derivative_y = convolve(warped_image, kernel_y) + convolve(image1, kernel_y) derivative_t = convolve(warped_image, kernel_t) + convolve(image1, -kernel_t) avg_horizontal_velocity = convolve(horizontal_flow, kernel_laplacian) avg_vertical_velocity = convolve(vertical_flow, kernel_laplacian) # This updates the flow as proposed in the paper (Step 12) update = ( derivative_x * avg_horizontal_velocity + derivative_y * avg_vertical_velocity + derivative_t ) update = update / (alpha**2 + derivative_x**2 + derivative_y**2) horizontal_flow = avg_horizontal_velocity - derivative_x * update vertical_flow = avg_vertical_velocity - derivative_y * update return horizontal_flow, vertical_flow if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Just to check """ def add(a, b): """ >>> add(2, 2) 4 >>> add(2, -2) 0 """ return a + b if __name__ == "__main__": a = 5 b = 6 print(f"The sum of {a} + {b} is {add(a, b)}")
""" Just to check """ def add(a, b): """ >>> add(2, 2) 4 >>> add(2, -2) 0 """ return a + b if __name__ == "__main__": a = 5 b = 6 print(f"The sum of {a} + {b} is {add(a, b)}")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generateLargePrime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, keySize: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generate_key(keySize) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write( "%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3]) ) print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write("%d,%d" % (privateKey[0], privateKey[1])) def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generateLargePrime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, keySize: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generate_key(keySize) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write( "%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3]) ) print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write("%d,%d" % (privateKey[0], privateKey[1])) def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Output: Enter an Infix Equation = a + b ^c Symbol | Stack | Postfix ---------------------------- c | | c ^ | ^ | c b | ^ | cb + | + | cb^ a | + | cb^a | | cb^a+ a+b^c (Infix) -> +a^bc (Prefix) """ def infix_2_postfix(Infix): Stack = [] Postfix = [] priority = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator print_width = len(Infix) if (len(Infix) > 7) else 7 # Print table header for output print( "Symbol".center(8), "Stack".center(print_width), "Postfix".center(print_width), sep=" | ", ) print("-" * (print_width * 3 + 7)) for x in Infix: if x.isalpha() or x.isdigit(): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix elif x == "(": Stack.append(x) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while Stack[-1] != "(": Postfix.append(Stack.pop()) # Pop stack & add the content to Postfix Stack.pop() else: if len(Stack) == 0: Stack.append(x) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(Stack) > 0 and priority[x] <= priority[Stack[-1]]: Postfix.append(Stack.pop()) # pop stack & add to Postfix Stack.append(x) # push x to stack print( x.center(8), ("".join(Stack)).ljust(print_width), ("".join(Postfix)).ljust(print_width), sep=" | ", ) # Output in tabular format while len(Stack) > 0: # while stack is not empty Postfix.append(Stack.pop()) # pop stack & add to Postfix print( " ".center(8), ("".join(Stack)).ljust(print_width), ("".join(Postfix)).ljust(print_width), sep=" | ", ) # Output in tabular format return "".join(Postfix) # return Postfix as str def infix_2_prefix(Infix): Infix = list(Infix[::-1]) # reverse the infix equation for i in range(len(Infix)): if Infix[i] == "(": Infix[i] = ")" # change "(" to ")" elif Infix[i] == ")": Infix[i] = "(" # change ")" to "(" return (infix_2_postfix("".join(Infix)))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation Infix = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
""" Output: Enter an Infix Equation = a + b ^c Symbol | Stack | Postfix ---------------------------- c | | c ^ | ^ | c b | ^ | cb + | + | cb^ a | + | cb^a | | cb^a+ a+b^c (Infix) -> +a^bc (Prefix) """ def infix_2_postfix(Infix): Stack = [] Postfix = [] priority = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator print_width = len(Infix) if (len(Infix) > 7) else 7 # Print table header for output print( "Symbol".center(8), "Stack".center(print_width), "Postfix".center(print_width), sep=" | ", ) print("-" * (print_width * 3 + 7)) for x in Infix: if x.isalpha() or x.isdigit(): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix elif x == "(": Stack.append(x) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while Stack[-1] != "(": Postfix.append(Stack.pop()) # Pop stack & add the content to Postfix Stack.pop() else: if len(Stack) == 0: Stack.append(x) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(Stack) > 0 and priority[x] <= priority[Stack[-1]]: Postfix.append(Stack.pop()) # pop stack & add to Postfix Stack.append(x) # push x to stack print( x.center(8), ("".join(Stack)).ljust(print_width), ("".join(Postfix)).ljust(print_width), sep=" | ", ) # Output in tabular format while len(Stack) > 0: # while stack is not empty Postfix.append(Stack.pop()) # pop stack & add to Postfix print( " ".center(8), ("".join(Stack)).ljust(print_width), ("".join(Postfix)).ljust(print_width), sep=" | ", ) # Output in tabular format return "".join(Postfix) # return Postfix as str def infix_2_prefix(Infix): Infix = list(Infix[::-1]) # reverse the infix equation for i in range(len(Infix)): if Infix[i] == "(": Infix[i] = ")" # change "(" to ")" elif Infix[i] == ")": Infix[i] = "(" # change ")" to "(" return (infix_2_postfix("".join(Infix)))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation Infix = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for num_index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
""" The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for num_index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b return -1 if __name__ == "__main__": print(f"{solution() = }")
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b return -1 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket") @patch("builtins.open") def test_send_file_running_as_expected(file, sock): # ===== initialization ===== conn = Mock() sock.return_value.accept.return_value = conn, Mock() f = iter([1, None]) file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) # ===== invoke ===== send_file(filename="mytext.txt", testing=True) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket") @patch("builtins.open") def test_send_file_running_as_expected(file, sock): # ===== initialization ===== conn = Mock() sock.return_value.accept.return_value = conn, Mock() f = iter([1, None]) file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) # ===== invoke ===== send_file(filename="mytext.txt", testing=True) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from collections.abc import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
from collections.abc import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class Harris_Corner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered """ if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return f"Harris Corner detection with k : {self.k}" def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: """ Returns the image with corners identified img_path : path of the image output : list of the corner positions, image """ img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = Harris_Corner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class Harris_Corner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered """ if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return f"Harris Corner detection with k : {self.k}" def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: """ Returns the image with corners identified img_path : path of the image output : list of the corner positions, image """ img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = Harris_Corner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" The function below will convert any binary string to the octal equivalent. >>> bin_to_octal("1111") '17' >>> bin_to_octal("101010101010011") '52523' >>> bin_to_octal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_octal("a-1") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ def bin_to_octal(bin_string: str) -> str: if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") if not bin_string: raise ValueError("Empty string was passed to the function") oct_string = "" while len(bin_string) % 3 != 0: bin_string = "0" + bin_string bin_string_in_3_list = [ bin_string[index : index + 3] for index in range(len(bin_string)) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: oct_val = 0 for index, val in enumerate(bin_group): oct_val += int(2 ** (2 - index) * int(val)) oct_string += str(oct_val) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
""" The function below will convert any binary string to the octal equivalent. >>> bin_to_octal("1111") '17' >>> bin_to_octal("101010101010011") '52523' >>> bin_to_octal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_octal("a-1") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ def bin_to_octal(bin_string: str) -> str: if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") if not bin_string: raise ValueError("Empty string was passed to the function") oct_string = "" while len(bin_string) % 3 != 0: bin_string = "0" + bin_string bin_string_in_3_list = [ bin_string[index : index + 3] for index in range(len(bin_string)) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: oct_val = 0 for index, val in enumerate(bin_group): oct_val += int(2 ** (2 - index) * int(val)) oct_string += str(oct_val) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from __future__ import annotations def find_min(nums: list[int | float]) -> int | float: """ Find Minimum Number in a List :param nums: contains elements :return: min number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min(nums) == min(nums) True True True True >>> find_min([0, 1, 2, 3, 4, 5, -3, 24, -56]) -56 >>> find_min([]) Traceback (most recent call last): ... ValueError: find_min() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_min() arg is an empty sequence") min_num = nums[0] for num in nums: if min_num > num: min_num = num return min_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations def find_min(nums: list[int | float]) -> int | float: """ Find Minimum Number in a List :param nums: contains elements :return: min number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min(nums) == min(nums) True True True True >>> find_min([0, 1, 2, 3, 4, 5, -3, 24, -56]) -56 >>> find_min([]) Traceback (most recent call last): ... ValueError: find_min() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_min() arg is an empty sequence") min_num = nums[0] for num in nums: if min_num > num: min_num = num return min_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(S, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in S: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(S, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in S: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
def bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. :param list_data: mutable ordered sequence of elements :param length: length of list data :return: the same list in ascending order >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] >>> bubble_sort([], 0) [] >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": import doctest doctest.testmod()
def bubble_sort(list_data: list, length: int = 0) -> list: """ It is similar is bubble sort but recursive. :param list_data: mutable ordered sequence of elements :param length: length of list data :return: the same list in ascending order >>> bubble_sort([0, 5, 2, 3, 2], 5) [0, 2, 2, 3, 5] >>> bubble_sort([], 0) [] >>> bubble_sort([-2, -45, -5], 3) [-45, -5, -2] >>> bubble_sort([-23, 0, 6, -4, 34], 5) [-23, -4, 0, 6, 34] >>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['z','a','y','b','x','c'], 6) ['a', 'b', 'c', 'x', 'y', 'z'] >>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] """ length = length or len(list_data) swapped = False for i in range(length - 1): if list_data[i] > list_data[i + 1]: list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i] swapped = True return list_data if not swapped else bubble_sort(list_data, length - 1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from collections.abc import Callable import numpy as np def euler_modified( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.array: """ Calculate solution at each step to an ODE using Euler's Modified Method The Euler Method is straightforward to implement, but can't give accurate solutions. So, some changes were proposed to improve accuracy. https://en.wikipedia.org/wiki/Euler_method Arguments: ode_func -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x stepsize -- the increment value for x x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f1(x, y): ... return -2*x*(y**2) >>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0) >>> y[-1] 0.503338255442106 >>> import math >>> def f2(x, y): ... return -2*y + (x**3)*math.exp(-2*x) >>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3) >>> y[-1] 0.5525976431951775 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y_get = y[k] + step_size * ode_func(x, y[k]) y[k + 1] = y[k] + ( (step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get)) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
from collections.abc import Callable import numpy as np def euler_modified( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.array: """ Calculate solution at each step to an ODE using Euler's Modified Method The Euler Method is straightforward to implement, but can't give accurate solutions. So, some changes were proposed to improve accuracy. https://en.wikipedia.org/wiki/Euler_method Arguments: ode_func -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x stepsize -- the increment value for x x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f1(x, y): ... return -2*x*(y**2) >>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0) >>> y[-1] 0.503338255442106 >>> import math >>> def f2(x, y): ... return -2*y + (x**3)*math.exp(-2*x) >>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3) >>> y[-1] 0.5525976431951775 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y_get = y[k] + step_size * ode_func(x, y[k]) y[k + 1] = y[k] + ( (step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get)) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Problem 14: https://projecteuler.net/problem=14 Problem Statement: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def solution(n: int = 1000000) -> int: """Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) >>> solution(1000000) 837799 >>> solution(200) 171 >>> solution(5000) 3711 >>> solution(15000) 13255 """ largest_number = 1 pre_counter = 1 counters = {1: 1} for input1 in range(2, n): counter = 0 number = input1 while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if input1 not in counters: counters[input1] = counter if counter > pre_counter: largest_number = input1 pre_counter = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
""" Problem 14: https://projecteuler.net/problem=14 Problem Statement: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def solution(n: int = 1000000) -> int: """Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) >>> solution(1000000) 837799 >>> solution(200) 171 >>> solution(5000) 3711 >>> solution(15000) 13255 """ largest_number = 1 pre_counter = 1 counters = {1: 1} for input1 in range(2, n): counter = 0 number = input1 while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if input1 not in counters: counters[input1] = counter if counter > pre_counter: largest_number = input1 pre_counter = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x 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) ** extended_gcd function is used when d = gcd(a,b) is required in output """ 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) def extended_euclid(a: int, b: int) -> tuple[int, int]: """ Extended Euclid >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) 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 if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x 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) ** extended_gcd function is used when d = gcd(a,b) is required in output """ 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) def extended_euclid(a: int, b: int) -> tuple[int, int]: """ Extended Euclid >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) 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 if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
#
#
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.array :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.array """ matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": # read original image image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # get image shape img_rows, img_cols = gray_img.shape # set different points to rotate image pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) # add all rotated images in a list images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] # plot different image rotations fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.array :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.array """ matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": # read original image image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # get image shape img_rows, img_cols = gray_img.shape # set different points to rotate image pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) # add all rotated images in a list images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] # plot different image rotations fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" author : Mayank Kumar Jha (mk9440) """ from __future__ import annotations def find_max_sub_array(A, low, high): if low == high: return low, high, A[low] else: mid = (low + high) // 2 left_low, left_high, left_sum = find_max_sub_array(A, low, mid) right_low, right_high, right_sum = find_max_sub_array(A, mid + 1, high) cross_left, cross_right, cross_sum = find_max_cross_sum(A, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_left, cross_right, cross_sum def find_max_cross_sum(A, low, mid, high): left_sum, max_left = -999999999, -1 right_sum, max_right = -999999999, -1 summ = 0 for i in range(mid, low - 1, -1): summ += A[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += A[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def max_sub_array(nums: list[int]) -> int: """ Finds the contiguous subarray which has the largest sum and return its sum. >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 An empty (sub)array has sum 0. >>> max_sub_array([]) 0 If all elements are negative, the largest subarray would be the empty array, having the sum 0. >>> max_sub_array([-1, -2, -3]) 0 >>> max_sub_array([5, -2, -3]) 5 >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) 187 """ best = 0 current = 0 for i in nums: current += i if current < 0: current = 0 best = max(best, current) return best if __name__ == "__main__": """ A random simulation of this algorithm. """ import time from random import randint from matplotlib import pyplot as plt inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: li = [randint(1, i) for j in range(i)] strt = time.time() (find_max_sub_array(li, 0, len(li) - 1)) end = time.time() tim.append(end - strt) print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i], "\t\t", tim[i]) plt.plot(inputs, tim) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds ") plt.show()
""" author : Mayank Kumar Jha (mk9440) """ from __future__ import annotations def find_max_sub_array(A, low, high): if low == high: return low, high, A[low] else: mid = (low + high) // 2 left_low, left_high, left_sum = find_max_sub_array(A, low, mid) right_low, right_high, right_sum = find_max_sub_array(A, mid + 1, high) cross_left, cross_right, cross_sum = find_max_cross_sum(A, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_left, cross_right, cross_sum def find_max_cross_sum(A, low, mid, high): left_sum, max_left = -999999999, -1 right_sum, max_right = -999999999, -1 summ = 0 for i in range(mid, low - 1, -1): summ += A[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += A[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def max_sub_array(nums: list[int]) -> int: """ Finds the contiguous subarray which has the largest sum and return its sum. >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 An empty (sub)array has sum 0. >>> max_sub_array([]) 0 If all elements are negative, the largest subarray would be the empty array, having the sum 0. >>> max_sub_array([-1, -2, -3]) 0 >>> max_sub_array([5, -2, -3]) 5 >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) 187 """ best = 0 current = 0 for i in nums: current += i if current < 0: current = 0 best = max(best, current) return best if __name__ == "__main__": """ A random simulation of this algorithm. """ import time from random import randint from matplotlib import pyplot as plt inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: li = [randint(1, i) for j in range(i)] strt = time.time() (find_max_sub_array(li, 0, len(li) - 1)) end = time.time() tim.append(end - strt) print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i], "\t\t", tim[i]) plt.plot(inputs, tim) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds ") plt.show()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
#
#
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}" def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print(f"======= Iteration {i + 1} =======") for j, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( ranks[ib] / outbounds[ib] for ib in node.inbound ) print(ranks) def main(): names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == "__main__": main()
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}" def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print(f"======= Iteration {i + 1} =======") for j, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( ranks[ib] / outbounds[ib] for ib in node.inbound ) print(ranks) def main(): names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" References: https://en.wikipedia.org/wiki/M%C3%B6bius_function References: wikipedia:square free number python/black : True flake8 : True """ from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: """ Mobius function >>> mobius(24) 0 >>> mobius(-1) 1 >>> mobius('asd') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> mobius(10**400) 0 >>> mobius(10**-400) 1 >>> mobius(-1424) 1 >>> mobius([1, '2', 2.0]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
""" References: https://en.wikipedia.org/wiki/M%C3%B6bius_function References: wikipedia:square free number python/black : True flake8 : True """ from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: """ Mobius function >>> mobius(24) 0 >>> mobius(-1) 1 >>> mobius('asd') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> mobius(10**400) 0 >>> mobius(10**-400) 1 >>> mobius(-1424) 1 >>> mobius([1, '2', 2.0]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
def actual_power(a: int, b: int): """ Function using divide and conquer to calculate a^b. It only works for integer a,b. """ if b == 0: return 1 if (b % 2) == 0: return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) else: return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) def power(a: int, b: int) -> float: """ >>> power(4,6) 4096 >>> power(2,3) 8 >>> power(-2,3) -8 >>> power(2,-3) 0.125 >>> power(-2,-3) -0.125 """ if b < 0: return 1 / actual_power(a, b) return actual_power(a, b) if __name__ == "__main__": print(power(-2, -3))
def actual_power(a: int, b: int): """ Function using divide and conquer to calculate a^b. It only works for integer a,b. """ if b == 0: return 1 if (b % 2) == 0: return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) else: return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) def power(a: int, b: int) -> float: """ >>> power(4,6) 4096 >>> power(2,3) 8 >>> power(-2,3) -8 >>> power(2,-3) 0.125 >>> power(-2,-3) -0.125 """ if b < 0: return 1 / actual_power(a, b) return actual_power(a, b) if __name__ == "__main__": print(power(-2, -3))
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" 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] = f"D{source_seq[i - 1]:c}" for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = f"I{destination_seq[i - 1]:c}" 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] = f"C{source_seq[i - 1]:c}" else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = f"R{source_seq[i - 1]:c}" + 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] = f"D{source_seq[i - 1]:c}" if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = f"I{destination_seq[j - 1]:c}" 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] = f"D{source_seq[i - 1]:c}" for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = f"I{destination_seq[i - 1]:c}" 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] = f"C{source_seq[i - 1]:c}" else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = f"R{source_seq[i - 1]:c}" + 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] = f"D{source_seq[i - 1]:c}" if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = f"I{destination_seq[j - 1]:c}" 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
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Check if three points are collinear in 3D. In short, the idea is that we are able to create a triangle using three points, and the area of that triangle can determine if the three points are collinear or not. First, we create two vectors with the same initial point from the three points, then we will calculate the cross-product of them. The length of the cross vector is numerically equal to the area of a parallelogram. Finally, the area of the triangle is equal to half of the area of the parallelogram. Since we are only differentiating between zero and anything else, we can get rid of the square root when calculating the length of the vector, and also the division by two at the end. From a second perspective, if the two vectors are parallel and overlapping, we can't get a nonzero perpendicular vector, since there will be an infinite number of orthogonal vectors. To simplify the solution we will not calculate the length, but we will decide directly from the vector whether it is equal to (0, 0, 0) or not. Read More: https://math.stackexchange.com/a/1951650 """ Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: """ Pass two points to get the vector from them in the form (x, y, z). >>> create_vector((0, 0, 0), (1, 1, 1)) (1, 1, 1) >>> create_vector((45, 70, 24), (47, 32, 1)) (2, -38, -23) >>> create_vector((-14, -1, -8), (-7, 6, 4)) (7, 7, 12) """ x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] return (x, y, z) def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d: """ Get the cross of the two vectors AB and AC. I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process. Read More: https://en.wikipedia.org/wiki/Cross_product https://en.wikipedia.org/wiki/Determinant >>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2)) (-55, 22, 11) >>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1)) (0, 0, 0) >>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12)) (-36, -48, 27) >>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33)) (-123.2594, 277.15110000000004, 129.11260000000001) """ x = ab[1] * ac[2] - ab[2] * ac[1] # *i y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j z = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def is_zero_vector(vector: Vector3d, accuracy: int) -> bool: """ Check if vector is equal to (0, 0, 0) of not. Sine the algorithm is very accurate, we will never get a zero vector, so we need to round the vector axis, because we want a result that is either True or False. In other applications, we can return a float that represents the collinearity ratio. >>> is_zero_vector((0, 0, 0), accuracy=10) True >>> is_zero_vector((15, 74, 32), accuracy=10) False >>> is_zero_vector((-15, -74, -32), accuracy=10) False """ return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool: """ Check if three points are collinear or not. 1- Create tow vectors AB and AC. 2- Get the cross vector of the tow vectors. 3- Calcolate the length of the cross vector. 4- If the length is zero then the points are collinear, else they are not. The use of the accuracy parameter is explained in is_zero_vector docstring. >>> are_collinear((4.802293498137402, 3.536233125455244, 0), ... (-2.186788107953106, -9.24561398001649, 7.141509524846482), ... (1.530169574640268, -2.447927606600034, 3.343487096469054)) True >>> are_collinear((-6, -2, 6), ... (6.200213806439997, -4.930157614926678, -4.482371908289856), ... (-4.085171149525941, -2.459889509029438, 4.354787180795383)) True >>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666), ... (-3.682816335934376, 5.753788986533145, 9.490993909044244), ... (1.962903518985307, 3.741415730125627, 7)) False >>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993), ... (-3.546599383667157, -4.630005261513976, 3.208784032924246), ... (-2.564606140206386, 3.937845170672183, 7)) False """ ab = create_vector(a, b) ac = create_vector(a, c) return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
""" Check if three points are collinear in 3D. In short, the idea is that we are able to create a triangle using three points, and the area of that triangle can determine if the three points are collinear or not. First, we create two vectors with the same initial point from the three points, then we will calculate the cross-product of them. The length of the cross vector is numerically equal to the area of a parallelogram. Finally, the area of the triangle is equal to half of the area of the parallelogram. Since we are only differentiating between zero and anything else, we can get rid of the square root when calculating the length of the vector, and also the division by two at the end. From a second perspective, if the two vectors are parallel and overlapping, we can't get a nonzero perpendicular vector, since there will be an infinite number of orthogonal vectors. To simplify the solution we will not calculate the length, but we will decide directly from the vector whether it is equal to (0, 0, 0) or not. Read More: https://math.stackexchange.com/a/1951650 """ Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: """ Pass two points to get the vector from them in the form (x, y, z). >>> create_vector((0, 0, 0), (1, 1, 1)) (1, 1, 1) >>> create_vector((45, 70, 24), (47, 32, 1)) (2, -38, -23) >>> create_vector((-14, -1, -8), (-7, 6, 4)) (7, 7, 12) """ x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] return (x, y, z) def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d: """ Get the cross of the two vectors AB and AC. I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process. Read More: https://en.wikipedia.org/wiki/Cross_product https://en.wikipedia.org/wiki/Determinant >>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2)) (-55, 22, 11) >>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1)) (0, 0, 0) >>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12)) (-36, -48, 27) >>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33)) (-123.2594, 277.15110000000004, 129.11260000000001) """ x = ab[1] * ac[2] - ab[2] * ac[1] # *i y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j z = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def is_zero_vector(vector: Vector3d, accuracy: int) -> bool: """ Check if vector is equal to (0, 0, 0) of not. Sine the algorithm is very accurate, we will never get a zero vector, so we need to round the vector axis, because we want a result that is either True or False. In other applications, we can return a float that represents the collinearity ratio. >>> is_zero_vector((0, 0, 0), accuracy=10) True >>> is_zero_vector((15, 74, 32), accuracy=10) False >>> is_zero_vector((-15, -74, -32), accuracy=10) False """ return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool: """ Check if three points are collinear or not. 1- Create tow vectors AB and AC. 2- Get the cross vector of the tow vectors. 3- Calcolate the length of the cross vector. 4- If the length is zero then the points are collinear, else they are not. The use of the accuracy parameter is explained in is_zero_vector docstring. >>> are_collinear((4.802293498137402, 3.536233125455244, 0), ... (-2.186788107953106, -9.24561398001649, 7.141509524846482), ... (1.530169574640268, -2.447927606600034, 3.343487096469054)) True >>> are_collinear((-6, -2, 6), ... (6.200213806439997, -4.930157614926678, -4.482371908289856), ... (-4.085171149525941, -2.459889509029438, 4.354787180795383)) True >>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666), ... (-3.682816335934376, 5.753788986533145, 9.490993909044244), ... (1.962903518985307, 3.741415730125627, 7)) False >>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993), ... (-3.546599383667157, -4.630005261513976, 3.208784032924246), ... (-2.564606140206386, 3.937845170672183, 7)) False """ ab = create_vector(a, b) ac = create_vector(a, c) return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
#!/usr/bin/env python3 """ Provide the current worldwide COVID-19 statistics. This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. """ import requests from bs4 import BeautifulSoup def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = soup.findAll("div", {"class": "maincounter-number"}) keys += soup.findAll("span", {"class": "panel-title"}) values += soup.findAll("div", {"class": "number-table-main"}) return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} if __name__ == "__main__": print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") for key, value in world_covid19_stats().items(): print(f"{key}\n{value}\n")
#!/usr/bin/env python3 """ Provide the current worldwide COVID-19 statistics. This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. """ import requests from bs4 import BeautifulSoup def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = soup.findAll("div", {"class": "maincounter-number"}) keys += soup.findAll("span", {"class": "panel-title"}) values += soup.findAll("div", {"class": "number-table-main"}) return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} if __name__ == "__main__": print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") for key, value in world_covid19_stats().items(): print(f"{key}\n{value}\n")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
def quick_sort(data: list) -> list: """ >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): ... quick_sort(data) == sorted(data) True True True """ if len(data) <= 1: return data else: return ( quick_sort([e for e in data[1:] if e <= data[0]]) + [data[0]] + quick_sort([e for e in data[1:] if e > data[0]]) ) if __name__ == "__main__": import doctest doctest.testmod()
def quick_sort(data: list) -> list: """ >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): ... quick_sort(data) == sorted(data) True True True """ if len(data) <= 1: return data else: return ( quick_sort([e for e in data[1:] if e <= data[0]]) + [data[0]] + quick_sort([e for e in data[1:] if e > data[0]]) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
# https://www.investopedia.com from __future__ import annotations def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: int ) -> float: """ >>> simple_interest(18000.0, 0.06, 3) 3240.0 >>> simple_interest(0.5, 0.06, 3) 0.09 >>> simple_interest(18000.0, 0.01, 10) 1800.0 >>> simple_interest(18000.0, 0.0, 3) 0.0 >>> simple_interest(5500.0, 0.01, 100) 5500.0 >>> simple_interest(10000.0, -0.06, 3) Traceback (most recent call last): ... ValueError: daily_interest_rate must be >= 0 >>> simple_interest(-10000.0, 0.06, 3) Traceback (most recent call last): ... ValueError: principal must be > 0 >>> simple_interest(5500.0, 0.01, -5) Traceback (most recent call last): ... ValueError: days_between_payments must be > 0 """ if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0") if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * daily_interest_rate * days_between_payments def compound_interest( principal: float, nominal_annual_interest_rate_percentage: float, number_of_compounding_periods: int, ) -> float: """ >>> compound_interest(10000.0, 0.05, 3) 1576.2500000000014 >>> compound_interest(10000.0, 0.05, 1) 500.00000000000045 >>> compound_interest(0.5, 0.05, 3) 0.07881250000000006 >>> compound_interest(10000.0, 0.06, -4) Traceback (most recent call last): ... ValueError: number_of_compounding_periods must be > 0 >>> compound_interest(10000.0, -3.5, 3.0) Traceback (most recent call last): ... ValueError: nominal_annual_interest_rate_percentage must be >= 0 >>> compound_interest(-5500.0, 0.01, 5) Traceback (most recent call last): ... ValueError: principal must be > 0 """ if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0") if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.investopedia.com from __future__ import annotations def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: int ) -> float: """ >>> simple_interest(18000.0, 0.06, 3) 3240.0 >>> simple_interest(0.5, 0.06, 3) 0.09 >>> simple_interest(18000.0, 0.01, 10) 1800.0 >>> simple_interest(18000.0, 0.0, 3) 0.0 >>> simple_interest(5500.0, 0.01, 100) 5500.0 >>> simple_interest(10000.0, -0.06, 3) Traceback (most recent call last): ... ValueError: daily_interest_rate must be >= 0 >>> simple_interest(-10000.0, 0.06, 3) Traceback (most recent call last): ... ValueError: principal must be > 0 >>> simple_interest(5500.0, 0.01, -5) Traceback (most recent call last): ... ValueError: days_between_payments must be > 0 """ if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0") if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * daily_interest_rate * days_between_payments def compound_interest( principal: float, nominal_annual_interest_rate_percentage: float, number_of_compounding_periods: int, ) -> float: """ >>> compound_interest(10000.0, 0.05, 3) 1576.2500000000014 >>> compound_interest(10000.0, 0.05, 1) 500.00000000000045 >>> compound_interest(0.5, 0.05, 3) 0.07881250000000006 >>> compound_interest(10000.0, 0.06, -4) Traceback (most recent call last): ... ValueError: number_of_compounding_periods must be > 0 >>> compound_interest(10000.0, -3.5, 3.0) Traceback (most recent call last): ... ValueError: nominal_annual_interest_rate_percentage must be >= 0 >>> compound_interest(-5500.0, 0.01, 5) Traceback (most recent call last): ... ValueError: principal must be > 0 """ if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0") if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,258
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`
### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
ngiachou
"2022-07-20T00:10:06Z"
"2022-09-14T08:40:04Z"
81e30fd33c91bc37bc3baf54c42d1b192ecf41a6
2104fa7aebe8d76b2b2b2c47fe7e2ee615a05df6
Unify `O(sqrt(N))` `is_prime` functions under `project_euler`. ### Describe your change: I changed the implementation of is_prime functions inside project_euler in order to have a unified implementation. There are some cases where the solution uses the Eratosthenes' sieve method. In some cases there is no specific gain from using that method so I changed it to the O(sqrt(n)) algorithm, but in other cases the sieve method is used in the core structure of the solution, hence I did not touch those. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. fixes #5434
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def MF_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global F # a global dp table for knapsack if F[i][j] < 0: if j < wt[i - 1]: val = MF_knapsack(i - 1, wt, val, j) else: val = max( MF_knapsack(i - 1, wt, val, j), MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) F[i][j] = val return F[i][j] def knapsack(W, wt, val, n): dp = [[0 for i in range(W + 1)] for j in range(n + 1)] for i in range(1, n + 1): for w in range(1, W + 1): if wt[i - 1] <= w: dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]) else: dp[i][w] = dp[i - 1][w] return dp[n][W], dp def knapsack_with_example_solution(W: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): raise ValueError( "The number of weights must be the " "same as the number of values.\nBut " f"got {num_items} weights and {len(val)} values" ) for i in range(num_items): if not isinstance(wt[i], int): raise TypeError( "All weights must be integers but " f"got weight of type {type(wt[i])} at index {i}" ) optimal_val, dp_table = knapsack(W, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, W, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(MF_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def MF_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global F # a global dp table for knapsack if F[i][j] < 0: if j < wt[i - 1]: val = MF_knapsack(i - 1, wt, val, j) else: val = max( MF_knapsack(i - 1, wt, val, j), MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) F[i][j] = val return F[i][j] def knapsack(W, wt, val, n): dp = [[0 for i in range(W + 1)] for j in range(n + 1)] for i in range(1, n + 1): for w in range(1, W + 1): if wt[i - 1] <= w: dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]) else: dp[i][w] = dp[i - 1][w] return dp[n][W], dp def knapsack_with_example_solution(W: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): raise ValueError( "The number of weights must be the " "same as the number of values.\nBut " f"got {num_items} weights and {len(val)} values" ) for i in range(num_items): if not isinstance(wt[i], int): raise TypeError( "All weights must be integers but " f"got weight of type {type(wt[i])} at index {i}" ) optimal_val, dp_table = knapsack(W, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, W, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(MF_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
-1