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
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works (Evaluation, Selection, Crossover and Mutation) https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia """ from __future__ import annotations import random # Maximum size of the population. bigger could be faster but is more memory expensive N_POPULATION = 200 # Number of elements selected in every generation for evolution the selection takes # place from the best to the worst of that generation must be smaller than N_POPULATION N_SELECTED = 50 # Probability that an element of a generation can mutate changing one of its genes this # guarantees that all genes will be used during evolution MUTATION_PROBABILITY = 0.4 # just a seed to improve randomness required by the algorithm random.seed(random.randint(0, 1000)) def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: """ Verify that the target contains no genes besides the ones inside genes variable. >>> from string import ascii_lowercase >>> basic("doctest", ascii_lowercase, debug=False)[2] 'doctest' >>> genes = list(ascii_lowercase) >>> genes.remove("e") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e'] is not in genes list, evolution cannot converge >>> genes.remove("s") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's'] is not in genes list, evolution cannot converge >>> genes.remove("t") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge """ # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}") # Verify that the target contains no genes besides the ones inside genes variable. not_in_genes_list = sorted({c for c in target if c not in genes}) if not_in_genes_list: raise ValueError( f"{not_in_genes_list} is not in genes list, evolution cannot converge" ) # Generate random starting population population = [] for _ in range(N_POPULATION): population.append("".join([random.choice(genes) for i in range(len(target))])) # Just some logs to know what the algorithms is doing generation, total_population = 0, 0 # This loop will end when we will find a perfect match for our target while True: generation += 1 total_population += len(population) # Random population created now it's time to evaluate def evaluate(item: str, main_target: str = target) -> tuple[str, float]: """ Evaluate how similar the item is with the target by just counting each char in the right position >>> evaluate("Helxo Worlx", Hello World) ["Helxo Worlx", 9] """ score = len( [g for position, g in enumerate(item) if g == main_target[position]] ) return (item, float(score)) # noqa: B023 # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this will probably be slower # we just need to call evaluate for every item inside population population_score = [evaluate(item) for item in population] # Check if there is a matching evolution population_score = sorted(population_score, key=lambda x: x[1], reverse=True) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the Best result every 10 generation # just to know that the algorithm is working if debug and generation % 10 == 0: print( f"\nGeneration: {generation}" f"\nTotal Population:{total_population}" f"\nBest score: {population_score[0][1]}" f"\nBest string: {population_score[0][0]}" ) # Flush the old population keeping some of the best evolutions # Keeping this avoid regression of evolution population_best = population[: int(N_POPULATION / 3)] population.clear() population.extend(population_best) # Normalize population score from 0 to 1 population_score = [ (item, score / len(target)) for item, score in population_score ] # Select, Crossover and Mutate a new population def select(parent_1: tuple[str, float]) -> list[str]: """Select the second parent and generate new population""" pop = [] # Generate more child proportionally to the fitness score child_n = int(parent_1[1] * 100) + 1 child_n = 10 if child_n >= 10 else child_n for _ in range(child_n): parent_2 = population_score[ # noqa: B023 random.randint(0, N_SELECTED) ][0] child_1, child_2 = crossover(parent_1[0], parent_2) # Append new string to the population list pop.append(mutate(child_1)) pop.append(mutate(child_2)) return pop def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: """Slice and combine two string in a random point""" random_slice = random.randint(0, len(parent_1) - 1) child_1 = parent_1[:random_slice] + parent_2[random_slice:] child_2 = parent_2[:random_slice] + parent_1[random_slice:] return (child_1, child_2) def mutate(child: str) -> str: """Mutate a random gene of a child with another one from the list""" child_list = list(child) if random.uniform(0, 1) < MUTATION_PROBABILITY: child_list[random.randint(0, len(child)) - 1] = random.choice(genes) return "".join(child_list) # This is Selection for i in range(N_SELECTED): population.extend(select(population_score[int(i)])) # Check if the population has already reached the maximum value and if so, # break the cycle. if this check is disabled the algorithm will take # forever to compute large strings but will also calculate small string in # a lot fewer generations if len(population) > N_POPULATION: break if __name__ == "__main__": target_str = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) genes_list = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$Β£/\\" ) print( "\nGeneration: %s\nTotal Population: %s\nTarget: %s" % basic(target_str, genes_list) )
""" Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works (Evaluation, Selection, Crossover and Mutation) https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia """ from __future__ import annotations import random # Maximum size of the population. bigger could be faster but is more memory expensive N_POPULATION = 200 # Number of elements selected in every generation for evolution the selection takes # place from the best to the worst of that generation must be smaller than N_POPULATION N_SELECTED = 50 # Probability that an element of a generation can mutate changing one of its genes this # guarantees that all genes will be used during evolution MUTATION_PROBABILITY = 0.4 # just a seed to improve randomness required by the algorithm random.seed(random.randint(0, 1000)) def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: """ Verify that the target contains no genes besides the ones inside genes variable. >>> from string import ascii_lowercase >>> basic("doctest", ascii_lowercase, debug=False)[2] 'doctest' >>> genes = list(ascii_lowercase) >>> genes.remove("e") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e'] is not in genes list, evolution cannot converge >>> genes.remove("s") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's'] is not in genes list, evolution cannot converge >>> genes.remove("t") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge """ # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}") # Verify that the target contains no genes besides the ones inside genes variable. not_in_genes_list = sorted({c for c in target if c not in genes}) if not_in_genes_list: raise ValueError( f"{not_in_genes_list} is not in genes list, evolution cannot converge" ) # Generate random starting population population = [] for _ in range(N_POPULATION): population.append("".join([random.choice(genes) for i in range(len(target))])) # Just some logs to know what the algorithms is doing generation, total_population = 0, 0 # This loop will end when we will find a perfect match for our target while True: generation += 1 total_population += len(population) # Random population created now it's time to evaluate def evaluate(item: str, main_target: str = target) -> tuple[str, float]: """ Evaluate how similar the item is with the target by just counting each char in the right position >>> evaluate("Helxo Worlx", Hello World) ["Helxo Worlx", 9] """ score = len( [g for position, g in enumerate(item) if g == main_target[position]] ) return (item, float(score)) # noqa: B023 # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this will probably be slower # we just need to call evaluate for every item inside population population_score = [evaluate(item) for item in population] # Check if there is a matching evolution population_score = sorted(population_score, key=lambda x: x[1], reverse=True) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the Best result every 10 generation # just to know that the algorithm is working if debug and generation % 10 == 0: print( f"\nGeneration: {generation}" f"\nTotal Population:{total_population}" f"\nBest score: {population_score[0][1]}" f"\nBest string: {population_score[0][0]}" ) # Flush the old population keeping some of the best evolutions # Keeping this avoid regression of evolution population_best = population[: int(N_POPULATION / 3)] population.clear() population.extend(population_best) # Normalize population score from 0 to 1 population_score = [ (item, score / len(target)) for item, score in population_score ] # Select, Crossover and Mutate a new population def select(parent_1: tuple[str, float]) -> list[str]: """Select the second parent and generate new population""" pop = [] # Generate more child proportionally to the fitness score child_n = int(parent_1[1] * 100) + 1 child_n = 10 if child_n >= 10 else child_n for _ in range(child_n): parent_2 = population_score[ # noqa: B023 random.randint(0, N_SELECTED) ][0] child_1, child_2 = crossover(parent_1[0], parent_2) # Append new string to the population list pop.append(mutate(child_1)) pop.append(mutate(child_2)) return pop def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: """Slice and combine two string in a random point""" random_slice = random.randint(0, len(parent_1) - 1) child_1 = parent_1[:random_slice] + parent_2[random_slice:] child_2 = parent_2[:random_slice] + parent_1[random_slice:] return (child_1, child_2) def mutate(child: str) -> str: """Mutate a random gene of a child with another one from the list""" child_list = list(child) if random.uniform(0, 1) < MUTATION_PROBABILITY: child_list[random.randint(0, len(child)) - 1] = random.choice(genes) return "".join(child_list) # This is Selection for i in range(N_SELECTED): population.extend(select(population_score[int(i)])) # Check if the population has already reached the maximum value and if so, # break the cycle. if this check is disabled the algorithm will take # forever to compute large strings but will also calculate small string in # a lot fewer generations if len(population) > N_POPULATION: break if __name__ == "__main__": target_str = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) genes_list = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$Β£/\\" ) print( "\nGeneration: %s\nTotal Population: %s\nTarget: %s" % basic(target_str, genes_list) )
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a Python implementation of the circle sort algorithm For doctests run following command: python3 -m doctest -v circle_sort.py For manual testing run: python3 circle_sort.py """ def circle_sort(collection: list) -> list: """A pure Python implementation of circle sort algorithm :param collection: a mutable collection of comparable items in any order :return: the same collection in ascending order Examples: >>> circle_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> circle_sort([]) [] >>> circle_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45]) >>> all(sorted(collection) == circle_sort(collection) for collection in collections) True """ if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: """ >>> arr = [5,4,3,2,1] >>> circle_sort_util(lst, 0, 2) True >>> arr [3, 4, 5, 2, 1] """ swapped = False if low == high: return swapped left = low right = high while left < right: if collection[left] > collection[right]: collection[left], collection[right] = ( collection[right], collection[left], ) swapped = True left += 1 right -= 1 if left == right: if collection[left] > collection[right + 1]: collection[left], collection[right + 1] = ( collection[right + 1], collection[left], ) swapped = True mid = low + int((high - low) / 2) left_swap = circle_sort_util(collection, low, mid) right_swap = circle_sort_util(collection, mid + 1, high) return swapped or left_swap or right_swap is_not_sorted = True while is_not_sorted is True: is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
""" This is a Python implementation of the circle sort algorithm For doctests run following command: python3 -m doctest -v circle_sort.py For manual testing run: python3 circle_sort.py """ def circle_sort(collection: list) -> list: """A pure Python implementation of circle sort algorithm :param collection: a mutable collection of comparable items in any order :return: the same collection in ascending order Examples: >>> circle_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> circle_sort([]) [] >>> circle_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45]) >>> all(sorted(collection) == circle_sort(collection) for collection in collections) True """ if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: """ >>> arr = [5,4,3,2,1] >>> circle_sort_util(lst, 0, 2) True >>> arr [3, 4, 5, 2, 1] """ swapped = False if low == high: return swapped left = low right = high while left < right: if collection[left] > collection[right]: collection[left], collection[right] = ( collection[right], collection[left], ) swapped = True left += 1 right -= 1 if left == right: if collection[left] > collection[right + 1]: collection[left], collection[right + 1] = ( collection[right + 1], collection[left], ) swapped = True mid = low + int((high - low) / 2) left_swap = circle_sort_util(collection, low, mid) right_swap = circle_sort_util(collection, mid + 1, high) return swapped or left_swap or right_swap is_not_sorted = True while is_not_sorted is True: is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar T = TypeVar("T") class LRUCache(Generic[T]): """ Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.refer(2) >>> lru_cache.refer(3) >>> lru_cache LRUCache(4) => [3, 2, 'A'] >>> lru_cache.refer("A") >>> lru_cache LRUCache(4) => ['A', 3, 2] >>> lru_cache.refer(4) >>> lru_cache.refer(5) >>> lru_cache LRUCache(4) => [5, 4, 'A', 3] """ dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: """ Looks for a page in the cache store and adds reference to the set. Remove the least recently used key if the store is full. Update store to reflect recent access. """ if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: """ Prints all the elements in the store. """ for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar T = TypeVar("T") class LRUCache(Generic[T]): """ Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.refer(2) >>> lru_cache.refer(3) >>> lru_cache LRUCache(4) => [3, 2, 'A'] >>> lru_cache.refer("A") >>> lru_cache LRUCache(4) => ['A', 3, 2] >>> lru_cache.refer(4) >>> lru_cache.refer(5) >>> lru_cache LRUCache(4) => [5, 4, 'A', 3] """ dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: """ Looks for a page in the cache store and adds reference to the set. Remove the least recently used key if the store is full. Update store to reflect recent access. """ if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: """ Prints all the elements in the store. """ for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Lucas_number """ def recursive_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> recursive_lucas_number(1) 1 >>> recursive_lucas_number(20) 15127 >>> recursive_lucas_number(0) 2 >>> recursive_lucas_number(25) 167761 >>> recursive_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: recursive_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: return 2 if n_th_number == 1: return 1 return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number( n_th_number - 2 ) def dynamic_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> dynamic_lucas_number(1) 1 >>> dynamic_lucas_number(20) 15127 >>> dynamic_lucas_number(0) 2 >>> dynamic_lucas_number(25) 167761 >>> dynamic_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: dynamic_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 for _ in range(n_th_number): a, b = b, a + b return a if __name__ == "__main__": from doctest import testmod testmod() n = int(input("Enter the number of terms in lucas series:\n").strip()) print("Using recursive function to calculate lucas series:") print(" ".join(str(recursive_lucas_number(i)) for i in range(n))) print("\nUsing dynamic function to calculate lucas series:") print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))
""" https://en.wikipedia.org/wiki/Lucas_number """ def recursive_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> recursive_lucas_number(1) 1 >>> recursive_lucas_number(20) 15127 >>> recursive_lucas_number(0) 2 >>> recursive_lucas_number(25) 167761 >>> recursive_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: recursive_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: return 2 if n_th_number == 1: return 1 return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number( n_th_number - 2 ) def dynamic_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> dynamic_lucas_number(1) 1 >>> dynamic_lucas_number(20) 15127 >>> dynamic_lucas_number(0) 2 >>> dynamic_lucas_number(25) 167761 >>> dynamic_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: dynamic_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 for _ in range(n_th_number): a, b = b, a + b return a if __name__ == "__main__": from doctest import testmod testmod() n = int(input("Enter the number of terms in lucas series:\n").strip()) print("Using recursive function to calculate lucas series:") print(" ".join(str(recursive_lucas_number(i)) for i in range(n))) print("\nUsing dynamic function to calculate lucas series:") print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The nested brackets problem is a problem that determines if a sequence of brackets are properly nested. A sequence of brackets s is considered properly nested if any of the following conditions are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s has the form VW where V and W are properly nested strings For example, the string "()()[()]" is properly nested but "[(()]" is not. The function called is_balanced takes as input a string S which is a sequence of brackets and returns true if S is nested and false otherwise. """ def is_balanced(s): stack = [] open_brackets = set({"(", "[", "{"}) closed_brackets = set({")", "]", "}"}) open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) for i in range(len(s)): if s[i] in open_brackets: stack.append(s[i]) elif s[i] in closed_brackets: if len(stack) == 0 or ( len(stack) > 0 and open_to_closed[stack.pop()] != s[i] ): return False return len(stack) == 0 def main(): s = input("Enter sequence of brackets: ") if is_balanced(s): print(s, "is balanced") else: print(s, "is not balanced") if __name__ == "__main__": main()
""" The nested brackets problem is a problem that determines if a sequence of brackets are properly nested. A sequence of brackets s is considered properly nested if any of the following conditions are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s has the form VW where V and W are properly nested strings For example, the string "()()[()]" is properly nested but "[(()]" is not. The function called is_balanced takes as input a string S which is a sequence of brackets and returns true if S is nested and false otherwise. """ def is_balanced(s): stack = [] open_brackets = set({"(", "[", "{"}) closed_brackets = set({")", "]", "}"}) open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) for i in range(len(s)): if s[i] in open_brackets: stack.append(s[i]) elif s[i] in closed_brackets: if len(stack) == 0 or ( len(stack) > 0 and open_to_closed[stack.pop()] != s[i] ): return False return len(stack) == 0 def main(): s = input("Enter sequence of brackets: ") if is_balanced(s): print(s, "is balanced") else: print(s, "is not balanced") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hβ‚™ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hβ‚™ = n(2n-1) where: hβ‚™ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hβ‚™ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hβ‚™ = n(2n-1) where: hβ‚™ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations DIRECTIONS = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] # function to search the path def search( grid: list[list[int]], init: list[int], goal: list[int], cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]], list[list[int]]]: closed = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the reference grid closed[init[0]][init[1]] = 1 action = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the action grid x = init[0] y = init[1] g = 0 f = g + heuristic[x][y] # cost from starting cell to destination cell cell = [[f, g, x, y]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand while not found and not resign: if len(cell) == 0: raise ValueError("Algorithm is unable to find solution") else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() next_cell = cell.pop() x = next_cell[2] y = next_cell[3] g = next_cell[1] if x == goal[0] and y == goal[1]: found = True else: for i in range(len(DIRECTIONS)): # to try out different valid actions x2 = x + DIRECTIONS[i][0] y2 = y + DIRECTIONS[i][1] if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]): if closed[x2][y2] == 0 and grid[x2][y2] == 0: g2 = g + cost f2 = g2 + heuristic[x2][y2] cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i invpath = [] x = goal[0] y = goal[1] invpath.append([x, y]) # we get the reverse path from here while x != init[0] or y != init[1]: x2 = x - DIRECTIONS[action[x][y]][0] y2 = y - DIRECTIONS[action[x][y]][1] x = x2 y = y2 invpath.append([x, y]) path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) return path, action if __name__ == "__main__": grid = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] init = [0, 0] # all coordinates are given in format [y,x] goal = [len(grid) - 1, len(grid[0]) - 1] cost = 1 # the cost map which pushes the path closer to the goal heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map heuristic[i][j] = 99 path, action = search(grid, init, goal, cost, heuristic) print("ACTION MAP") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
from __future__ import annotations DIRECTIONS = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] # function to search the path def search( grid: list[list[int]], init: list[int], goal: list[int], cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]], list[list[int]]]: closed = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the reference grid closed[init[0]][init[1]] = 1 action = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the action grid x = init[0] y = init[1] g = 0 f = g + heuristic[x][y] # cost from starting cell to destination cell cell = [[f, g, x, y]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand while not found and not resign: if len(cell) == 0: raise ValueError("Algorithm is unable to find solution") else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() next_cell = cell.pop() x = next_cell[2] y = next_cell[3] g = next_cell[1] if x == goal[0] and y == goal[1]: found = True else: for i in range(len(DIRECTIONS)): # to try out different valid actions x2 = x + DIRECTIONS[i][0] y2 = y + DIRECTIONS[i][1] if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]): if closed[x2][y2] == 0 and grid[x2][y2] == 0: g2 = g + cost f2 = g2 + heuristic[x2][y2] cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i invpath = [] x = goal[0] y = goal[1] invpath.append([x, y]) # we get the reverse path from here while x != init[0] or y != init[1]: x2 = x - DIRECTIONS[action[x][y]][0] y2 = y - DIRECTIONS[action[x][y]][1] x = x2 y = y2 invpath.append([x, y]) path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) return path, action if __name__ == "__main__": grid = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] init = [0, 0] # all coordinates are given in format [y,x] goal = [len(grid) - 1, len(grid[0]) - 1] cost = 1 # the cost map which pushes the path closer to the goal heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map heuristic[i][j] = 99 path, action = search(grid, init, goal, cost, heuristic) print("ACTION MAP") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) Discussion in stackoverflow: https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array """ from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: """ >>> make_matrix() [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] >>> make_matrix(1) [[1]] >>> make_matrix(-2) [[1, 2], [3, 4]] >>> make_matrix(3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> make_matrix() == make_matrix(4) True """ row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_90(make_matrix()) [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] >>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix())) True """ return reverse_row(transpose(matrix)) # OR.. transpose(reverse_column(matrix)) def rotate_180(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_180(make_matrix()) [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] >>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix())) True """ return reverse_row(reverse_column(matrix)) # OR.. reverse_column(reverse_row(matrix)) def rotate_270(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_270(make_matrix()) [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] >>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix())) True """ return reverse_column(transpose(matrix)) # OR.. transpose(reverse_row(matrix)) def transpose(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [list(x) for x in zip(*matrix)] return matrix def reverse_row(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = matrix[::-1] return matrix def reverse_column(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [x[::-1] for x in matrix] return matrix def print_matrix(matrix: list[list[int]]) -> None: for i in matrix: print(*i) if __name__ == "__main__": matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_90(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_180(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_270(matrix))
""" In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) Discussion in stackoverflow: https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array """ from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: """ >>> make_matrix() [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] >>> make_matrix(1) [[1]] >>> make_matrix(-2) [[1, 2], [3, 4]] >>> make_matrix(3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> make_matrix() == make_matrix(4) True """ row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_90(make_matrix()) [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] >>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix())) True """ return reverse_row(transpose(matrix)) # OR.. transpose(reverse_column(matrix)) def rotate_180(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_180(make_matrix()) [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] >>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix())) True """ return reverse_row(reverse_column(matrix)) # OR.. reverse_column(reverse_row(matrix)) def rotate_270(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_270(make_matrix()) [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] >>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix())) True """ return reverse_column(transpose(matrix)) # OR.. transpose(reverse_row(matrix)) def transpose(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [list(x) for x in zip(*matrix)] return matrix def reverse_row(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = matrix[::-1] return matrix def reverse_column(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [x[::-1] for x in matrix] return matrix def print_matrix(matrix: list[list[int]]) -> None: for i in matrix: print(*i) if __name__ == "__main__": matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_90(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_180(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_270(matrix))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a type of divide and conquer algorithm which divides the search space into 3 parts and finds the target value based on the property of the array or list (usually monotonic property). Time Complexity : O(log3 N) Space Complexity : O(1) """ from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. precision = 10 # This is the linear search that will occur after the search space has become smaller. def lin_search(left: int, right: int, array: list[int], target: int) -> int: """Perform linear search in list. Returns -1 if element is not found. Parameters ---------- left : int left index bound. right : int right index bound. array : List[int] List of elements to be searched on target : int Element that is searched Returns ------- int index of element that is looked for. Examples -------- >>> lin_search(0, 4, [4, 5, 6, 7], 7) 3 >>> lin_search(0, 3, [4, 5, 6, 7], 7) -1 >>> lin_search(0, 2, [-18, 2], -18) 0 >>> lin_search(0, 1, [5], 5) 0 >>> lin_search(0, 3, ['a', 'c', 'd'], 'c') 1 >>> lin_search(0, 3, [.1, .4 , -.1], .1) 0 >>> lin_search(0, 3, [.1, .4 , -.1], -.1) 2 """ for i in range(left, right): if array[i] == target: return i return -1 def ite_ternary_search(array: list[int], target: int) -> int: """Iterative method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> ite_ternary_search(test_list, 3) -1 >>> ite_ternary_search(test_list, 13) 4 >>> ite_ternary_search([4, 5, 6, 7], 4) 0 >>> ite_ternary_search([4, 5, 6, 7], -10) -1 >>> ite_ternary_search([-18, 2], -18) 0 >>> ite_ternary_search([5], 5) 0 >>> ite_ternary_search(['a', 'c', 'd'], 'c') 1 >>> ite_ternary_search(['a', 'c', 'd'], 'f') -1 >>> ite_ternary_search([], 1) -1 >>> ite_ternary_search([.1, .4 , -.1], .1) 0 """ left = 0 right = len(array) while left <= right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: right = one_third - 1 elif array[two_third] < target: left = two_third + 1 else: left = one_third + 1 right = two_third - 1 else: return -1 def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int: """Recursive method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> rec_ternary_search(0, len(test_list), test_list, 3) -1 >>> rec_ternary_search(4, len(test_list), test_list, 42) 8 >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4) 0 >>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10) -1 >>> rec_ternary_search(0, 1, [-18, 2], -18) 0 >>> rec_ternary_search(0, 1, [5], 5) 0 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c') 1 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f') -1 >>> rec_ternary_search(0, 0, [], 1) -1 >>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1) 0 """ if left < right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(left, one_third - 1, array, target) elif array[two_third] < target: return rec_ternary_search(two_third + 1, right, array, target) else: return rec_ternary_search(one_third + 1, two_third - 1, array, target) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n").strip() collection = [int(item.strip()) for item in user_input.split(",")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." target = int(input("Enter the number to be found in the list:\n").strip()) result1 = ite_ternary_search(collection, target) result2 = rec_ternary_search(0, len(collection) - 1, collection, target) if result2 != -1: print(f"Iterative search: {target} found at positions: {result1}") print(f"Recursive search: {target} found at positions: {result2}") else: print("Not found")
""" This is a type of divide and conquer algorithm which divides the search space into 3 parts and finds the target value based on the property of the array or list (usually monotonic property). Time Complexity : O(log3 N) Space Complexity : O(1) """ from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. precision = 10 # This is the linear search that will occur after the search space has become smaller. def lin_search(left: int, right: int, array: list[int], target: int) -> int: """Perform linear search in list. Returns -1 if element is not found. Parameters ---------- left : int left index bound. right : int right index bound. array : List[int] List of elements to be searched on target : int Element that is searched Returns ------- int index of element that is looked for. Examples -------- >>> lin_search(0, 4, [4, 5, 6, 7], 7) 3 >>> lin_search(0, 3, [4, 5, 6, 7], 7) -1 >>> lin_search(0, 2, [-18, 2], -18) 0 >>> lin_search(0, 1, [5], 5) 0 >>> lin_search(0, 3, ['a', 'c', 'd'], 'c') 1 >>> lin_search(0, 3, [.1, .4 , -.1], .1) 0 >>> lin_search(0, 3, [.1, .4 , -.1], -.1) 2 """ for i in range(left, right): if array[i] == target: return i return -1 def ite_ternary_search(array: list[int], target: int) -> int: """Iterative method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> ite_ternary_search(test_list, 3) -1 >>> ite_ternary_search(test_list, 13) 4 >>> ite_ternary_search([4, 5, 6, 7], 4) 0 >>> ite_ternary_search([4, 5, 6, 7], -10) -1 >>> ite_ternary_search([-18, 2], -18) 0 >>> ite_ternary_search([5], 5) 0 >>> ite_ternary_search(['a', 'c', 'd'], 'c') 1 >>> ite_ternary_search(['a', 'c', 'd'], 'f') -1 >>> ite_ternary_search([], 1) -1 >>> ite_ternary_search([.1, .4 , -.1], .1) 0 """ left = 0 right = len(array) while left <= right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: right = one_third - 1 elif array[two_third] < target: left = two_third + 1 else: left = one_third + 1 right = two_third - 1 else: return -1 def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int: """Recursive method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> rec_ternary_search(0, len(test_list), test_list, 3) -1 >>> rec_ternary_search(4, len(test_list), test_list, 42) 8 >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4) 0 >>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10) -1 >>> rec_ternary_search(0, 1, [-18, 2], -18) 0 >>> rec_ternary_search(0, 1, [5], 5) 0 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c') 1 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f') -1 >>> rec_ternary_search(0, 0, [], 1) -1 >>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1) 0 """ if left < right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(left, one_third - 1, array, target) elif array[two_third] < target: return rec_ternary_search(two_third + 1, right, array, target) else: return rec_ternary_search(one_third + 1, two_third - 1, array, target) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n").strip() collection = [int(item.strip()) for item in user_input.split(",")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." target = int(input("Enter the number to be found in the list:\n").strip()) result1 = ite_ternary_search(collection, target) result2 = rec_ternary_search(0, len(collection) - 1, collection, target) if result2 != -1: print(f"Iterative search: {target} found at positions: {result1}") print(f"Recursive search: {target} found at positions: {result2}") else: print("Not found")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author: Mohit Radadiya """ from string import ascii_uppercase dict1 = {char: i for i, char in enumerate(ascii_uppercase)} dict2 = {i: char for i, char in enumerate(ascii_uppercase)} # This function generates the key in # a cyclic manner until it's length isn't # equal to the length of original text def generate_key(message: str, key: str) -> str: """ >>> generate_key("THE GERMAN ATTACK","SECRET") 'SECRETSECRETSECRE' """ x = len(message) i = 0 while True: if x == i: i = 0 if len(key) == len(message): break key += key[i] i += 1 return key # This function returns the encrypted text # generated with the help of the key def cipher_text(message: str, key_new: str) -> str: """ >>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE") 'BDC PAYUWL JPAIYI' """ cipher_text = "" i = 0 for letter in message: if letter == " ": cipher_text += " " else: x = (dict1[letter] - dict1[key_new[i]]) % 26 i += 1 cipher_text += dict2[x] return cipher_text # This function decrypts the encrypted text # and returns the original text def original_text(cipher_text: str, key_new: str) -> str: """ >>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE") 'THE GERMAN ATTACK' """ or_txt = "" i = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 i += 1 or_txt += dict2[x] return or_txt def main() -> None: message = "THE GERMAN ATTACK" key = "SECRET" key_new = generate_key(message, key) s = cipher_text(message, key_new) print(f"Encrypted Text = {s}") print(f"Original Text = {original_text(s, key_new)}") if __name__ == "__main__": import doctest doctest.testmod() main()
""" Author: Mohit Radadiya """ from string import ascii_uppercase dict1 = {char: i for i, char in enumerate(ascii_uppercase)} dict2 = {i: char for i, char in enumerate(ascii_uppercase)} # This function generates the key in # a cyclic manner until it's length isn't # equal to the length of original text def generate_key(message: str, key: str) -> str: """ >>> generate_key("THE GERMAN ATTACK","SECRET") 'SECRETSECRETSECRE' """ x = len(message) i = 0 while True: if x == i: i = 0 if len(key) == len(message): break key += key[i] i += 1 return key # This function returns the encrypted text # generated with the help of the key def cipher_text(message: str, key_new: str) -> str: """ >>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE") 'BDC PAYUWL JPAIYI' """ cipher_text = "" i = 0 for letter in message: if letter == " ": cipher_text += " " else: x = (dict1[letter] - dict1[key_new[i]]) % 26 i += 1 cipher_text += dict2[x] return cipher_text # This function decrypts the encrypted text # and returns the original text def original_text(cipher_text: str, key_new: str) -> str: """ >>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE") 'THE GERMAN ATTACK' """ or_txt = "" i = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 i += 1 or_txt += dict2[x] return or_txt def main() -> None: message = "THE GERMAN ATTACK" key = "SECRET" key_new = generate_key(message, key) s = cipher_text(message, key_new) print(f"Encrypted Text = {s}") print(f"Original Text = {original_text(s, key_new)}") if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Public/Teaching/ORF523/ORF523_Lec6.pdf """ def matching_min_vertex_cover(graph: dict) -> set: """ APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cover(graph) {0, 1, 2, 4} """ # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: from_node, to_node = edges.pop() chosen_vertices.add(from_node) chosen_vertices.add(to_node) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(edge) return chosen_vertices def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph) {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)} """ edges = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node)) return edges 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"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Public/Teaching/ORF523/ORF523_Lec6.pdf """ def matching_min_vertex_cover(graph: dict) -> set: """ APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cover(graph) {0, 1, 2, 4} """ # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: from_node, to_node = edges.pop() chosen_vertices.add(from_node) chosen_vertices.add(to_node) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(edge) return chosen_vertices def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph) {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)} """ edges = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node)) return edges 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"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from string import ascii_lowercase, ascii_uppercase def capitalize(sentence: str) -> str: """ This function will capitalize the first letter of a sentence or a word >>> capitalize("hello world") 'Hello world' >>> capitalize("123 hello world") '123 hello world' >>> capitalize(" hello world") ' hello world' >>> capitalize("a") 'A' >>> capitalize("") '' """ if not sentence: return "" lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)} return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
from string import ascii_lowercase, ascii_uppercase def capitalize(sentence: str) -> str: """ This function will capitalize the first letter of a sentence or a word >>> capitalize("hello world") 'Hello world' >>> capitalize("123 hello world") '123 hello world' >>> capitalize(" hello world") ' hello world' >>> capitalize("a") 'A' >>> capitalize("") '' """ if not sentence: return "" lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)} return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda l: l.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if type(root) is Letter: root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda l: l.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if type(root) is Letter: root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Convert speed units https://en.wikipedia.org/wiki/Kilometres_per_hour https://en.wikipedia.org/wiki/Miles_per_hour https://en.wikipedia.org/wiki/Knot_(unit) https://en.wikipedia.org/wiki/Metre_per_second """ speed_chart: dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } speed_chart_inverse: dict[str, float] = { "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def convert_speed(speed: float, unit_from: str, unit_to: str) -> float: """ Convert speed from one unit to another using the speed_chart above. "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, >>> convert_speed(100, "km/h", "m/s") 27.778 >>> convert_speed(100, "km/h", "mph") 62.137 >>> convert_speed(100, "km/h", "knot") 53.996 >>> convert_speed(100, "m/s", "km/h") 360.0 >>> convert_speed(100, "m/s", "mph") 223.694 >>> convert_speed(100, "m/s", "knot") 194.384 >>> convert_speed(100, "mph", "km/h") 160.934 >>> convert_speed(100, "mph", "m/s") 44.704 >>> convert_speed(100, "mph", "knot") 86.898 >>> convert_speed(100, "knot", "km/h") 185.2 >>> convert_speed(100, "knot", "m/s") 51.444 >>> convert_speed(100, "knot", "mph") 115.078 """ if unit_to not in speed_chart or unit_from not in speed_chart_inverse: raise ValueError( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Valid values are: {', '.join(speed_chart_inverse)}" ) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) if __name__ == "__main__": import doctest doctest.testmod()
""" Convert speed units https://en.wikipedia.org/wiki/Kilometres_per_hour https://en.wikipedia.org/wiki/Miles_per_hour https://en.wikipedia.org/wiki/Knot_(unit) https://en.wikipedia.org/wiki/Metre_per_second """ speed_chart: dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } speed_chart_inverse: dict[str, float] = { "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def convert_speed(speed: float, unit_from: str, unit_to: str) -> float: """ Convert speed from one unit to another using the speed_chart above. "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, >>> convert_speed(100, "km/h", "m/s") 27.778 >>> convert_speed(100, "km/h", "mph") 62.137 >>> convert_speed(100, "km/h", "knot") 53.996 >>> convert_speed(100, "m/s", "km/h") 360.0 >>> convert_speed(100, "m/s", "mph") 223.694 >>> convert_speed(100, "m/s", "knot") 194.384 >>> convert_speed(100, "mph", "km/h") 160.934 >>> convert_speed(100, "mph", "m/s") 44.704 >>> convert_speed(100, "mph", "knot") 86.898 >>> convert_speed(100, "knot", "km/h") 185.2 >>> convert_speed(100, "knot", "m/s") 51.444 >>> convert_speed(100, "knot", "mph") 115.078 """ if unit_to not in speed_chart or unit_from not in speed_chart_inverse: raise ValueError( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Valid values are: {', '.join(speed_chart_inverse)}" ) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ from __future__ import annotations from random import choice def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: list[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf """ from __future__ import annotations from random import choice def random_pivot(lst): """ Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the median-of-medians algorithm. """ return choice(lst) def kth_number(lst: list[int], k: int) -> int: """ Return the kth smallest number in lst. >>> kth_number([2, 1, 3, 4, 5], 3) 3 >>> kth_number([2, 1, 3, 4, 5], 1) 1 >>> kth_number([2, 1, 3, 4, 5], 5) 5 >>> kth_number([3, 2, 5, 6, 7, 8], 2) 3 >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4) 43 """ # pick a pivot and separate into list based on pivot. pivot = random_pivot(lst) # partition based on pivot # linear time small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(small) == k - 1: return pivot # pivot is in elements bigger than k elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) # pivot is in elements smaller than k else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# DarkCoder def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float: """ Find the sum of n terms in an arithmetic progression. >>> sum_of_series(1, 1, 10) 55.0 >>> sum_of_series(1, 10, 100) 49600.0 """ total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def main(): print(sum_of_series(1, 1, 10)) if __name__ == "__main__": import doctest doctest.testmod()
# DarkCoder def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float: """ Find the sum of n terms in an arithmetic progression. >>> sum_of_series(1, 1, 10) 55.0 >>> sum_of_series(1, 10, 100) 49600.0 """ total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def main(): print(sum_of_series(1, 1, 10)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage =========== Arguments: * ciphertext (str): the text to decode (encoded with the caesar cipher) Optional Arguments: * cipher_alphabet (list): the alphabet used for the cipher (each letter is a string separated by commas) * frequencies_dict (dict): a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal/float * case_sensitive (bool): a boolean value: True if the case matters during decryption, False if it doesn't Returns: * A tuple in the form of: ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher ) where... - most_likely_cipher is an integer representing the shift of the smallest chi-squared statistic (most likely key) - most_likely_cipher_chi_squared_value is a float representing the chi-squared statistic of the most likely shift - decoded_most_likely_cipher is a string with the decoded cipher (decoded by the most_likely_cipher key) The Chi-squared test ==================== The caesar cipher ----------------- The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: Plain text: hello Key: 1 Cipher text: ifmmp (each letter in hello has been shifted one to the right in the eng. alphabet) As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by brute-force is extremely easy even by hand. However one way to do that is the chi-squared test. The chi-squared test ------------------- Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters (usually expressed as a decimal representing the percentage likelihood). The most common letter in the english language is "e" with a frequency of 0.11162 or 11.162%. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way (every combination of the 26 possible combinations) 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter For example: In a message of 100 characters, e should appear around 11.162 times. 3. Then, to calculate the margin of error (the amount of times the letter SHOULD appear with the amount of times the letter DOES appear), we use the chi-squared test. The following formula is used: Let: - n be the number of times the letter actually appears - p be the predicted value of the number of times the letter should appear (see #2) - let v be the chi-squared test result (referred to here as chi-squared value/statistic) (n - p)^2 --------- = v p 4. Each chi squared value for each letter is then added up to the total. The total is the chi-squared statistic for that encryption key. 5. The encryption key with the lowest chi-squared value is the most likely to be the decoded answer. Further Reading ================ * http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared- statistic/ * https://en.wikipedia.org/wiki/Letter_frequency * https://en.wikipedia.org/wiki/Chi-squared_test * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt_caesar_with_chi_squared( ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... ) # doctest: +NORMALIZE_WHITESPACE (7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!') >>> decrypt_caesar_with_chi_squared('crybd cdbsxq') (10, 233.35343938980898, 'short string') >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True) (10, 233.35343938980898, 'Short String') >>> decrypt_caesar_with_chi_squared(12) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'lower' """ alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: # Custom frequencies dictionary frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() # Chi squared statistic values chi_squared_statistic_values: dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(alphabet_letters)): decrypted_with_shift = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter chi_squared_statistic = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.lower().count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) # Get all the data from the most likely cipher (key, decoded message) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage =========== Arguments: * ciphertext (str): the text to decode (encoded with the caesar cipher) Optional Arguments: * cipher_alphabet (list): the alphabet used for the cipher (each letter is a string separated by commas) * frequencies_dict (dict): a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal/float * case_sensitive (bool): a boolean value: True if the case matters during decryption, False if it doesn't Returns: * A tuple in the form of: ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher ) where... - most_likely_cipher is an integer representing the shift of the smallest chi-squared statistic (most likely key) - most_likely_cipher_chi_squared_value is a float representing the chi-squared statistic of the most likely shift - decoded_most_likely_cipher is a string with the decoded cipher (decoded by the most_likely_cipher key) The Chi-squared test ==================== The caesar cipher ----------------- The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: Plain text: hello Key: 1 Cipher text: ifmmp (each letter in hello has been shifted one to the right in the eng. alphabet) As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by brute-force is extremely easy even by hand. However one way to do that is the chi-squared test. The chi-squared test ------------------- Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters (usually expressed as a decimal representing the percentage likelihood). The most common letter in the english language is "e" with a frequency of 0.11162 or 11.162%. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way (every combination of the 26 possible combinations) 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter For example: In a message of 100 characters, e should appear around 11.162 times. 3. Then, to calculate the margin of error (the amount of times the letter SHOULD appear with the amount of times the letter DOES appear), we use the chi-squared test. The following formula is used: Let: - n be the number of times the letter actually appears - p be the predicted value of the number of times the letter should appear (see #2) - let v be the chi-squared test result (referred to here as chi-squared value/statistic) (n - p)^2 --------- = v p 4. Each chi squared value for each letter is then added up to the total. The total is the chi-squared statistic for that encryption key. 5. The encryption key with the lowest chi-squared value is the most likely to be the decoded answer. Further Reading ================ * http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared- statistic/ * https://en.wikipedia.org/wiki/Letter_frequency * https://en.wikipedia.org/wiki/Chi-squared_test * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt_caesar_with_chi_squared( ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... ) # doctest: +NORMALIZE_WHITESPACE (7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!') >>> decrypt_caesar_with_chi_squared('crybd cdbsxq') (10, 233.35343938980898, 'short string') >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True) (10, 233.35343938980898, 'Short String') >>> decrypt_caesar_with_chi_squared(12) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'lower' """ alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: # Custom frequencies dictionary frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() # Chi squared statistic values chi_squared_statistic_values: dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(alphabet_letters)): decrypted_with_shift = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter chi_squared_statistic = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.lower().count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) # Get all the data from the most likely cipher (key, decoded message) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Author: M. Yathurshan # Black Formatter: True """ Implementation of SHA256 Hash function in a Python class and provides utilities to find hash of string or hash of text from a file. Usage: python sha256.py --string "Hello World!!" python sha256.py --file "hello_world.txt" When run without any arguments, it prints the hash of the string "Hello World!! Welcome to Cryptography" References: https://qvault.io/cryptography/how-sha-2-works-step-by-step-sha-256/ https://en.wikipedia.org/wiki/SHA-2 """ import argparse import struct import unittest class SHA256: """ Class to contain the entire pipeline for SHA1 Hashing Algorithm >>> SHA256(b'Python').hash '18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db' >>> SHA256(b'hello world').hash 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9' """ def __init__(self, data: bytes) -> None: self.data = data # Initialize hash values self.hashes = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ] # Initialize round constants self.round_constants = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, ] self.preprocessed_data = self.preprocessing(self.data) self.final_hash() @staticmethod def preprocessing(data: bytes) -> bytes: padding = b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64)) big_endian_integer = struct.pack(">Q", (len(data) * 8)) return data + padding + big_endian_integer def final_hash(self) -> None: # Convert into blocks of 64 bytes self.blocks = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data), 64) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers words = list(struct.unpack(">16L", block)) # add 48 0-ed integers words += [0] * 48 a, b, c, d, e, f, g, h = self.hashes for index in range(0, 64): if index > 15: # modify the zero-ed indexes at the end of the array s0 = ( self.ror(words[index - 15], 7) ^ self.ror(words[index - 15], 18) ^ (words[index - 15] >> 3) ) s1 = ( self.ror(words[index - 2], 17) ^ self.ror(words[index - 2], 19) ^ (words[index - 2] >> 10) ) words[index] = ( words[index - 16] + s0 + words[index - 7] + s1 ) % 0x100000000 # Compression s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g) temp1 = ( h + s1 + ch + self.round_constants[index] + words[index] ) % 0x100000000 s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) maj = (a & b) ^ (a & c) ^ (b & c) temp2 = (s0 + maj) % 0x100000000 h, g, f, e, d, c, b, a = ( g, f, e, ((d + temp1) % 0x100000000), c, b, a, ((temp1 + temp2) % 0x100000000), ) mutated_hash_values = [a, b, c, d, e, f, g, h] # Modify final values self.hashes = [ ((element + mutated_hash_values[index]) % 0x100000000) for index, element in enumerate(self.hashes) ] self.hash = "".join([hex(value)[2:].zfill(8) for value in self.hashes]) def ror(self, value: int, rotations: int) -> int: """ Right rotate a given unsigned number by a certain amount of rotations """ return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations) class SHA256HashTest(unittest.TestCase): """ Test class for the SHA256 class. Inherits the TestCase class from unittest """ def test_match_hashes(self) -> None: import hashlib msg = bytes("Test String", "utf-8") self.assertEqual(SHA256(msg).hash, hashlib.sha256(msg).hexdigest()) def main() -> None: """ Provides option 'string' or 'file' to take input and prints the calculated SHA-256 hash """ # unittest.main() import doctest doctest.testmod() parser = argparse.ArgumentParser() parser.add_argument( "-s", "--string", dest="input_string", default="Hello World!! Welcome to Cryptography", help="Hash the string", ) parser.add_argument( "-f", "--file", dest="input_file", help="Hash contents of a file" ) args = parser.parse_args() input_string = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file, "rb") as f: hash_input = f.read() else: hash_input = bytes(input_string, "utf-8") print(SHA256(hash_input).hash) if __name__ == "__main__": main()
# Author: M. Yathurshan # Black Formatter: True """ Implementation of SHA256 Hash function in a Python class and provides utilities to find hash of string or hash of text from a file. Usage: python sha256.py --string "Hello World!!" python sha256.py --file "hello_world.txt" When run without any arguments, it prints the hash of the string "Hello World!! Welcome to Cryptography" References: https://qvault.io/cryptography/how-sha-2-works-step-by-step-sha-256/ https://en.wikipedia.org/wiki/SHA-2 """ import argparse import struct import unittest class SHA256: """ Class to contain the entire pipeline for SHA1 Hashing Algorithm >>> SHA256(b'Python').hash '18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db' >>> SHA256(b'hello world').hash 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9' """ def __init__(self, data: bytes) -> None: self.data = data # Initialize hash values self.hashes = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ] # Initialize round constants self.round_constants = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, ] self.preprocessed_data = self.preprocessing(self.data) self.final_hash() @staticmethod def preprocessing(data: bytes) -> bytes: padding = b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64)) big_endian_integer = struct.pack(">Q", (len(data) * 8)) return data + padding + big_endian_integer def final_hash(self) -> None: # Convert into blocks of 64 bytes self.blocks = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data), 64) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers words = list(struct.unpack(">16L", block)) # add 48 0-ed integers words += [0] * 48 a, b, c, d, e, f, g, h = self.hashes for index in range(0, 64): if index > 15: # modify the zero-ed indexes at the end of the array s0 = ( self.ror(words[index - 15], 7) ^ self.ror(words[index - 15], 18) ^ (words[index - 15] >> 3) ) s1 = ( self.ror(words[index - 2], 17) ^ self.ror(words[index - 2], 19) ^ (words[index - 2] >> 10) ) words[index] = ( words[index - 16] + s0 + words[index - 7] + s1 ) % 0x100000000 # Compression s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g) temp1 = ( h + s1 + ch + self.round_constants[index] + words[index] ) % 0x100000000 s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) maj = (a & b) ^ (a & c) ^ (b & c) temp2 = (s0 + maj) % 0x100000000 h, g, f, e, d, c, b, a = ( g, f, e, ((d + temp1) % 0x100000000), c, b, a, ((temp1 + temp2) % 0x100000000), ) mutated_hash_values = [a, b, c, d, e, f, g, h] # Modify final values self.hashes = [ ((element + mutated_hash_values[index]) % 0x100000000) for index, element in enumerate(self.hashes) ] self.hash = "".join([hex(value)[2:].zfill(8) for value in self.hashes]) def ror(self, value: int, rotations: int) -> int: """ Right rotate a given unsigned number by a certain amount of rotations """ return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations) class SHA256HashTest(unittest.TestCase): """ Test class for the SHA256 class. Inherits the TestCase class from unittest """ def test_match_hashes(self) -> None: import hashlib msg = bytes("Test String", "utf-8") self.assertEqual(SHA256(msg).hash, hashlib.sha256(msg).hexdigest()) def main() -> None: """ Provides option 'string' or 'file' to take input and prints the calculated SHA-256 hash """ # unittest.main() import doctest doctest.testmod() parser = argparse.ArgumentParser() parser.add_argument( "-s", "--string", dest="input_string", default="Hello World!! Welcome to Cryptography", help="Hash the string", ) parser.add_argument( "-f", "--file", dest="input_file", help="Hash contents of a file" ) args = parser.parse_args() input_string = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file, "rb") as f: hash_input = f.read() else: hash_input = bytes(input_string, "utf-8") print(SHA256(hash_input).hash) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The Reverse Polish Nation also known as Polish postfix notation or simply postfix notation. https://en.wikipedia.org/wiki/Reverse_Polish_notation Classic examples of simple stack implementations Valid operators are +, -, *, /. Each operand may be an integer or another expression. """ from __future__ import annotations from typing import Any def evaluate_postfix(postfix_notation: list) -> int: """ >>> evaluate_postfix(["2", "1", "+", "3", "*"]) 9 >>> evaluate_postfix(["4", "13", "5", "/", "+"]) 6 >>> evaluate_postfix([]) 0 """ if not postfix_notation: return 0 operations = {"+", "-", "*", "/"} stack: list[Any] = [] for token in postfix_notation: if token in operations: b, a = stack.pop(), stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1) else: stack.append(a // b) else: stack.append(int(token)) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
""" The Reverse Polish Nation also known as Polish postfix notation or simply postfix notation. https://en.wikipedia.org/wiki/Reverse_Polish_notation Classic examples of simple stack implementations Valid operators are +, -, *, /. Each operand may be an integer or another expression. """ from __future__ import annotations from typing import Any def evaluate_postfix(postfix_notation: list) -> int: """ >>> evaluate_postfix(["2", "1", "+", "3", "*"]) 9 >>> evaluate_postfix(["4", "13", "5", "/", "+"]) 6 >>> evaluate_postfix([]) 0 """ if not postfix_notation: return 0 operations = {"+", "-", "*", "/"} stack: list[Any] = [] for token in postfix_notation: if token in operations: b, a = stack.pop(), stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1) else: stack.append(a // b) else: stack.append(int(token)) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 Γ— 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 Γ— 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Calculate the nth Proth number Source: https://handwiki.org/wiki/Proth_number """ import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 >>> proth(6) 25 >>> proth(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> proth(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> proth(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError(f"Input value of [number={number}] must be > 0") elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
""" Calculate the nth Proth number Source: https://handwiki.org/wiki/Proth_number """ import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 >>> proth(6) 25 >>> proth(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> proth(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> proth(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError(f"Input value of [number={number}] must be > 0") elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 205: https://projecteuler.net/problem=205 Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. Peter and Colin roll their dice and compare totals: the highest total wins. The result is a draw if the totals are equal. What is the probability that Pyramidal Peter beats Cubic Colin? Give your answer rounded to seven decimal places in the form 0.abcdefg """ from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: """ Returns frequency distribution of total >>> total_frequency_distribution(sides_number=6, dice_number=1) [0, 1, 1, 1, 1, 1, 1] >>> total_frequency_distribution(sides_number=4, dice_number=2) [0, 0, 1, 2, 3, 4, 3, 2, 1] """ max_face_number = sides_number max_total = max_face_number * dice_number totals_frequencies = [0] * (max_total + 1) min_face_number = 1 faces_numbers = range(min_face_number, max_face_number + 1) for dice_numbers in product(faces_numbers, repeat=dice_number): total = sum(dice_numbers) totals_frequencies[total] += 1 return totals_frequencies def solution() -> float: """ Returns probability that Pyramidal Peter beats Cubic Colin rounded to seven decimal places in the form 0.abcdefg >>> solution() 0.5731441 """ peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 ) colin_totals_frequencies = total_frequency_distribution( sides_number=6, dice_number=6 ) peter_wins_count = 0 min_peter_total = 9 max_peter_total = 4 * 9 min_colin_total = 6 for peter_total in range(min_peter_total, max_peter_total + 1): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) total_games_number = (4**9) * (6**6) peter_win_probability = peter_wins_count / total_games_number rounded_peter_win_probability = round(peter_win_probability, ndigits=7) return rounded_peter_win_probability if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 205: https://projecteuler.net/problem=205 Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. Peter and Colin roll their dice and compare totals: the highest total wins. The result is a draw if the totals are equal. What is the probability that Pyramidal Peter beats Cubic Colin? Give your answer rounded to seven decimal places in the form 0.abcdefg """ from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: """ Returns frequency distribution of total >>> total_frequency_distribution(sides_number=6, dice_number=1) [0, 1, 1, 1, 1, 1, 1] >>> total_frequency_distribution(sides_number=4, dice_number=2) [0, 0, 1, 2, 3, 4, 3, 2, 1] """ max_face_number = sides_number max_total = max_face_number * dice_number totals_frequencies = [0] * (max_total + 1) min_face_number = 1 faces_numbers = range(min_face_number, max_face_number + 1) for dice_numbers in product(faces_numbers, repeat=dice_number): total = sum(dice_numbers) totals_frequencies[total] += 1 return totals_frequencies def solution() -> float: """ Returns probability that Pyramidal Peter beats Cubic Colin rounded to seven decimal places in the form 0.abcdefg >>> solution() 0.5731441 """ peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 ) colin_totals_frequencies = total_frequency_distribution( sides_number=6, dice_number=6 ) peter_wins_count = 0 min_peter_total = 9 max_peter_total = 4 * 9 min_colin_total = 6 for peter_total in range(min_peter_total, max_peter_total + 1): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) total_games_number = (4**9) * (6**6) peter_win_probability = peter_wins_count / total_games_number rounded_peter_win_probability = round(peter_win_probability, ndigits=7) return rounded_peter_win_probability if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Description The Koch snowflake is a fractal curve and one of the earliest fractals to have been described. The Koch snowflake can be built up iteratively, in a sequence of stages. The first stage is an equilateral triangle, and each successive stage is formed by adding outward bends to each side of the previous stage, making smaller equilateral triangles. This can be achieved through the following steps for each line: 1. divide the line segment into three segments of equal length. 2. draw an equilateral triangle that has the middle segment from step 1 as its base and points outward. 3. remove the line segment that is the base of the triangle from step 2. (description adapted from https://en.wikipedia.org/wiki/Koch_snowflake ) (for a more detailed explanation and an implementation in the Processing language, see https://natureofcode.com/book/chapter-8-fractals/ #84-the-koch-curve-and-the-arraylist-technique ) Requirements (pip): - matplotlib - numpy """ from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake VECTOR_1 = numpy.array([0, 0]) VECTOR_2 = numpy.array([0.5, 0.8660254]) VECTOR_3 = numpy.array([1, 0]) INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] # uncomment for simple Koch curve instead of Koch snowflake # INITIAL_VECTORS = [VECTOR_1, VECTOR_3] def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]: """ Go through the number of iterations determined by the argument "steps". Be careful with high values (above 5) since the time to calculate increases exponentially. >>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1) [array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \ 0.28867513]), array([0.66666667, 0. ]), array([1, 0])] """ vectors = initial_vectors for _ in range(steps): vectors = iteration_step(vectors) return vectors def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]: """ Loops through each pair of adjacent vectors. Each line between two adjacent vectors is divided into 4 segments by adding 3 additional vectors in-between the original two vectors. The vector in the middle is constructed through a 60 degree rotation so it is bent outwards. >>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])]) [array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \ 0.28867513]), array([0.66666667, 0. ]), array([1, 0])] """ new_vectors = [] for i, start_vector in enumerate(vectors[:-1]): end_vector = vectors[i + 1] new_vectors.append(start_vector) difference_vector = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60) ) new_vectors.append(start_vector + difference_vector * 2 / 3) new_vectors.append(vectors[-1]) return new_vectors def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray: """ Standard rotation of a 2D vector with a rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix ) >>> rotate(numpy.array([1, 0]), 60) array([0.5 , 0.8660254]) >>> rotate(numpy.array([1, 0]), 90) array([6.123234e-17, 1.000000e+00]) """ theta = numpy.radians(angle_in_degrees) c, s = numpy.cos(theta), numpy.sin(theta) rotation_matrix = numpy.array(((c, -s), (s, c))) return numpy.dot(rotation_matrix, vector) def plot(vectors: list[numpy.ndarray]) -> None: """ Utility function to plot the vectors using matplotlib.pyplot No doctest was implemented since this function does not have a return value """ # avoid stretched display of graph axes = plt.gca() axes.set_aspect("equal") # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() x_coordinates, y_coordinates = zip(*vectors) plt.plot(x_coordinates, y_coordinates) plt.show() if __name__ == "__main__": import doctest doctest.testmod() processed_vectors = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
""" Description The Koch snowflake is a fractal curve and one of the earliest fractals to have been described. The Koch snowflake can be built up iteratively, in a sequence of stages. The first stage is an equilateral triangle, and each successive stage is formed by adding outward bends to each side of the previous stage, making smaller equilateral triangles. This can be achieved through the following steps for each line: 1. divide the line segment into three segments of equal length. 2. draw an equilateral triangle that has the middle segment from step 1 as its base and points outward. 3. remove the line segment that is the base of the triangle from step 2. (description adapted from https://en.wikipedia.org/wiki/Koch_snowflake ) (for a more detailed explanation and an implementation in the Processing language, see https://natureofcode.com/book/chapter-8-fractals/ #84-the-koch-curve-and-the-arraylist-technique ) Requirements (pip): - matplotlib - numpy """ from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake VECTOR_1 = numpy.array([0, 0]) VECTOR_2 = numpy.array([0.5, 0.8660254]) VECTOR_3 = numpy.array([1, 0]) INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] # uncomment for simple Koch curve instead of Koch snowflake # INITIAL_VECTORS = [VECTOR_1, VECTOR_3] def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]: """ Go through the number of iterations determined by the argument "steps". Be careful with high values (above 5) since the time to calculate increases exponentially. >>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1) [array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \ 0.28867513]), array([0.66666667, 0. ]), array([1, 0])] """ vectors = initial_vectors for _ in range(steps): vectors = iteration_step(vectors) return vectors def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]: """ Loops through each pair of adjacent vectors. Each line between two adjacent vectors is divided into 4 segments by adding 3 additional vectors in-between the original two vectors. The vector in the middle is constructed through a 60 degree rotation so it is bent outwards. >>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])]) [array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \ 0.28867513]), array([0.66666667, 0. ]), array([1, 0])] """ new_vectors = [] for i, start_vector in enumerate(vectors[:-1]): end_vector = vectors[i + 1] new_vectors.append(start_vector) difference_vector = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60) ) new_vectors.append(start_vector + difference_vector * 2 / 3) new_vectors.append(vectors[-1]) return new_vectors def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray: """ Standard rotation of a 2D vector with a rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix ) >>> rotate(numpy.array([1, 0]), 60) array([0.5 , 0.8660254]) >>> rotate(numpy.array([1, 0]), 90) array([6.123234e-17, 1.000000e+00]) """ theta = numpy.radians(angle_in_degrees) c, s = numpy.cos(theta), numpy.sin(theta) rotation_matrix = numpy.array(((c, -s), (s, c))) return numpy.dot(rotation_matrix, vector) def plot(vectors: list[numpy.ndarray]) -> None: """ Utility function to plot the vectors using matplotlib.pyplot No doctest was implemented since this function does not have a return value """ # avoid stretched display of graph axes = plt.gca() axes.set_aspect("equal") # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() x_coordinates, y_coordinates = zip(*vectors) plt.plot(x_coordinates, y_coordinates) plt.show() if __name__ == "__main__": import doctest doctest.testmod() processed_vectors = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def solve_maze(maze: list[list[int]]) -> bool: """ This method solves the "rat in maze" problem. In this problem we have some n by n matrix, a start point and an end point. We want to go from the start to the end. In this matrix zeroes represent walls and ones paths we can use. Parameters : maze(2D matrix) : maze Returns: Return: True if the maze has a solution or False if it does not. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 1, 1, 1, 0] [0, 0, 0, 1, 0] [0, 0, 0, 1, 1] [0, 0, 0, 0, 1] True >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 1, 1, 1, 1] True >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) [1, 1, 1] [0, 0, 1] [0, 0, 1] True >>> maze = [[0, 1, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) No solution exists! False >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze) No solution exists! False """ size = len(maze) # We need to create solution object to save path. solutions = [[0 for _ in range(size)] for _ in range(size)] solved = run_maze(maze, 0, 0, solutions) if solved: print("\n".join(str(row) for row in solutions)) else: print("No solution exists!") return solved def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not (i < 0)) and (not (j < 0)) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not (solutions[i][j])) and (not (maze[i][j])) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations def solve_maze(maze: list[list[int]]) -> bool: """ This method solves the "rat in maze" problem. In this problem we have some n by n matrix, a start point and an end point. We want to go from the start to the end. In this matrix zeroes represent walls and ones paths we can use. Parameters : maze(2D matrix) : maze Returns: Return: True if the maze has a solution or False if it does not. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 1, 1, 1, 0] [0, 0, 0, 1, 0] [0, 0, 0, 1, 1] [0, 0, 0, 0, 1] True >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 1, 1, 1, 1] True >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) [1, 1, 1] [0, 0, 1] [0, 0, 1] True >>> maze = [[0, 1, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) No solution exists! False >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze) No solution exists! False """ size = len(maze) # We need to create solution object to save path. solutions = [[0 for _ in range(size)] for _ in range(size)] solved = run_maze(maze, 0, 0, solutions) if solved: print("\n".join(str(row) for row in solutions)) else: print("No solution exists!") return solved def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not (i < 0)) and (not (j < 0)) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not (solutions[i][j])) and (not (maze[i][j])) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from sys import maxsize def max_sub_array_sum(a: list, size: int = 0): """ >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]) -3 """ size = size or len(a) max_so_far = -maxsize - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far if __name__ == "__main__": a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7] print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a))))
from sys import maxsize def max_sub_array_sum(a: list, size: int = 0): """ >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]) -3 """ size = size or len(a) max_so_far = -maxsize - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far if __name__ == "__main__": a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7] print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a))))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Rail_fence_cipher """ def encrypt(input_string: str, key: int) -> str: """ Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) 'HWe olordll' >>> encrypt("This is a message", 0) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> encrypt(b"This is a byte string", 5) Traceback (most recent call last): ... TypeError: sequence item 0: expected str instance, int found """ temp_grid: list[list[str]] = [[] for _ in range(key)] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1 or len(input_string) <= key: return input_string for position, character in enumerate(input_string): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append(character) grid = ["".join(row) for row in temp_grid] output_string = "".join(grid) return output_string def decrypt(input_string: str, key: int) -> str: """ Generates a template based on the key and fills it in with the characters of the input string and then reading it in a zigzag formation. >>> decrypt("HWe olordll", 4) 'Hello World' >>> decrypt("This is a message", -10) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> decrypt("My key is very big", 100) 'My key is very big' """ grid = [] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1: return input_string temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append("*") counter = 0 for row in temp_grid: # fills in the characters splice = input_string[counter : counter + len(row)] grid.append(list(splice)) counter += len(row) output_string = "" # reads as zigzag for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0) return output_string def bruteforce(input_string: str) -> dict[int, str]: """Uses decrypt function by guessing every key >>> bruteforce("HWe olordll")[4] 'Hello World' """ results = {} for key_guess in range(1, len(input_string)): # tries every key results[key_guess] = decrypt(input_string, key_guess) return results if __name__ == "__main__": import doctest doctest.testmod()
""" https://en.wikipedia.org/wiki/Rail_fence_cipher """ def encrypt(input_string: str, key: int) -> str: """ Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) 'HWe olordll' >>> encrypt("This is a message", 0) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> encrypt(b"This is a byte string", 5) Traceback (most recent call last): ... TypeError: sequence item 0: expected str instance, int found """ temp_grid: list[list[str]] = [[] for _ in range(key)] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1 or len(input_string) <= key: return input_string for position, character in enumerate(input_string): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append(character) grid = ["".join(row) for row in temp_grid] output_string = "".join(grid) return output_string def decrypt(input_string: str, key: int) -> str: """ Generates a template based on the key and fills it in with the characters of the input string and then reading it in a zigzag formation. >>> decrypt("HWe olordll", 4) 'Hello World' >>> decrypt("This is a message", -10) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> decrypt("My key is very big", 100) 'My key is very big' """ grid = [] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1: return input_string temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append("*") counter = 0 for row in temp_grid: # fills in the characters splice = input_string[counter : counter + len(row)] grid.append(list(splice)) counter += len(row) output_string = "" # reads as zigzag for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0) return output_string def bruteforce(input_string: str) -> dict[int, str]: """Uses decrypt function by guessing every key >>> bruteforce("HWe olordll")[4] 'Hello World' """ results = {} for key_guess in range(1, len(input_string)): # tries every key results[key_guess] = decrypt(input_string, key_guess) return results if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 78 Url: https://projecteuler.net/problem=78 Statement: Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7. OOOOO OOOO O OOO OO OOO O O OO OO O OO O O O O O O O O Find the least value of n for which p(n) is divisible by one million. """ import itertools def solution(number: int = 1000000) -> int: """ >>> solution(1) 1 >>> solution(9) 14 >>> solution() 55374 """ partitions = [1] for i in itertools.count(len(partitions)): item = 0 for j in itertools.count(1): sign = -1 if j % 2 == 0 else +1 index = (j * j * 3 - j) // 2 if index > i: break item += partitions[i - index] * sign item %= number index += j if index > i: break item += partitions[i - index] * sign item %= number if item == 0: return i partitions.append(item) return 0 if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
""" Problem 78 Url: https://projecteuler.net/problem=78 Statement: Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7. OOOOO OOOO O OOO OO OOO O O OO OO O OO O O O O O O O O Find the least value of n for which p(n) is divisible by one million. """ import itertools def solution(number: int = 1000000) -> int: """ >>> solution(1) 1 >>> solution(9) 14 >>> solution() 55374 """ partitions = [1] for i in itertools.count(len(partitions)): item = 0 for j in itertools.count(1): sign = -1 if j % 2 == 0 else +1 index = (j * j * 3 - j) // 2 if index > i: break item += partitions[i - index] * sign item %= number index += j if index > i: break item += partitions[i - index] * sign item %= number if item == 0: return i partitions.append(item) return 0 if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Convert between different units of temperature """ def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
""" Convert between different units of temperature """ def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is an implementation of Pigeon Hole Sort. For doctests run following command: python3 -m doctest -v pigeon_sort.py or python -m doctest -v pigeon_sort.py For manual testing run: python pigeon_sort.py """ from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: """ Implementation of pigeon hole sort algorithm :param array: Collection of comparable items :return: Collection sorted in ascending order >>> pigeon_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pigeon_sort([]) [] >>> pigeon_sort([-2, -5, -45]) [-45, -5, -2] """ if len(array) == 0: return array _min, _max = min(array), max(array) # Compute the variables holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: index = i - _min holes[index] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. index = 0 for i in range(holes_range): while holes_repeat[i] > 0: array[index] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n") unsorted = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
""" This is an implementation of Pigeon Hole Sort. For doctests run following command: python3 -m doctest -v pigeon_sort.py or python -m doctest -v pigeon_sort.py For manual testing run: python pigeon_sort.py """ from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: """ Implementation of pigeon hole sort algorithm :param array: Collection of comparable items :return: Collection sorted in ascending order >>> pigeon_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pigeon_sort([]) [] >>> pigeon_sort([-2, -5, -45]) [-45, -5, -2] """ if len(array) == 0: return array _min, _max = min(array), max(array) # Compute the variables holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: index = i - _min holes[index] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. index = 0 for i in range(holes_range): while holes_repeat[i] > 0: array[index] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n") unsorted = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Get the site emails from URL.""" from __future__ import annotations __author__ = "Muhammad Umer Farooq" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Muhammad Umer Farooq" __email__ = "[email protected]" __status__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class Parser(HTMLParser): def __init__(self, domain: str) -> None: super().__init__() self.urls: list[str] = [] self.domain = domain def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: """ This function parse html to take takes url from tags """ # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: url = parse.urljoin(self.domain, value) self.urls.append(url) # Get main domain name (example.com) def get_domain_name(url: str) -> str: """ This function get the main domain name >>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'c.d' >>> get_domain_name("Not a URL!") '' """ return ".".join(get_sub_domain_name(url).split(".")[-2:]) # Get sub domain name (sub.example.com) def get_sub_domain_name(url: str) -> str: """ >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'a.b.c.d' >>> get_sub_domain_name("Not a URL!") '' """ return parse.urlparse(url).netloc def emails_from_url(url: str = "https://github.com") -> list[str]: """ This function takes url and return all valid urls """ # Get the base domain from the url domain = get_domain_name(url) # Initialize the parser parser = Parser(domain) try: # Open URL r = requests.get(url) # pass the raw HTML to the parser to get links parser.feed(r.text) # Get links and loop through valid_emails = set() for link in parser.urls: # open URL. # read = requests.get(link) try: read = requests.get(link) # Get the valid email. emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text) # If not in list then append it. for email in emails: valid_emails.add(email) except ValueError: pass except ValueError: raise SystemExit(1) # Finally return a sorted list of email addresses with no duplicates. return sorted(valid_emails) if __name__ == "__main__": emails = emails_from_url("https://github.com") print(f"{len(emails)} emails found:") print("\n".join(sorted(emails)))
"""Get the site emails from URL.""" from __future__ import annotations __author__ = "Muhammad Umer Farooq" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Muhammad Umer Farooq" __email__ = "[email protected]" __status__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class Parser(HTMLParser): def __init__(self, domain: str) -> None: super().__init__() self.urls: list[str] = [] self.domain = domain def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: """ This function parse html to take takes url from tags """ # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: url = parse.urljoin(self.domain, value) self.urls.append(url) # Get main domain name (example.com) def get_domain_name(url: str) -> str: """ This function get the main domain name >>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'c.d' >>> get_domain_name("Not a URL!") '' """ return ".".join(get_sub_domain_name(url).split(".")[-2:]) # Get sub domain name (sub.example.com) def get_sub_domain_name(url: str) -> str: """ >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'a.b.c.d' >>> get_sub_domain_name("Not a URL!") '' """ return parse.urlparse(url).netloc def emails_from_url(url: str = "https://github.com") -> list[str]: """ This function takes url and return all valid urls """ # Get the base domain from the url domain = get_domain_name(url) # Initialize the parser parser = Parser(domain) try: # Open URL r = requests.get(url) # pass the raw HTML to the parser to get links parser.feed(r.text) # Get links and loop through valid_emails = set() for link in parser.urls: # open URL. # read = requests.get(link) try: read = requests.get(link) # Get the valid email. emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text) # If not in list then append it. for email in emails: valid_emails.add(email) except ValueError: pass except ValueError: raise SystemExit(1) # Finally return a sorted list of email addresses with no duplicates. return sorted(valid_emails) if __name__ == "__main__": emails = emails_from_url("https://github.com") print(f"{len(emails)} emails found:") print("\n".join(sorted(emails)))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Breadth-first search shortest path implementations. doctest: python -m doctest -v bfs_shortest_path.py Manual test: python bfs_shortest_path.py """ demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def bfs_shortest_path(graph: dict, start, goal) -> list[str]: """Find shortest path between `start` and `goal` nodes. Args: graph (dict): node/list of neighboring nodes key/value pairs. start: start node. goal: target node. Returns: Shortest path between `start` and `goal` nodes as a string of nodes. 'Not found' string if no path found. Example: >>> bfs_shortest_path(demo_graph, "G", "D") ['G', 'C', 'A', 'B', 'D'] >>> bfs_shortest_path(demo_graph, "G", "G") ['G'] >>> bfs_shortest_path(demo_graph, "G", "Unknown") [] """ # keep track of explored nodes explored = set() # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.pop(0) # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(node) # in case there's no path between the 2 nodes return [] def bfs_shortest_path_distance(graph: dict, start, target) -> int: """Find shortest path distance between `start` and `target` nodes. Args: graph: node/list of neighboring nodes key/value pairs. start: node to start search from. target: node to search for. Returns: Number of edges in shortest path between `start` and `target` nodes. -1 if no path exists. Example: >>> bfs_shortest_path_distance(demo_graph, "G", "D") 4 >>> bfs_shortest_path_distance(demo_graph, "A", "A") 0 >>> bfs_shortest_path_distance(demo_graph, "A", "Unknown") -1 """ if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 queue = [start] visited = set(start) # Keep tab on distances from `start` node. dist = {start: 0, target: -1} while queue: node = queue.pop(0) if node == target: dist[target] = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) dist[adjacent] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
"""Breadth-first search shortest path implementations. doctest: python -m doctest -v bfs_shortest_path.py Manual test: python bfs_shortest_path.py """ demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def bfs_shortest_path(graph: dict, start, goal) -> list[str]: """Find shortest path between `start` and `goal` nodes. Args: graph (dict): node/list of neighboring nodes key/value pairs. start: start node. goal: target node. Returns: Shortest path between `start` and `goal` nodes as a string of nodes. 'Not found' string if no path found. Example: >>> bfs_shortest_path(demo_graph, "G", "D") ['G', 'C', 'A', 'B', 'D'] >>> bfs_shortest_path(demo_graph, "G", "G") ['G'] >>> bfs_shortest_path(demo_graph, "G", "Unknown") [] """ # keep track of explored nodes explored = set() # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.pop(0) # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(node) # in case there's no path between the 2 nodes return [] def bfs_shortest_path_distance(graph: dict, start, target) -> int: """Find shortest path distance between `start` and `target` nodes. Args: graph: node/list of neighboring nodes key/value pairs. start: node to start search from. target: node to search for. Returns: Number of edges in shortest path between `start` and `target` nodes. -1 if no path exists. Example: >>> bfs_shortest_path_distance(demo_graph, "G", "D") 4 >>> bfs_shortest_path_distance(demo_graph, "A", "A") 0 >>> bfs_shortest_path_distance(demo_graph, "A", "Unknown") -1 """ if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 queue = [start] visited = set(start) # Keep tab on distances from `start` node. dist = {start: 0, target: -1} while queue: node = queue.pop(0) if node == target: dist[target] = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) dist[adjacent] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 81: https://projecteuler.net/problem=81 In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427. [131] 673 234 103 18 [201] [96] [342] 965 150 630 803 [746] [422] 111 537 699 497 [121] 956 805 732 524 [37] [331] Find the minimal path sum from the top left to the bottom right by only moving right and down in matrix.txt (https://projecteuler.net/project/resources/p081_matrix.txt), a 31K text file containing an 80 by 80 matrix. """ import os def solution(filename: str = "matrix.txt") -> int: """ Returns the minimal path sum from the top left to the bottom right of the matrix. >>> solution() 427337 """ with open(os.path.join(os.path.dirname(__file__), filename)) as in_file: data = in_file.read() grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()] dp = [[0 for cell in row] for row in grid] n = len(grid[0]) dp = [[0 for i in range(n)] for j in range(n)] dp[0][0] = grid[0][0] for i in range(1, n): dp[0][i] = grid[0][i] + dp[0][i - 1] for i in range(1, n): dp[i][0] = grid[i][0] + dp[i - 1][0] for i in range(1, n): for j in range(1, n): dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) return dp[-1][-1] if __name__ == "__main__": print(f"{solution() = }")
""" Problem 81: https://projecteuler.net/problem=81 In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427. [131] 673 234 103 18 [201] [96] [342] 965 150 630 803 [746] [422] 111 537 699 497 [121] 956 805 732 524 [37] [331] Find the minimal path sum from the top left to the bottom right by only moving right and down in matrix.txt (https://projecteuler.net/project/resources/p081_matrix.txt), a 31K text file containing an 80 by 80 matrix. """ import os def solution(filename: str = "matrix.txt") -> int: """ Returns the minimal path sum from the top left to the bottom right of the matrix. >>> solution() 427337 """ with open(os.path.join(os.path.dirname(__file__), filename)) as in_file: data = in_file.read() grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()] dp = [[0 for cell in row] for row in grid] n = len(grid[0]) dp = [[0 for i in range(n)] for j in range(n)] dp[0][0] = grid[0][0] for i in range(1, n): dp[0][i] = grid[0][i] + dp[0][i - 1] for i in range(1, n): dp[i][0] = grid[i][0] + dp[i - 1][0] for i in range(1, n): for j in range(1, n): dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) return dp[-1][-1] if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import random import sys LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}") def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.") def encrypt_message(key: str, message: str) -> str: """ >>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') 'Ilcrism Olcvs' """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: """ >>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') 'Harshil Darji' """ return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()
import random import sys LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}") def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.") def encrypt_message(key: str, message: str) -> str: """ >>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') 'Ilcrism Olcvs' """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: """ >>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') 'Harshil Darji' """ return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Author: JoΓ£o Gustavo A. Amorim & Gabriel Kunz # Author email: [email protected] and [email protected] # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1": if x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(0, size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(0, size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
# Author: JoΓ£o Gustavo A. Amorim & Gabriel Kunz # Author email: [email protected] and [email protected] # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1": if x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(0, size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(0, size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Totient maximum Problem 69: https://projecteuler.net/problem=69 Euler's Totient function, Ο†(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, Ο†(9)=6. n Relatively Prime Ο†(n) n/Ο†(n) 2 1 1 2 3 1,2 2 1.5 4 1,3 2 2 5 1,2,3,4 4 1.25 6 1,5 2 3 7 1,2,3,4,5,6 6 1.1666... 8 1,3,5,7 4 2 9 1,2,4,5,7,8 6 1.5 10 1,3,7,9 4 2.5 It can be seen that n=6 produces a maximum n/Ο†(n) for n ≀ 10. Find the value of n ≀ 1,000,000 for which n/Ο†(n) is a maximum. """ def solution(n: int = 10**6) -> int: """ Returns solution to problem. Algorithm: 1. Precompute Ο†(k) for all natural k, k <= n using product formula (wikilink below) https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula 2. Find k/Ο†(k) for all k ≀ n and return the k that attains maximum >>> solution(10) 6 >>> solution(100) 30 >>> solution(9973) 2310 """ if n <= 0: raise ValueError("Please enter an integer greater than 0") phi = list(range(n + 1)) for number in range(2, n + 1): if phi[number] == number: phi[number] -= 1 for multiple in range(number * 2, n + 1, number): phi[multiple] = (phi[multiple] // number) * (number - 1) answer = 1 for number in range(1, n + 1): if (answer / phi[answer]) < (number / phi[number]): answer = number return answer if __name__ == "__main__": print(solution())
""" Totient maximum Problem 69: https://projecteuler.net/problem=69 Euler's Totient function, Ο†(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, Ο†(9)=6. n Relatively Prime Ο†(n) n/Ο†(n) 2 1 1 2 3 1,2 2 1.5 4 1,3 2 2 5 1,2,3,4 4 1.25 6 1,5 2 3 7 1,2,3,4,5,6 6 1.1666... 8 1,3,5,7 4 2 9 1,2,4,5,7,8 6 1.5 10 1,3,7,9 4 2.5 It can be seen that n=6 produces a maximum n/Ο†(n) for n ≀ 10. Find the value of n ≀ 1,000,000 for which n/Ο†(n) is a maximum. """ def solution(n: int = 10**6) -> int: """ Returns solution to problem. Algorithm: 1. Precompute Ο†(k) for all natural k, k <= n using product formula (wikilink below) https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula 2. Find k/Ο†(k) for all k ≀ n and return the k that attains maximum >>> solution(10) 6 >>> solution(100) 30 >>> solution(9973) 2310 """ if n <= 0: raise ValueError("Please enter an integer greater than 0") phi = list(range(n + 1)) for number in range(2, n + 1): if phi[number] == number: phi[number] -= 1 for multiple in range(number * 2, n + 1, number): phi[multiple] = (phi[multiple] // number) * (number - 1) answer = 1 for number in range(1, n + 1): if (answer / phi[answer]) < (number / phi[number]): answer = number return answer if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph if __name__ == "__main__": n, m = (int(i) for i in _input("Number of nodes and edges: ")) graph_choice = int( _input( "Press 1 or 2 or 3 \n" "1. Unweighted directed \n" "2. Unweighted undirected \n" "3. Weighted undirected \n" )[0] ) g = { 1: initialize_unweighted_directed_graph, 2: initialize_unweighted_undirected_graph, 3: initialize_weighted_undirected_graph, }[graph_choice](n, m) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(g, s): vis, _s = {s}, [s] print(s) while _s: flag = 0 for i in g[_s[-1]]: if i not in vis: _s.append(i) vis.add(i) flag = 1 print(i) break if not flag: _s.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traversal Stack -------------------------------------------------------------------------------- """ def bfs(g, s): vis, q = {s}, deque([s]) print(s) while q: u = q.popleft() for v in g[u]: if v not in vis: vis.add(v) q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known: if dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ def topo(g, ind=None, q=None): if q is None: q = [1] if ind is None: ind = [0] * (len(g) + 1) # SInce oth Index is ignored for u in g: for v in g[u]: ind[v] += 1 q = deque() for i in g: if ind[i] == 0: q.append(i) if len(q) == 0: return v = q.popleft() print(v) for w in g[v]: ind[w] -= 1 if ind[w] == 0: q.append(w) topo(g, ind, q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for _ in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(a_and_n): (a, n) = a_and_n dist = list(a) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known: if v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) edges = [] for _ in range(m): edges.append(map(int, input().split(" "))) return edges, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(e_and_n): # Sort edges on the basis of distance (e, n) = e_and_n e.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = e.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph if __name__ == "__main__": n, m = (int(i) for i in _input("Number of nodes and edges: ")) graph_choice = int( _input( "Press 1 or 2 or 3 \n" "1. Unweighted directed \n" "2. Unweighted undirected \n" "3. Weighted undirected \n" )[0] ) g = { 1: initialize_unweighted_directed_graph, 2: initialize_unweighted_undirected_graph, 3: initialize_weighted_undirected_graph, }[graph_choice](n, m) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(g, s): vis, _s = {s}, [s] print(s) while _s: flag = 0 for i in g[_s[-1]]: if i not in vis: _s.append(i) vis.add(i) flag = 1 print(i) break if not flag: _s.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traversal Stack -------------------------------------------------------------------------------- """ def bfs(g, s): vis, q = {s}, deque([s]) print(s) while q: u = q.popleft() for v in g[u]: if v not in vis: vis.add(v) q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known: if dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ def topo(g, ind=None, q=None): if q is None: q = [1] if ind is None: ind = [0] * (len(g) + 1) # SInce oth Index is ignored for u in g: for v in g[u]: ind[v] += 1 q = deque() for i in g: if ind[i] == 0: q.append(i) if len(q) == 0: return v = q.popleft() print(v) for w in g[v]: ind[w] -= 1 if ind[w] == 0: q.append(w) topo(g, ind, q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for _ in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(a_and_n): (a, n) = a_and_n dist = list(a) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known: if v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) edges = [] for _ in range(m): edges.append(map(int, input().split(" "))) return edges, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(e_and_n): # Sort edges on the basis of distance (e, n) = e_and_n e.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = e.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Title : Finding the value of either Gravitational Force, one of the masses or distance provided that the other three parameters are given. Description : Newton's Law of Universal Gravitation explains the presence of force of attraction between bodies having a definite mass situated at a distance. It is usually stated as that, every particle attracts every other particle in the universe with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centers. The publication of the theory has become known as the "first great unification", as it marked the unification of the previously described phenomena of gravity on Earth with known astronomical behaviors. The equation for the universal gravitation is as follows: F = (G * mass_1 * mass_2) / (distance)^2 Source : - https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation - Newton (1687) "Philosophiæ Naturalis Principia Mathematica" """ from __future__ import annotations # Define the Gravitational Constant G and the function GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: """ Input Parameters ---------------- force : magnitude in Newtons mass_1 : mass in Kilograms mass_2 : mass in Kilograms distance : distance in Meters Returns ------- result : dict name, value pair of the parameter having Zero as it's value Returns the value of one of the parameters specified as 0, provided the values of other parameters are given. >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20) {'force': 8.342875e-12} >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048) {'mass_1': 1.385816317292268e+19} >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: Mass can not be negative >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374) Traceback (most recent call last): ... ValueError: Gravitational force can not be negative """ product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
""" Title : Finding the value of either Gravitational Force, one of the masses or distance provided that the other three parameters are given. Description : Newton's Law of Universal Gravitation explains the presence of force of attraction between bodies having a definite mass situated at a distance. It is usually stated as that, every particle attracts every other particle in the universe with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centers. The publication of the theory has become known as the "first great unification", as it marked the unification of the previously described phenomena of gravity on Earth with known astronomical behaviors. The equation for the universal gravitation is as follows: F = (G * mass_1 * mass_2) / (distance)^2 Source : - https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation - Newton (1687) "Philosophiæ Naturalis Principia Mathematica" """ from __future__ import annotations # Define the Gravitational Constant G and the function GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: """ Input Parameters ---------------- force : magnitude in Newtons mass_1 : mass in Kilograms mass_2 : mass in Kilograms distance : distance in Meters Returns ------- result : dict name, value pair of the parameter having Zero as it's value Returns the value of one of the parameters specified as 0, provided the values of other parameters are given. >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20) {'force': 8.342875e-12} >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048) {'mass_1': 1.385816317292268e+19} >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: Mass can not be negative >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374) Traceback (most recent call last): ... ValueError: Gravitational force can not be negative """ product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 Γ— 9 Γ— 8 Γ— 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = """73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450""" def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 Γ— 9 Γ— 8 Γ— 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = """73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450""" def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") str_n = str(n) sorted_str_n = "".join(sorted(str_n)) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") str_n = str(n) sorted_str_n = "".join(sorted(str_n)) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def kmp(pattern: str, text: str) -> bool: """ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern and the text. 2) Step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary """ # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False def get_failure_array(pattern: str) -> list[int]: """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - 1] continue j += 1 failure.append(i) return failure if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert kmp(pattern, text1) and not kmp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert kmp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
from __future__ import annotations def kmp(pattern: str, text: str) -> bool: """ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern and the text. 2) Step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary """ # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False def get_failure_array(pattern: str) -> list[int]: """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - 1] continue j += 1 failure.append(i) return failure if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert kmp(pattern, text1) and not kmp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert kmp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Convert a Decimal Number to an Octal Number.""" import math # Modified from: # https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js def decimal_to_octal(num: int) -> str: """Convert a Decimal Number to an Octal Number. >>> all(decimal_to_octal(i) == oct(i) for i ... in (0, 2, 8, 64, 65, 216, 255, 256, 512)) True """ octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.floor(math.pow(10, counter))) counter += 1 num = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"0o{int(octal)}" def main() -> None: """Print octal equivalents of decimal numbers.""" print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") print(decimal_to_octal(8)) # = 10 print("\n65 in octal is:") print(decimal_to_octal(65)) # = 101 print("\n216 in octal is:") print(decimal_to_octal(216)) # = 330 print("\n512 in octal is:") print(decimal_to_octal(512)) # = 1000 print("\n") if __name__ == "__main__": main()
"""Convert a Decimal Number to an Octal Number.""" import math # Modified from: # https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js def decimal_to_octal(num: int) -> str: """Convert a Decimal Number to an Octal Number. >>> all(decimal_to_octal(i) == oct(i) for i ... in (0, 2, 8, 64, 65, 216, 255, 256, 512)) True """ octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.floor(math.pow(10, counter))) counter += 1 num = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"0o{int(octal)}" def main() -> None: """Print octal equivalents of decimal numbers.""" print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") print(decimal_to_octal(8)) # = 10 print("\n65 in octal is:") print(decimal_to_octal(65)) # = 101 print("\n216 in octal is:") print(decimal_to_octal(216)) # = 330 print("\n512 in octal is:") print(decimal_to_octal(512)) # = 1000 print("\n") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# An OOP approach to representing and manipulating matrices from __future__ import annotations class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> print(matrix.rows) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> print(matrix.columns()) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> print(matrix.inverse()) Traceback (most recent call last): ... TypeError: Only matrices with a non-zero determinant have an inverse Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows: list[list[int]]): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self) -> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self) -> int: return len(self.rows) @property def num_columns(self) -> int: return len(self.rows[0]) @property def order(self) -> tuple[int, int]: return (self.num_rows, self.num_columns) @property def is_square(self) -> bool: return self.order[0] == self.order[1] def identity(self) -> Matrix: values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self) -> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0]) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self) -> bool: return bool(self.determinant()) def get_minor(self, row: int, column: int) -> int: values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row: int, column: int) -> int: if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self) -> Matrix: return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self) -> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self) -> Matrix: values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self) -> Matrix: determinant = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse") return self.adjugate() * (1 / determinant) def __repr__(self) -> str: return str(self.rows) def __str__(self) -> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0])) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row: list[int], position: int | None = None) -> None: type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column: list[int], position: int | None = None) -> None: type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return NotImplemented return self.rows == other.rows def __ne__(self, other: object) -> bool: return not self == other def __neg__(self) -> Matrix: return self * -1 def __add__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other: Matrix | int | float) -> Matrix: if isinstance(other, (int, float)): return Matrix( [[int(element * other) for element in row] for row in self.rows] ) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other: int) -> Matrix: if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable: return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for _ in range(other - 1): result *= self return result @classmethod def dot_product(cls, row: list[int], column: list[int]) -> int: return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
# An OOP approach to representing and manipulating matrices from __future__ import annotations class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> print(matrix.rows) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> print(matrix.columns()) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> print(matrix.inverse()) Traceback (most recent call last): ... TypeError: Only matrices with a non-zero determinant have an inverse Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows: list[list[int]]): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self) -> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self) -> int: return len(self.rows) @property def num_columns(self) -> int: return len(self.rows[0]) @property def order(self) -> tuple[int, int]: return (self.num_rows, self.num_columns) @property def is_square(self) -> bool: return self.order[0] == self.order[1] def identity(self) -> Matrix: values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self) -> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0]) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self) -> bool: return bool(self.determinant()) def get_minor(self, row: int, column: int) -> int: values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row: int, column: int) -> int: if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self) -> Matrix: return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self) -> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self) -> Matrix: values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self) -> Matrix: determinant = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse") return self.adjugate() * (1 / determinant) def __repr__(self) -> str: return str(self.rows) def __str__(self) -> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0])) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row: list[int], position: int | None = None) -> None: type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column: list[int], position: int | None = None) -> None: type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return NotImplemented return self.rows == other.rows def __ne__(self, other: object) -> bool: return not self == other def __neg__(self) -> Matrix: return self * -1 def __add__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other: Matrix | int | float) -> Matrix: if isinstance(other, (int, float)): return Matrix( [[int(element * other) for element in row] for row in self.rows] ) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other: int) -> Matrix: if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable: return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for _ in range(other - 1): result *= self return result @classmethod def dot_product(cls, row: list[int], column: list[int]) -> int: return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar T = TypeVar("T") class GraphAdjacencyList(Generic[T]): """ Adjacency List type Graph Data Structure that accounts for directed and undirected Graphs. Initialize graph object indicating whether it's directed or undirected. Directed graph example: >>> d_graph = GraphAdjacencyList() >>> d_graph {} >>> d_graph.add_edge(0, 1) {0: [1], 1: []} >>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []} >>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(d_graph) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(repr(d_graph)) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} Undirected graph example: >>> u_graph = GraphAdjacencyList(directed=False) >>> u_graph.add_edge(0, 1) {0: [1], 1: [0]} >>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]} >>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]} >>> u_graph.add_edge(4, 5) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(u_graph) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(repr(u_graph)) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> char_graph = GraphAdjacencyList(directed=False) >>> char_graph.add_edge('a', 'b') {'a': ['b'], 'b': ['a']} >>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f') {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} >>> print(char_graph) {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} """ def __init__(self, directed: bool = True) -> None: """ Parameters: directed: (bool) Indicates if graph is directed or undirected. Default is True. """ self.adj_list: dict[T, list[T]] = {} # dictionary of lists self.directed = directed def add_edge( self, source_vertex: T, destination_vertex: T ) -> GraphAdjacencyList[T]: """ Connects vertices together. Creates and Edge from source vertex to destination vertex. Vertices will be created if not found in graph """ if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex].append(source_vertex) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(source_vertex) self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [] return self def __repr__(self) -> str: return pformat(self.adj_list)
#!/usr/bin/env python3 # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar T = TypeVar("T") class GraphAdjacencyList(Generic[T]): """ Adjacency List type Graph Data Structure that accounts for directed and undirected Graphs. Initialize graph object indicating whether it's directed or undirected. Directed graph example: >>> d_graph = GraphAdjacencyList() >>> d_graph {} >>> d_graph.add_edge(0, 1) {0: [1], 1: []} >>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []} >>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(d_graph) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} >>> print(repr(d_graph)) {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} Undirected graph example: >>> u_graph = GraphAdjacencyList(directed=False) >>> u_graph.add_edge(0, 1) {0: [1], 1: [0]} >>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) {0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]} >>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]} >>> u_graph.add_edge(4, 5) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(u_graph) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> print(repr(u_graph)) {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1, 5], 5: [1, 4], 6: [2], 7: [2]} >>> char_graph = GraphAdjacencyList(directed=False) >>> char_graph.add_edge('a', 'b') {'a': ['b'], 'b': ['a']} >>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f') {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} >>> print(char_graph) {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} """ def __init__(self, directed: bool = True) -> None: """ Parameters: directed: (bool) Indicates if graph is directed or undirected. Default is True. """ self.adj_list: dict[T, list[T]] = {} # dictionary of lists self.directed = directed def add_edge( self, source_vertex: T, destination_vertex: T ) -> GraphAdjacencyList[T]: """ Connects vertices together. Creates and Edge from source vertex to destination vertex. Vertices will be created if not found in graph """ if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex].append(source_vertex) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(source_vertex) self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [] return self def __repr__(self) -> str: return pformat(self.adj_list)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The algorithm finds the pattern in given text using following rule. The bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pattern. If the mismatched character does not occur to the left in Pattern, a shift is proposed that moves the entirety of Pattern past the point of mismatch in the text. If there no mismatch then the pattern matches with text block. Time Complexity : O(n/m) n=length of main string m=length of pattern string """ from __future__ import annotations class BoyerMooreSearch: def __init__(self, text: str, pattern: str): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char: str) -> int: """finds the index of char in pattern in reverse order Parameters : char (chr): character to be searched Returns : i (int): index of char from last in pattern -1 (int): if char is not found in pattern """ for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 def mismatch_in_text(self, current_pos: int) -> int: """ find the index of mis-matched character in text when compared with pattern from last Parameters : current_pos (int): current index position of text Returns : i (int): index of mismatched char from last in text -1 (int): if there is no mismatch between pattern and text block """ for i in range(self.patLen - 1, -1, -1): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def bad_character_heuristic(self) -> list[int]: # searches pattern in text and returns index positions positions = [] for i in range(self.textLen - self.patLen + 1): mismatch_index = self.mismatch_in_text(i) if mismatch_index == -1: positions.append(i) else: match_index = self.match_in_pattern(self.text[mismatch_index]) i = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions text = "ABAABA" pattern = "AB" bms = BoyerMooreSearch(text, pattern) positions = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
""" The algorithm finds the pattern in given text using following rule. The bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pattern. If the mismatched character does not occur to the left in Pattern, a shift is proposed that moves the entirety of Pattern past the point of mismatch in the text. If there no mismatch then the pattern matches with text block. Time Complexity : O(n/m) n=length of main string m=length of pattern string """ from __future__ import annotations class BoyerMooreSearch: def __init__(self, text: str, pattern: str): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char: str) -> int: """finds the index of char in pattern in reverse order Parameters : char (chr): character to be searched Returns : i (int): index of char from last in pattern -1 (int): if char is not found in pattern """ for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 def mismatch_in_text(self, current_pos: int) -> int: """ find the index of mis-matched character in text when compared with pattern from last Parameters : current_pos (int): current index position of text Returns : i (int): index of mismatched char from last in text -1 (int): if there is no mismatch between pattern and text block """ for i in range(self.patLen - 1, -1, -1): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def bad_character_heuristic(self) -> list[int]: # searches pattern in text and returns index positions positions = [] for i in range(self.textLen - self.patLen + 1): mismatch_index = self.mismatch_in_text(i) if mismatch_index == -1: positions.append(i) else: match_index = self.match_in_pattern(self.text[mismatch_index]) i = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions text = "ABAABA" pattern = "AB" bms = BoyerMooreSearch(text, pattern) positions = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# A Python implementation of the 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 45: https://projecteuler.net/problem=45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ... Pentagonal P(n) = (n * (3 * n βˆ’ 1)) / 2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n * (2 * n βˆ’ 1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. All triangle numbers are hexagonal numbers. T(2n-1) = n * (2 * n - 1) = H(n) So we shall check only for hexagonal numbers which are also pentagonal. """ def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1) 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(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
""" Problem 45: https://projecteuler.net/problem=45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ... Pentagonal P(n) = (n * (3 * n βˆ’ 1)) / 2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n * (2 * n βˆ’ 1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. All triangle numbers are hexagonal numbers. T(2n-1) = n * (2 * n - 1) = H(n) So we shall check only for hexagonal numbers which are also pentagonal. """ def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1) 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(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 074: https://projecteuler.net/problem=74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 β†’ 363601 β†’ 1454 β†’ 169 871 β†’ 45361 β†’ 871 872 β†’ 45362 β†’ 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 β†’ 363600 β†’ 1454 β†’ 169 β†’ 363601 (β†’ 1454) 78 β†’ 45360 β†’ 871 β†’ 45361 (β†’ 871) 540 β†’ 145 (β†’ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? Solution approach: This solution simply consists in a loop that generates the chains of non repeating items using the cached sizes of the previous chains. The generation of the chain stops before a repeating item or if the size of the chain is greater then the desired one. After generating each chain, the length is checked and the counter increases. """ from math import factorial DIGIT_FACTORIAL: dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def digit_factorial_sum(number: int) -> int: """ Function to perform the sum of the factorial of all the digits in number >>> digit_factorial_sum(69.0) Traceback (most recent call last): ... TypeError: Parameter number must be int >>> digit_factorial_sum(-1) Traceback (most recent call last): ... ValueError: Parameter number must be greater than or equal to 0 >>> digit_factorial_sum(0) 1 >>> digit_factorial_sum(69) 363600 """ if not isinstance(number, int): raise TypeError("Parameter number must be int") if number < 0: raise ValueError("Parameter number must be greater than or equal to 0") # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(number)) def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: """ Returns the number of numbers below number_limit that produce chains with exactly chain_length non repeating elements. >>> solution(10.0, 1000) Traceback (most recent call last): ... TypeError: Parameters chain_length and number_limit must be int >>> solution(10, 1000.0) Traceback (most recent call last): ... TypeError: Parameters chain_length and number_limit must be int >>> solution(0, 1000) Traceback (most recent call last): ... ValueError: Parameters chain_length and number_limit must be greater than 0 >>> solution(10, 0) Traceback (most recent call last): ... ValueError: Parameters chain_length and number_limit must be greater than 0 >>> solution(10, 1000) 26 """ if not isinstance(chain_length, int) or not isinstance(number_limit, int): raise TypeError("Parameters chain_length and number_limit must be int") if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0" ) # the counter for the chains with the exact desired length chains_counter = 0 # the cached sizes of the previous chains chain_sets_lengths: dict[int, int] = {} for start_chain_element in range(1, number_limit): # The temporary set will contain the elements of the chain chain_set = set() chain_set_length = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. chain_element = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(chain_element) chain_set_length += 1 chain_element = digit_factorial_sum(chain_element) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] chain_sets_lengths[start_chain_element] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution()}")
""" Project Euler Problem 074: https://projecteuler.net/problem=74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 β†’ 363601 β†’ 1454 β†’ 169 871 β†’ 45361 β†’ 871 872 β†’ 45362 β†’ 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 β†’ 363600 β†’ 1454 β†’ 169 β†’ 363601 (β†’ 1454) 78 β†’ 45360 β†’ 871 β†’ 45361 (β†’ 871) 540 β†’ 145 (β†’ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? Solution approach: This solution simply consists in a loop that generates the chains of non repeating items using the cached sizes of the previous chains. The generation of the chain stops before a repeating item or if the size of the chain is greater then the desired one. After generating each chain, the length is checked and the counter increases. """ from math import factorial DIGIT_FACTORIAL: dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def digit_factorial_sum(number: int) -> int: """ Function to perform the sum of the factorial of all the digits in number >>> digit_factorial_sum(69.0) Traceback (most recent call last): ... TypeError: Parameter number must be int >>> digit_factorial_sum(-1) Traceback (most recent call last): ... ValueError: Parameter number must be greater than or equal to 0 >>> digit_factorial_sum(0) 1 >>> digit_factorial_sum(69) 363600 """ if not isinstance(number, int): raise TypeError("Parameter number must be int") if number < 0: raise ValueError("Parameter number must be greater than or equal to 0") # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(number)) def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: """ Returns the number of numbers below number_limit that produce chains with exactly chain_length non repeating elements. >>> solution(10.0, 1000) Traceback (most recent call last): ... TypeError: Parameters chain_length and number_limit must be int >>> solution(10, 1000.0) Traceback (most recent call last): ... TypeError: Parameters chain_length and number_limit must be int >>> solution(0, 1000) Traceback (most recent call last): ... ValueError: Parameters chain_length and number_limit must be greater than 0 >>> solution(10, 0) Traceback (most recent call last): ... ValueError: Parameters chain_length and number_limit must be greater than 0 >>> solution(10, 1000) 26 """ if not isinstance(chain_length, int) or not isinstance(number_limit, int): raise TypeError("Parameters chain_length and number_limit must be int") if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0" ) # the counter for the chains with the exact desired length chains_counter = 0 # the cached sizes of the previous chains chain_sets_lengths: dict[int, int] = {} for start_chain_element in range(1, number_limit): # The temporary set will contain the elements of the chain chain_set = set() chain_set_length = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. chain_element = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(chain_element) chain_set_length += 1 chain_element = digit_factorial_sum(chain_element) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] chain_sets_lengths[start_chain_element] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution()}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Lorentz transformation describes the transition from a reference frame P to another reference frame P', each of which is moving in a direction with respect to the other. The Lorentz transformation implemented in this code is the relativistic version using a four vector described by Minkowsky Space: x0 = ct, x1 = x, x2 = y, and x3 = z NOTE: Please note that x0 is c (speed of light) times t (time). So, the Lorentz transformation using a four vector is defined as: |ct'| | Ξ³ -Ξ³Ξ² 0 0| |ct| |x' | = |-Ξ³Ξ² Ξ³ 0 0| *|x | |y' | | 0 0 1 0| |y | |z' | | 0 0 0 1| |z | Where: 1 Ξ³ = --------------- ----------- / v^2 | /(1 - --- -/ c^2 v Ξ² = ----- c Reference: https://en.wikipedia.org/wiki/Lorentz_transformation """ from __future__ import annotations from math import sqrt import numpy as np # type: ignore from sympy import symbols # type: ignore # Coefficient # Speed of light (m/s) c = 299792458 # Symbols ct, x, y, z = symbols("ct x y z") ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") # Vehicle's speed divided by speed of light (no units) def beta(velocity: float) -> float: """ >>> beta(c) 1.0 >>> beta(199792458) 0.666435904801848 >>> beta(1e5) 0.00033356409519815205 >>> beta(0.2) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! """ if velocity > c: raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") # Usually the speed u should be much higher than 1 (c order of magnitude) elif velocity < 1: raise ValueError("Speed must be greater than 1!") return velocity / c def gamma(velocity: float) -> float: """ >>> gamma(4) 1.0000000000000002 >>> gamma(1e5) 1.0000000556325075 >>> gamma(3e7) 1.005044845777813 >>> gamma(2.8e8) 2.7985595722318277 >>> gamma(299792451) 4627.49902669495 >>> gamma(0.3) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! >>> gamma(2*c) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! """ return 1 / (sqrt(1 - beta(velocity) ** 2)) def transformation_matrix(velocity: float) -> np.array: """ >>> transformation_matrix(29979245) array([[ 1.00503781, -0.10050378, 0. , 0. ], [-0.10050378, 1.00503781, 0. , 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) >>> transformation_matrix(19979245.2) array([[ 1.00222811, -0.06679208, 0. , 0. ], [-0.06679208, 1.00222811, 0. , 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) >>> transformation_matrix(1) array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00, 0.00000000e+00], [-3.33564095e-09, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) >>> transformation_matrix(0) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! >>> transformation_matrix(c * 1.5) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! """ return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], [-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def transform( velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008 ) -> np.array: """ >>> transform(29979245,np.array([1,2,3,4]), False) array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) >>> transform(29979245) array([1.00503781498831*ct - 0.100503778816875*x, -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], dtype=object) >>> transform(19879210.2) array([1.0022057787097*ct - 0.066456172618675*x, -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], dtype=object) >>> transform(299792459, np.array([1,1,1,1])) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! >>> transform(-1, np.array([1,1,1,1])) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! """ # Ensure event is not a vector of zeros if not symbolic: # x0 is ct (speed of ligt * time) event[0] = event[0] * c else: # Symbolic four vector event = np.array([ct, x, y, z]) return transformation_matrix(velocity).dot(event) if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: four_vector = transform(29979245) print("Example of four vector: ") print(f"ct' = {four_vector[0]}") print(f"x' = {four_vector[1]}") print(f"y' = {four_vector[2]}") print(f"z' = {four_vector[3]}") # Substitute symbols with numerical values: values = np.array([1, 1, 1, 1]) sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)] print(f"\n{numerical_vector}")
""" Lorentz transformation describes the transition from a reference frame P to another reference frame P', each of which is moving in a direction with respect to the other. The Lorentz transformation implemented in this code is the relativistic version using a four vector described by Minkowsky Space: x0 = ct, x1 = x, x2 = y, and x3 = z NOTE: Please note that x0 is c (speed of light) times t (time). So, the Lorentz transformation using a four vector is defined as: |ct'| | Ξ³ -Ξ³Ξ² 0 0| |ct| |x' | = |-Ξ³Ξ² Ξ³ 0 0| *|x | |y' | | 0 0 1 0| |y | |z' | | 0 0 0 1| |z | Where: 1 Ξ³ = --------------- ----------- / v^2 | /(1 - --- -/ c^2 v Ξ² = ----- c Reference: https://en.wikipedia.org/wiki/Lorentz_transformation """ from __future__ import annotations from math import sqrt import numpy as np # type: ignore from sympy import symbols # type: ignore # Coefficient # Speed of light (m/s) c = 299792458 # Symbols ct, x, y, z = symbols("ct x y z") ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") # Vehicle's speed divided by speed of light (no units) def beta(velocity: float) -> float: """ >>> beta(c) 1.0 >>> beta(199792458) 0.666435904801848 >>> beta(1e5) 0.00033356409519815205 >>> beta(0.2) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! """ if velocity > c: raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") # Usually the speed u should be much higher than 1 (c order of magnitude) elif velocity < 1: raise ValueError("Speed must be greater than 1!") return velocity / c def gamma(velocity: float) -> float: """ >>> gamma(4) 1.0000000000000002 >>> gamma(1e5) 1.0000000556325075 >>> gamma(3e7) 1.005044845777813 >>> gamma(2.8e8) 2.7985595722318277 >>> gamma(299792451) 4627.49902669495 >>> gamma(0.3) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! >>> gamma(2*c) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! """ return 1 / (sqrt(1 - beta(velocity) ** 2)) def transformation_matrix(velocity: float) -> np.array: """ >>> transformation_matrix(29979245) array([[ 1.00503781, -0.10050378, 0. , 0. ], [-0.10050378, 1.00503781, 0. , 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) >>> transformation_matrix(19979245.2) array([[ 1.00222811, -0.06679208, 0. , 0. ], [-0.06679208, 1.00222811, 0. , 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) >>> transformation_matrix(1) array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00, 0.00000000e+00], [-3.33564095e-09, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) >>> transformation_matrix(0) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! >>> transformation_matrix(c * 1.5) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! """ return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], [-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def transform( velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008 ) -> np.array: """ >>> transform(29979245,np.array([1,2,3,4]), False) array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) >>> transform(29979245) array([1.00503781498831*ct - 0.100503778816875*x, -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], dtype=object) >>> transform(19879210.2) array([1.0022057787097*ct - 0.066456172618675*x, -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], dtype=object) >>> transform(299792459, np.array([1,1,1,1])) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! >>> transform(-1, np.array([1,1,1,1])) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! """ # Ensure event is not a vector of zeros if not symbolic: # x0 is ct (speed of ligt * time) event[0] = event[0] * c else: # Symbolic four vector event = np.array([ct, x, y, z]) return transformation_matrix(velocity).dot(event) if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: four_vector = transform(29979245) print("Example of four vector: ") print(f"ct' = {four_vector[0]}") print(f"x' = {four_vector[1]}") print(f"y' = {four_vector[2]}") print(f"z' = {four_vector[3]}") # Substitute symbols with numerical values: values = np.array([1, 1, 1, 1]) sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)] print(f"\n{numerical_vector}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author : Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. """ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(",") print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])] * len(self.array) sum_value = [int(self.array[0])] * len(self.array) for i in range(1, len(self.array)): sum_value[i] = max( int(self.array[i]) + sum_value[i - 1], int(self.array[i]) ) rear[i] = max(sum_value[i], rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() print(("the results is:", re))
""" Author : Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. """ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(",") print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])] * len(self.array) sum_value = [int(self.array[0])] * len(self.array) for i in range(1, len(self.array)): sum_value[i] = max( int(self.array[i]) + sum_value[i - 1], int(self.array[i]) ) rear[i] = max(sum_value[i], rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() print(("the results is:", re))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import re def indian_phone_validator(phone: str) -> bool: """ Determine whether the string is a valid phone number or not :param phone: :return: Boolean >>> indian_phone_validator("+91123456789") False >>> indian_phone_validator("+919876543210") True >>> indian_phone_validator("01234567896") False >>> indian_phone_validator("919876543218") True >>> indian_phone_validator("+91-1234567899") False >>> indian_phone_validator("+91-9876543218") True """ pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") match = re.search(pat, phone) if match: return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
import re def indian_phone_validator(phone: str) -> bool: """ Determine whether the string is a valid phone number or not :param phone: :return: Boolean >>> indian_phone_validator("+91123456789") False >>> indian_phone_validator("+919876543210") True >>> indian_phone_validator("01234567896") False >>> indian_phone_validator("919876543218") True >>> indian_phone_validator("+91-1234567899") False >>> indian_phone_validator("+91-9876543218") True """ pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") match = re.search(pat, phone) if match: return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Program to join a list of strings with a given separator """ def join(separator: str, separated: list[str]) -> str: """ >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' >>> join("#", "a") 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' >>> join("#", ["a", "b", "c", 1]) Traceback (most recent call last): ... Exception: join() accepts only strings to be joined """ joined = "" for word_or_phrase in separated: if not isinstance(word_or_phrase, str): raise Exception("join() accepts only strings to be joined") joined += word_or_phrase + separator return joined.strip(separator) if __name__ == "__main__": from doctest import testmod testmod()
""" Program to join a list of strings with a given separator """ def join(separator: str, separated: list[str]) -> str: """ >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' >>> join("#", "a") 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' >>> join("#", ["a", "b", "c", 1]) Traceback (most recent call last): ... Exception: join() accepts only strings to be joined """ joined = "" for word_or_phrase in separated: if not isinstance(word_or_phrase, str): raise Exception("join() accepts only strings to be joined") joined += word_or_phrase + separator return joined.strip(separator) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def double_factorial(n: int) -> int: """ Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_factorial >>> import math >>> all(double_factorial(i) == math.prod(range(i, 0, -2)) for i in range(20)) True >>> double_factorial(0.1) Traceback (most recent call last): ... ValueError: double_factorial() only accepts integral values >>> double_factorial(-1) Traceback (most recent call last): ... ValueError: double_factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("double_factorial() only accepts integral values") if n < 0: raise ValueError("double_factorial() not defined for negative values") return 1 if n <= 1 else n * double_factorial(n - 2) if __name__ == "__main__": import doctest doctest.testmod()
def double_factorial(n: int) -> int: """ Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_factorial >>> import math >>> all(double_factorial(i) == math.prod(range(i, 0, -2)) for i in range(20)) True >>> double_factorial(0.1) Traceback (most recent call last): ... ValueError: double_factorial() only accepts integral values >>> double_factorial(-1) Traceback (most recent call last): ... ValueError: double_factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("double_factorial() only accepts integral values") if n < 0: raise ValueError("double_factorial() not defined for negative values") return 1 if n <= 1 else n * double_factorial(n - 2) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Recursive Prorgam to create a Linked List from a sequence and # print a string representation of it. class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = "" temp = self while temp: string_rep += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List.""" # if elements_list is empty if not elements_list: raise Exception("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
# Recursive Prorgam to create a Linked List from a sequence and # print a string representation of it. class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = "" temp = self while temp: string_rep += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List.""" # if elements_list is empty if not elements_list: raise Exception("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import itertools import string from collections.abc import Generator, Iterable def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]: it = iter(seq) while True: chunk = tuple(itertools.islice(it, size)) if not chunk: return yield chunk def prepare_input(dirty: str) -> str: """ Prepare the plaintext by up-casing it and separating repeated letters with X's """ dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty) - 1): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(clean) & 1: clean += "X" return clean def generate_table(key: str) -> list[str]: # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler table = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(char) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(char) return table def encode(plaintext: str, key: str) -> str: table = generate_table(key) plaintext = prepare_input(plaintext) ciphertext = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for char1, char2 in chunker(plaintext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: ciphertext += table[row1 * 5 + (col1 + 1) % 5] ciphertext += table[row2 * 5 + (col2 + 1) % 5] elif col1 == col2: ciphertext += table[((row1 + 1) % 5) * 5 + col1] ciphertext += table[((row2 + 1) % 5) * 5 + col2] else: # rectangle ciphertext += table[row1 * 5 + col2] ciphertext += table[row2 * 5 + col1] return ciphertext def decode(ciphertext: str, key: str) -> str: table = generate_table(key) plaintext = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for char1, char2 in chunker(ciphertext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: plaintext += table[row1 * 5 + (col1 - 1) % 5] plaintext += table[row2 * 5 + (col2 - 1) % 5] elif col1 == col2: plaintext += table[((row1 - 1) % 5) * 5 + col1] plaintext += table[((row2 - 1) % 5) * 5 + col2] else: # rectangle plaintext += table[row1 * 5 + col2] plaintext += table[row2 * 5 + col1] return plaintext
import itertools import string from collections.abc import Generator, Iterable def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]: it = iter(seq) while True: chunk = tuple(itertools.islice(it, size)) if not chunk: return yield chunk def prepare_input(dirty: str) -> str: """ Prepare the plaintext by up-casing it and separating repeated letters with X's """ dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty) - 1): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(clean) & 1: clean += "X" return clean def generate_table(key: str) -> list[str]: # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler table = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(char) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(char) return table def encode(plaintext: str, key: str) -> str: table = generate_table(key) plaintext = prepare_input(plaintext) ciphertext = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for char1, char2 in chunker(plaintext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: ciphertext += table[row1 * 5 + (col1 + 1) % 5] ciphertext += table[row2 * 5 + (col2 + 1) % 5] elif col1 == col2: ciphertext += table[((row1 + 1) % 5) * 5 + col1] ciphertext += table[((row2 + 1) % 5) * 5 + col2] else: # rectangle ciphertext += table[row1 * 5 + col2] ciphertext += table[row2 * 5 + col1] return ciphertext def decode(ciphertext: str, key: str) -> str: table = generate_table(key) plaintext = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for char1, char2 in chunker(ciphertext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: plaintext += table[row1 * 5 + (col1 - 1) % 5] plaintext += table[row2 * 5 + (col2 - 1) % 5] elif col1 == col2: plaintext += table[((row1 - 1) % 5) * 5 + col1] plaintext += table[((row2 - 1) % 5) * 5 + col2] else: # rectangle plaintext += table[row1 * 5 + col2] plaintext += table[row2 * 5 + col1] return plaintext
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def binomial_coefficient(n, r): """ Find binomial coefficient using pascals triangle. >>> binomial_coefficient(10, 5) 252 """ c = [0 for i in range(r + 1)] # nc0 = 1 c[0] = 1 for i in range(1, n + 1): # to compute current row from previous row. j = min(i, r) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
def binomial_coefficient(n, r): """ Find binomial coefficient using pascals triangle. >>> binomial_coefficient(10, 5) 252 """ c = [0 for i in range(r + 1)] # nc0 = 1 c[0] = 1 for i in range(1, n + 1): # to compute current row from previous row. j = min(i, r) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html """ from __future__ import annotations def encode(plain: str) -> list[int]: """ >>> encode("myname") [13, 25, 14, 1, 13, 5] """ return [ord(elem) - 96 for elem in plain] def decode(encoded: list[int]) -> str: """ >>> decode([13, 25, 14, 1, 13, 5]) 'myname' """ return "".join(chr(elem + 96) for elem in encoded) def main() -> None: encoded = encode(input("-> ").strip().lower()) print("Encoded: ", encoded) print("Decoded:", decode(encoded)) if __name__ == "__main__": main()
""" Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html """ from __future__ import annotations def encode(plain: str) -> list[int]: """ >>> encode("myname") [13, 25, 14, 1, 13, 5] """ return [ord(elem) - 96 for elem in plain] def decode(encoded: list[int]) -> str: """ >>> decode([13, 25, 14, 1, 13, 5]) 'myname' """ return "".join(chr(elem + 96) for elem in encoded) def main() -> None: encoded = encode(input("-> ").strip().lower()) print("Encoded: ", encoded) print("Decoded:", decode(encoded)) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≀ x, y ≀ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≀ x, y ≀ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import collections import pprint from pathlib import Path def signature(word: str) -> str: """Return a word sorted >>> signature("test") 'estt' >>> signature("this is a test") ' aehiisssttt' >>> signature("finaltest") 'aefilnstt' """ return "".join(sorted(word)) def anagram(my_word: str) -> list[str]: """Return every anagram of the given word >>> anagram('test') ['sett', 'stet', 'test'] >>> anagram('this is a test') [] >>> anagram('final') ['final'] """ return word_bysig[signature(my_word)] data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8") word_list = sorted({word.strip().lower() for word in data.splitlines()}) word_bysig = collections.defaultdict(list) for word in word_list: word_bysig[signature(word)].append(word) if __name__ == "__main__": all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open("anagrams.txt", "w") as file: file.write("all_anagrams = \n ") file.write(pprint.pformat(all_anagrams))
from __future__ import annotations import collections import pprint from pathlib import Path def signature(word: str) -> str: """Return a word sorted >>> signature("test") 'estt' >>> signature("this is a test") ' aehiisssttt' >>> signature("finaltest") 'aefilnstt' """ return "".join(sorted(word)) def anagram(my_word: str) -> list[str]: """Return every anagram of the given word >>> anagram('test') ['sett', 'stet', 'test'] >>> anagram('this is a test') [] >>> anagram('final') ['final'] """ return word_bysig[signature(my_word)] data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8") word_list = sorted({word.strip().lower() for word in data.splitlines()}) word_bysig = collections.defaultdict(list) for word in word_list: word_bysig[signature(word)].append(word) if __name__ == "__main__": all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open("anagrams.txt", "w") as file: file.write("all_anagrams = \n ") file.write(pprint.pformat(all_anagrams))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import sys """ Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: O(n^3) Space Complexity: O(n^2) """ def matrix_chain_order(array): n = len(array) matrix = [[0 for x in range(n)] for x in range(n)] sol = [[0 for x in range(n)] for x in range(n)] for chain_length in range(2, n): for a in range(1, n - chain_length + 1): b = a + chain_length - 1 matrix[a][b] = sys.maxsize for c in range(a, b): cost = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: matrix[a][b] = cost sol[a][b] = c return matrix, sol # Print order of matrix with Ai as Matrix def print_optiomal_solution(optimal_solution, i, j): if i == j: print("A" + str(i), end=" ") else: print("(", end=" ") print_optiomal_solution(optimal_solution, i, optimal_solution[i][j]) print_optiomal_solution(optimal_solution, optimal_solution[i][j] + 1, j) print(")", end=" ") def main(): array = [30, 35, 15, 5, 10, 20, 25] n = len(array) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 matrix, optimal_solution = matrix_chain_order(array) print("No. of Operation required: " + str(matrix[1][n - 1])) print_optiomal_solution(optimal_solution, 1, n - 1) if __name__ == "__main__": main()
import sys """ Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: O(n^3) Space Complexity: O(n^2) """ def matrix_chain_order(array): n = len(array) matrix = [[0 for x in range(n)] for x in range(n)] sol = [[0 for x in range(n)] for x in range(n)] for chain_length in range(2, n): for a in range(1, n - chain_length + 1): b = a + chain_length - 1 matrix[a][b] = sys.maxsize for c in range(a, b): cost = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: matrix[a][b] = cost sol[a][b] = c return matrix, sol # Print order of matrix with Ai as Matrix def print_optiomal_solution(optimal_solution, i, j): if i == j: print("A" + str(i), end=" ") else: print("(", end=" ") print_optiomal_solution(optimal_solution, i, optimal_solution[i][j]) print_optiomal_solution(optimal_solution, optimal_solution[i][j] + 1, j) print(")", end=" ") def main(): array = [30, 35, 15, 5, 10, 20, 25] n = len(array) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 matrix, optimal_solution = matrix_chain_order(array) print("No. of Operation required: " + str(matrix[1][n - 1])) print_optiomal_solution(optimal_solution, 1, n - 1) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations # Divide and Conquer algorithm def find_max(nums: list[int | float], left: int, right: int) -> int | float: """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums, 0, len(nums) - 1) == max(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True >>> find_max([], 0, 0) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence >>> find_max(nums, 0, len(nums)) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_max(nums, -len(nums), -1) == max(nums) True >>> find_max(nums, -len(nums) - 1, -1) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max(nums, left, mid) # find max in range[left, mid] right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations # Divide and Conquer algorithm def find_max(nums: list[int | float], left: int, right: int) -> int | float: """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums, 0, len(nums) - 1) == max(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True >>> find_max([], 0, 0) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence >>> find_max(nums, 0, len(nums)) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_max(nums, -len(nums), -1) == max(nums) True >>> find_max(nums, -len(nums) - 1, -1) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max(nums, left, mid) # find max in range[left, mid] right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Equal Loudness Filter](audio_filters/equal_loudness_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [Norgate](boolean_algebra/norgate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Cnn Classification](computer_vision/cnn_classification.py) * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue On List](data_structures/queue/queue_on_list.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Fractional Knapsack](dynamic_programming/fractional_knapsack.py) * [Fractional Knapsack 2](dynamic_programming/fractional_knapsack_2.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) ## Electronics * [Carrier Concentration](electronics/carrier_concentration.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Power](electronics/electric_power.py) * [Ohms Law](electronics/ohms_law.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Fuzzy Logic * [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bfs Shortest Path](graphs/bfs_shortest_path.py) * [Bfs Zero One Shortest Path](graphs/bfs_zero_one_shortest_path.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph List](graphs/graph_list.py) * [Graph Matrix](graphs/graph_matrix.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gaussian Naive Bayes](machine_learning/gaussian_naive_bayes.py) * [Gradient Boosting Regressor](machine_learning/gradient_boosting_regressor.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Knn Sklearn](machine_learning/knn_sklearn.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * Lstm * [Lstm Prediction](machine_learning/lstm/lstm_prediction.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polymonial Regression](machine_learning/polymonial_regression.py) * [Random Forest Classifier](machine_learning/random_forest_classifier.py) * [Random Forest Regressor](machine_learning/random_forest_regressor.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) * [Abs](maths/abs.py) * [Abs Max](maths/abs_max.py) * [Abs Min](maths/abs_min.py) * [Add](maths/add.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euclidean Gcd](maths/euclidean_gcd.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial Iterative](maths/factorial_iterative.py) * [Factorial Recursive](maths/factorial_recursive.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Max Recursion](maths/find_max_recursion.py) * [Find Min](maths/find_min.py) * [Find Min Recursion](maths/find_min_recursion.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Kadanes](maths/kadanes.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Largest Subarray Sum](maths/largest_subarray_sum.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Miller Rabin](maths/miller_rabin.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Simpson Rule](maths/simpson_rule.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Test Prime Check](maths/test_prime_check.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Perceptron](neural_network/perceptron.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Check Strong Password](other/check_strong_password.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Nested Brackets](other/nested_brackets.py) * [Password Generator](other/password_generator.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) ## Quantum * [Deutsch Jozsa](quantum/deutsch_jozsa.py) * [Half Adder](quantum/half_adder.py) * [Not Gate](quantum/not_gate.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Random Normal Distribution Quicksort](sorts/random_normal_distribution_quicksort.py) * [Random Pivot Quick Sort](sorts/random_pivot_quick_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Check Pangram](strings/check_pangram.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Palindrome](strings/is_palindrome.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Anime And Play](web_programming/fetch_anime_and_play.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Equal Loudness Filter](audio_filters/equal_loudness_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [Norgate](boolean_algebra/norgate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Cnn Classification](computer_vision/cnn_classification.py) * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue On List](data_structures/queue/queue_on_list.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Fractional Knapsack](dynamic_programming/fractional_knapsack.py) * [Fractional Knapsack 2](dynamic_programming/fractional_knapsack_2.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) ## Electronics * [Carrier Concentration](electronics/carrier_concentration.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Power](electronics/electric_power.py) * [Ohms Law](electronics/ohms_law.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Fuzzy Logic * [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bfs Shortest Path](graphs/bfs_shortest_path.py) * [Bfs Zero One Shortest Path](graphs/bfs_zero_one_shortest_path.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph List](graphs/graph_list.py) * [Graph Matrix](graphs/graph_matrix.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gaussian Naive Bayes](machine_learning/gaussian_naive_bayes.py) * [Gradient Boosting Regressor](machine_learning/gradient_boosting_regressor.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Knn Sklearn](machine_learning/knn_sklearn.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * Lstm * [Lstm Prediction](machine_learning/lstm/lstm_prediction.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polymonial Regression](machine_learning/polymonial_regression.py) * [Random Forest Classifier](machine_learning/random_forest_classifier.py) * [Random Forest Regressor](machine_learning/random_forest_regressor.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) * [Abs](maths/abs.py) * [Abs Max](maths/abs_max.py) * [Abs Min](maths/abs_min.py) * [Add](maths/add.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euclidean Gcd](maths/euclidean_gcd.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial Iterative](maths/factorial_iterative.py) * [Factorial Recursive](maths/factorial_recursive.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Max Recursion](maths/find_max_recursion.py) * [Find Min](maths/find_min.py) * [Find Min Recursion](maths/find_min_recursion.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Kadanes](maths/kadanes.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Largest Subarray Sum](maths/largest_subarray_sum.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Miller Rabin](maths/miller_rabin.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Simpson Rule](maths/simpson_rule.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Test Prime Check](maths/test_prime_check.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Perceptron](neural_network/perceptron.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Check Strong Password](other/check_strong_password.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Nested Brackets](other/nested_brackets.py) * [Password Generator](other/password_generator.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) ## Quantum * [Deutsch Jozsa](quantum/deutsch_jozsa.py) * [Half Adder](quantum/half_adder.py) * [Not Gate](quantum/not_gate.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Random Normal Distribution Quicksort](sorts/random_normal_distribution_quicksort.py) * [Random Pivot Quick Sort](sorts/random_pivot_quick_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Check Pangram](strings/check_pangram.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Palindrome](strings/is_palindrome.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Anime And Play](web_programming/fetch_anime_and_play.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def topological_sort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
def topological_sort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001/010/100/000/101 b source: http://www.cse.yorku.ca/~oz/hash.html """ def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash_value = 5381 for x in s: hash_value = ((hash_value << 5) + hash_value) + ord(x) return hash_value & 0xFFFFFFFF
""" This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001/010/100/000/101 b source: http://www.cse.yorku.ca/~oz/hash.html """ def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash_value = 5381 for x in s: hash_value = ((hash_value << 5) + hash_value) + ord(x) return hash_value & 0xFFFFFFFF
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import base64 def base32_encode(string: str) -> bytes: """ Encodes a given string to base32, returning a bytes-like object >>> base32_encode("Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode("123456") b'GEZDGNBVGY======' >>> base32_encode("some long complex string") b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' """ # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8")) def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') 'some long complex string' """ # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8") if __name__ == "__main__": test = "Hello World!" encoded = base32_encode(test) print(encoded) decoded = base32_decode(encoded) print(decoded)
import base64 def base32_encode(string: str) -> bytes: """ Encodes a given string to base32, returning a bytes-like object >>> base32_encode("Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode("123456") b'GEZDGNBVGY======' >>> base32_encode("some long complex string") b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' """ # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8")) def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') 'some long complex string' """ # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8") if __name__ == "__main__": test = "Hello World!" encoded = base32_encode(test) print(encoded) decoded = base32_decode(encoded) print(decoded)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math class SegmentTree: def __init__(self, a): self.N = len(a) self.st = [0] * ( 4 * self.N ) # approximate the overall size of segment tree with array N self.build(1, 0, self.N - 1) def left(self, idx): return idx * 2 def right(self, idx): return idx * 2 + 1 def build(self, idx, l, r): # noqa: E741 if l == r: # noqa: E741 self.st[idx] = A[l] else: mid = (l + r) // 2 self.build(self.left(idx), l, mid) self.build(self.right(idx), mid + 1, r) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) def update(self, a, b, val): return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) def update_recursive(self, idx, l, r, a, b, val): # noqa: E741 """ update(1, 1, N, a, b, v) for update val v to [a,b] """ if r < a or l > b: return True if l == r: # noqa: E741 self.st[idx] = val return True mid = (l + r) // 2 self.update_recursive(self.left(idx), l, mid, a, b, val) self.update_recursive(self.right(idx), mid + 1, r, a, b, val) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) return True def query(self, a, b): return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1) def query_recursive(self, idx, l, r, a, b): # noqa: E741 """ query(1, 1, N, a, b) for query max of [a,b] """ if r < a or l > b: return -math.inf if l >= a and r <= b: # noqa: E741 return self.st[idx] mid = (l + r) // 2 q1 = self.query_recursive(self.left(idx), l, mid, a, b) q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b) return max(q1, q2) def show_data(self): show_list = [] for i in range(1, N + 1): show_list += [self.query(i, i)] print(show_list) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] N = 15 segt = SegmentTree(A) print(segt.query(4, 6)) print(segt.query(7, 11)) print(segt.query(7, 12)) segt.update(1, 3, 111) print(segt.query(1, 15)) segt.update(7, 8, 235) segt.show_data()
import math class SegmentTree: def __init__(self, a): self.N = len(a) self.st = [0] * ( 4 * self.N ) # approximate the overall size of segment tree with array N self.build(1, 0, self.N - 1) def left(self, idx): return idx * 2 def right(self, idx): return idx * 2 + 1 def build(self, idx, l, r): # noqa: E741 if l == r: # noqa: E741 self.st[idx] = A[l] else: mid = (l + r) // 2 self.build(self.left(idx), l, mid) self.build(self.right(idx), mid + 1, r) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) def update(self, a, b, val): return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) def update_recursive(self, idx, l, r, a, b, val): # noqa: E741 """ update(1, 1, N, a, b, v) for update val v to [a,b] """ if r < a or l > b: return True if l == r: # noqa: E741 self.st[idx] = val return True mid = (l + r) // 2 self.update_recursive(self.left(idx), l, mid, a, b, val) self.update_recursive(self.right(idx), mid + 1, r, a, b, val) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) return True def query(self, a, b): return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1) def query_recursive(self, idx, l, r, a, b): # noqa: E741 """ query(1, 1, N, a, b) for query max of [a,b] """ if r < a or l > b: return -math.inf if l >= a and r <= b: # noqa: E741 return self.st[idx] mid = (l + r) // 2 q1 = self.query_recursive(self.left(idx), l, mid, a, b) q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b) return max(q1, q2) def show_data(self): show_list = [] for i in range(1, N + 1): show_list += [self.query(i, i)] print(show_list) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] N = 15 segt = SegmentTree(A) print(segt.query(4, 6)) print(segt.query(7, 11)) print(segt.query(7, 12)) segt.update(1, 3, 111) print(segt.query(1, 15)) segt.update(7, 8, 235) segt.show_data()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
[report] sort = Cover omit = .env/*
[report] sort = Cover omit = .env/*
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def bubble_sort(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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) return (v_star_dot.dot(v)) / (v_star.dot(v)) def tests() -> None: a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(a), f"{a} is not hermitian." print(rayleigh_quotient(a, v)) a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(a), f"{a} is not hermitian." assert rayleigh_quotient(a, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) return (v_star_dot.dot(v)) / (v_star.dot(v)) def tests() -> None: a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(a), f"{a} is not hermitian." print(rayleigh_quotient(a, v)) a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(a), f"{a} is not hermitian." assert rayleigh_quotient(a, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Build the quantum full adder (QFA) for any sum of two quantum registers and one carry in. This circuit is designed using the Qiskit framework. This experiment run in IBM Q simulator with 1000 shots. . References: https://www.quantum-inspire.com/kbase/full-adder/ """ import math import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_full_adder( input_1: int = 1, input_2: int = 1, carry_in: int = 1 ) -> qiskit.result.counts.Counts: """ # >>> q_full_adder(inp_1, inp_2, cin) # the inputs can be 0/1 for qubits in define # values, or can be in a superposition of both # states with hadamard gate using the input value 2. # result for default values: {11: 1000} qr_0: ──■────■──────────────■── β”‚ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” qr_1: ──■─── X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€ X β”œ β”‚ β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ qr_2: ──┼─────────■─── X β”œβ”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ qr_3: ─ X β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ cr: 2/═════════════════════════ Args: input_1: input 1 for the circuit. input_2: input 2 for the circuit. carry_in: carry in for the circuit. Returns: qiskit.result.counts.Counts: sum result counts. >>> quantum_full_adder(1,1,1) {'11': 1000} >>> quantum_full_adder(0,0,1) {'01': 1000} >>> quantum_full_adder(1,0,1) {'10': 1000} >>> quantum_full_adder(1,-4,1) Traceback (most recent call last): ... ValueError: inputs must be positive. >>> quantum_full_adder('q',0,1) Traceback (most recent call last): ... TypeError: inputs must be integers. >>> quantum_full_adder(0.5,0,1) Traceback (most recent call last): ... ValueError: inputs must be exact integers. >>> quantum_full_adder(0,1,3) Traceback (most recent call last): ... ValueError: inputs must be less or equal to 2. """ if (type(input_1) == str) or (type(input_2) == str) or (type(carry_in) == str): raise TypeError("inputs must be integers.") if (input_1 < 0) or (input_2 < 0) or (carry_in < 0): raise ValueError("inputs must be positive.") if ( (math.floor(input_1) != input_1) or (math.floor(input_2) != input_2) or (math.floor(carry_in) != carry_in) ): raise ValueError("inputs must be exact integers.") if (input_1 > 2) or (input_2 > 2) or (carry_in > 2): raise ValueError("inputs must be less or equal to 2.") # build registers qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") # list the entries entry = [input_1, input_2, carry_in] quantum_circuit = QuantumCircuit(qr, cr) for i in range(0, 3): if entry[i] == 2: quantum_circuit.h(i) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(i) # for 1 entries elif entry[i] == 0: quantum_circuit.i(i) # for 0 entries # build the circuit quantum_circuit.ccx(0, 1, 3) # ccx = toffoli gate quantum_circuit.cx(0, 1) quantum_circuit.ccx(1, 2, 3) quantum_circuit.cx(1, 2) quantum_circuit.cx(0, 1) quantum_circuit.measure([2, 3], cr) # measure the last two qbits backend = Aer.get_backend("qasm_simulator") job = execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print(f"Total sum count for state is: {quantum_full_adder(1,1,1)}")
""" Build the quantum full adder (QFA) for any sum of two quantum registers and one carry in. This circuit is designed using the Qiskit framework. This experiment run in IBM Q simulator with 1000 shots. . References: https://www.quantum-inspire.com/kbase/full-adder/ """ import math import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_full_adder( input_1: int = 1, input_2: int = 1, carry_in: int = 1 ) -> qiskit.result.counts.Counts: """ # >>> q_full_adder(inp_1, inp_2, cin) # the inputs can be 0/1 for qubits in define # values, or can be in a superposition of both # states with hadamard gate using the input value 2. # result for default values: {11: 1000} qr_0: ──■────■──────────────■── β”‚ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” qr_1: ──■─── X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€ X β”œ β”‚ β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ qr_2: ──┼─────────■─── X β”œβ”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ qr_3: ─ X β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ cr: 2/═════════════════════════ Args: input_1: input 1 for the circuit. input_2: input 2 for the circuit. carry_in: carry in for the circuit. Returns: qiskit.result.counts.Counts: sum result counts. >>> quantum_full_adder(1,1,1) {'11': 1000} >>> quantum_full_adder(0,0,1) {'01': 1000} >>> quantum_full_adder(1,0,1) {'10': 1000} >>> quantum_full_adder(1,-4,1) Traceback (most recent call last): ... ValueError: inputs must be positive. >>> quantum_full_adder('q',0,1) Traceback (most recent call last): ... TypeError: inputs must be integers. >>> quantum_full_adder(0.5,0,1) Traceback (most recent call last): ... ValueError: inputs must be exact integers. >>> quantum_full_adder(0,1,3) Traceback (most recent call last): ... ValueError: inputs must be less or equal to 2. """ if (type(input_1) == str) or (type(input_2) == str) or (type(carry_in) == str): raise TypeError("inputs must be integers.") if (input_1 < 0) or (input_2 < 0) or (carry_in < 0): raise ValueError("inputs must be positive.") if ( (math.floor(input_1) != input_1) or (math.floor(input_2) != input_2) or (math.floor(carry_in) != carry_in) ): raise ValueError("inputs must be exact integers.") if (input_1 > 2) or (input_2 > 2) or (carry_in > 2): raise ValueError("inputs must be less or equal to 2.") # build registers qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") # list the entries entry = [input_1, input_2, carry_in] quantum_circuit = QuantumCircuit(qr, cr) for i in range(0, 3): if entry[i] == 2: quantum_circuit.h(i) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(i) # for 1 entries elif entry[i] == 0: quantum_circuit.i(i) # for 0 entries # build the circuit quantum_circuit.ccx(0, 1, 3) # ccx = toffoli gate quantum_circuit.cx(0, 1) quantum_circuit.ccx(1, 2, 3) quantum_circuit.cx(1, 2) quantum_circuit.cx(0, 1) quantum_circuit.measure([2, 3], cr) # measure the last two qbits backend = Aer.get_backend("qasm_simulator") job = execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print(f"Total sum count for state is: {quantum_full_adder(1,1,1)}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to find a factor within the specified number of attempts or within the specified number of steps. If ``num`` is prime, this algorithm is guaranteed to return None. https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm >>> pollard_rho(18446744073709551617) 274177 >>> pollard_rho(97546105601219326301) 9876543191 >>> pollard_rho(100) 2 >>> pollard_rho(17) >>> pollard_rho(17**3) 17 >>> pollard_rho(17**3, attempts=1) >>> pollard_rho(3*5*7) 21 >>> pollard_rho(1) Traceback (most recent call last): ... ValueError: The input value cannot be less than 2 """ # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(value: int, step: int, modulus: int) -> int: """ Returns a pseudorandom value modulo ``modulus`` based on the input ``value`` and attempt-specific ``step`` size. >>> rand_fn(0, 0, 0) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero >>> rand_fn(1, 2, 3) 0 >>> rand_fn(0, 10, 7) 3 >>> rand_fn(1234, 1, 17) 16 """ return (pow(value, 2) + step) % modulus for _ in range(attempts): # These track the position within the cycle detection logic. tortoise = seed hare = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. tortoise = rand_fn(tortoise, step, num) hare = rand_fn(hare, step, num) hare = rand_fn(hare, step, num) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. divisor = gcd(hare - tortoise, num) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. seed = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) args = parser.parse_args() divisor = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: quotient = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to find a factor within the specified number of attempts or within the specified number of steps. If ``num`` is prime, this algorithm is guaranteed to return None. https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm >>> pollard_rho(18446744073709551617) 274177 >>> pollard_rho(97546105601219326301) 9876543191 >>> pollard_rho(100) 2 >>> pollard_rho(17) >>> pollard_rho(17**3) 17 >>> pollard_rho(17**3, attempts=1) >>> pollard_rho(3*5*7) 21 >>> pollard_rho(1) Traceback (most recent call last): ... ValueError: The input value cannot be less than 2 """ # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(value: int, step: int, modulus: int) -> int: """ Returns a pseudorandom value modulo ``modulus`` based on the input ``value`` and attempt-specific ``step`` size. >>> rand_fn(0, 0, 0) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero >>> rand_fn(1, 2, 3) 0 >>> rand_fn(0, 10, 7) 3 >>> rand_fn(1234, 1, 17) 16 """ return (pow(value, 2) + step) % modulus for _ in range(attempts): # These track the position within the cycle detection logic. tortoise = seed hare = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. tortoise = rand_fn(tortoise, step, num) hare = rand_fn(hare, step, num) hare = rand_fn(hare, step, num) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. divisor = gcd(hare - tortoise, num) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. seed = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) args = parser.parse_args() divisor = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: quotient = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Demonstrates implementation of SHA1 Hash function in a Python class and gives utilities to find hash of string or hash of text from a file. Usage: python sha1.py --string "Hello World!!" python sha1.py --file "hello_world.txt" When run without any arguments, it prints the hash of the string "Hello World!! Welcome to Cryptography" Also contains a Test class to verify that the generated Hash is same as that returned by the hashlib library SHA1 hash or SHA1 sum of a string is a cryptographic function which means it is easy to calculate forwards but extremely difficult to calculate backwards. What this means is, you can easily calculate the hash of a string, but it is extremely difficult to know the original string if you have its hash. This property is useful to communicate securely, send encrypted messages and is very useful in payment systems, blockchain and cryptocurrency etc. The Algorithm as described in the reference: First we start with a message. The message is padded and the length of the message is added to the end. It is then split into blocks of 512 bits or 64 bytes. The blocks are then processed one at a time. Each block must be expanded and compressed. The value after each compression is added to a 160bit buffer called the current hash state. After the last block is processed the current hash state is returned as the final hash. Reference: https://deadhacker.com/2006/02/21/sha-1-illustrated/ """ import argparse import hashlib # hashlib is only used inside the Test class import struct import unittest class SHA1Hash: """ Class to contain the entire pipeline for SHA1 Hashing Algorithm >>> SHA1Hash(bytes('Allan', 'utf-8')).final_hash() '872af2d8ac3d8695387e7c804bf0e02c18df9e6e' """ def __init__(self, data): """ Inititates the variables data and h. h is a list of 5 8-digit Hexadecimal numbers corresponding to (1732584193, 4023233417, 2562383102, 271733878, 3285377520) respectively. We will start with this as a message digest. 0x is how you write Hexadecimal numbers in Python """ self.data = data self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] @staticmethod def rotate(n, b): """ Static method to be used inside other methods. Left rotates n by b. >>> SHA1Hash('').rotate(12,2) 48 """ return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF def padding(self): """ Pads the input message with zeros so that padded_data has 64 bytes or 512 bits """ padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64) padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data)) return padded_data def split_blocks(self): """ Returns a list of bytestrings each of length 64 """ return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64) ] # @staticmethod def expand_block(self, block): """ Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a list of 80 integers after some bit operations """ w = list(struct.unpack(">16L", block)) + [0] * 64 for i in range(16, 80): w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1) return w def final_hash(self): """ Calls all the other methods to process the input. Pads the data, then splits into blocks and then does a series of operations for each block (including expansion). For each block, the variable h that was initialized is copied to a,b,c,d,e and these 5 variables a,b,c,d,e undergo several changes. After all the blocks are processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1] and so on. This h becomes our final hash which is returned. """ self.padded_data = self.padding() self.blocks = self.split_blocks() for block in self.blocks: expanded_block = self.expand_block(block) a, b, c, d, e = self.h for i in range(0, 80): if 0 <= i < 20: f = (b & c) | ((~b) & d) k = 0x5A827999 elif 20 <= i < 40: f = b ^ c ^ d k = 0x6ED9EBA1 elif 40 <= i < 60: f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC elif 60 <= i < 80: f = b ^ c ^ d k = 0xCA62C1D6 a, b, c, d, e = ( self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xFFFFFFFF, a, self.rotate(b, 30), c, d, ) self.h = ( self.h[0] + a & 0xFFFFFFFF, self.h[1] + b & 0xFFFFFFFF, self.h[2] + c & 0xFFFFFFFF, self.h[3] + d & 0xFFFFFFFF, self.h[4] + e & 0xFFFFFFFF, ) return "%08x%08x%08x%08x%08x" % tuple(self.h) class SHA1HashTest(unittest.TestCase): """ Test class for the SHA1Hash class. Inherits the TestCase class from unittest """ def testMatchHashes(self): # noqa: N802 msg = bytes("Test String", "utf-8") self.assertEqual(SHA1Hash(msg).final_hash(), hashlib.sha1(msg).hexdigest()) def main(): """ Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main() has been commented because we probably don't want to run the test each time. """ # unittest.main() parser = argparse.ArgumentParser(description="Process some strings or files") parser.add_argument( "--string", dest="input_string", default="Hello World!! Welcome to Cryptography", help="Hash the string", ) parser.add_argument("--file", dest="input_file", help="Hash contents of a file") args = parser.parse_args() input_string = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file, "rb") as f: hash_input = f.read() else: hash_input = bytes(input_string, "utf-8") print(SHA1Hash(hash_input).final_hash()) if __name__ == "__main__": main() import doctest doctest.testmod()
""" Demonstrates implementation of SHA1 Hash function in a Python class and gives utilities to find hash of string or hash of text from a file. Usage: python sha1.py --string "Hello World!!" python sha1.py --file "hello_world.txt" When run without any arguments, it prints the hash of the string "Hello World!! Welcome to Cryptography" Also contains a Test class to verify that the generated Hash is same as that returned by the hashlib library SHA1 hash or SHA1 sum of a string is a cryptographic function which means it is easy to calculate forwards but extremely difficult to calculate backwards. What this means is, you can easily calculate the hash of a string, but it is extremely difficult to know the original string if you have its hash. This property is useful to communicate securely, send encrypted messages and is very useful in payment systems, blockchain and cryptocurrency etc. The Algorithm as described in the reference: First we start with a message. The message is padded and the length of the message is added to the end. It is then split into blocks of 512 bits or 64 bytes. The blocks are then processed one at a time. Each block must be expanded and compressed. The value after each compression is added to a 160bit buffer called the current hash state. After the last block is processed the current hash state is returned as the final hash. Reference: https://deadhacker.com/2006/02/21/sha-1-illustrated/ """ import argparse import hashlib # hashlib is only used inside the Test class import struct import unittest class SHA1Hash: """ Class to contain the entire pipeline for SHA1 Hashing Algorithm >>> SHA1Hash(bytes('Allan', 'utf-8')).final_hash() '872af2d8ac3d8695387e7c804bf0e02c18df9e6e' """ def __init__(self, data): """ Inititates the variables data and h. h is a list of 5 8-digit Hexadecimal numbers corresponding to (1732584193, 4023233417, 2562383102, 271733878, 3285377520) respectively. We will start with this as a message digest. 0x is how you write Hexadecimal numbers in Python """ self.data = data self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] @staticmethod def rotate(n, b): """ Static method to be used inside other methods. Left rotates n by b. >>> SHA1Hash('').rotate(12,2) 48 """ return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF def padding(self): """ Pads the input message with zeros so that padded_data has 64 bytes or 512 bits """ padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64) padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data)) return padded_data def split_blocks(self): """ Returns a list of bytestrings each of length 64 """ return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64) ] # @staticmethod def expand_block(self, block): """ Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a list of 80 integers after some bit operations """ w = list(struct.unpack(">16L", block)) + [0] * 64 for i in range(16, 80): w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1) return w def final_hash(self): """ Calls all the other methods to process the input. Pads the data, then splits into blocks and then does a series of operations for each block (including expansion). For each block, the variable h that was initialized is copied to a,b,c,d,e and these 5 variables a,b,c,d,e undergo several changes. After all the blocks are processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1] and so on. This h becomes our final hash which is returned. """ self.padded_data = self.padding() self.blocks = self.split_blocks() for block in self.blocks: expanded_block = self.expand_block(block) a, b, c, d, e = self.h for i in range(0, 80): if 0 <= i < 20: f = (b & c) | ((~b) & d) k = 0x5A827999 elif 20 <= i < 40: f = b ^ c ^ d k = 0x6ED9EBA1 elif 40 <= i < 60: f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC elif 60 <= i < 80: f = b ^ c ^ d k = 0xCA62C1D6 a, b, c, d, e = ( self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xFFFFFFFF, a, self.rotate(b, 30), c, d, ) self.h = ( self.h[0] + a & 0xFFFFFFFF, self.h[1] + b & 0xFFFFFFFF, self.h[2] + c & 0xFFFFFFFF, self.h[3] + d & 0xFFFFFFFF, self.h[4] + e & 0xFFFFFFFF, ) return "%08x%08x%08x%08x%08x" % tuple(self.h) class SHA1HashTest(unittest.TestCase): """ Test class for the SHA1Hash class. Inherits the TestCase class from unittest """ def testMatchHashes(self): # noqa: N802 msg = bytes("Test String", "utf-8") self.assertEqual(SHA1Hash(msg).final_hash(), hashlib.sha1(msg).hexdigest()) def main(): """ Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main() has been commented because we probably don't want to run the test each time. """ # unittest.main() parser = argparse.ArgumentParser(description="Process some strings or files") parser.add_argument( "--string", dest="input_string", default="Hello World!! Welcome to Cryptography", help="Hash the string", ) parser.add_argument("--file", dest="input_file", help="Hash contents of a file") args = parser.parse_args() input_string = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file, "rb") as f: hash_input = f.read() else: hash_input = bytes(input_string, "utf-8") print(SHA1Hash(hash_input).final_hash()) if __name__ == "__main__": main() import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
2022-10-15T19:51:55Z
2022-10-16T09:33:29Z
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≀ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≀ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≀ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≀ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
-1