repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list [10, 6] >>> len(binary_heap) 2 """ def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: """ Swap the element up """ temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: """ Insert new element """ self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: """ Swap the element down """ while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: """ Pop the root element """ max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): """ Length of the array """ return self.__size if __name__ == "__main__": import doctest doctest.testmod() # create an instance of BinaryHeap binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) # pop root(max-values because it is max heap) print(binary_heap.pop()) # 15 print(binary_heap.pop()) # 12 # get the list and size after operations print(binary_heap.get_list) print(len(binary_heap))
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list [10, 6] >>> len(binary_heap) 2 """ def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: """Swap the element up""" temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: """Insert new element""" self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: """Swap the element down""" while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: """Pop the root element""" max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): """Length of the array""" return self.__size if __name__ == "__main__": import doctest doctest.testmod() # create an instance of BinaryHeap binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) # pop root(max-values because it is max heap) print(binary_heap.pop()) # 15 print(binary_heap.pop()) # 12 # get the list and size after operations print(binary_heap.get_list) print(len(binary_heap))
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """ A Private class (to be inherited) """ class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """A Private class (to be inherited)""" class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class StackOverflowError(BaseException): pass class Stack: """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out (LIFO). https://en.wikipedia.org/wiki/Stack_(abstract_data_type) """ def __init__(self, limit: int = 10): self.stack = [] self.limit = limit def __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data): """ Push an element to the top of the stack.""" if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self): """ Pop an element off of the top of the stack.""" return self.stack.pop() def peek(self): """ Peek at the top-most element of the stack.""" return self.stack[-1] def is_empty(self) -> bool: """ Check if a stack is empty.""" return not bool(self.stack) def is_full(self) -> bool: return self.size() == self.limit def size(self) -> int: """ Return the size of the stack.""" return len(self.stack) def __contains__(self, item) -> bool: """Check if item is in stack""" return item in self.stack def test_stack() -> None: """ >>> test_stack() """ stack = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() assert False # This should not happen except IndexError: assert True # This should happen try: _ = stack.peek() assert False # This should not happen except IndexError: assert True # This should happen for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) is True assert stack.is_empty() is False assert stack.is_full() is True assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) assert False # This should not happen except StackOverflowError: assert True # This should happen assert stack.is_empty() is False assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack()
class StackOverflowError(BaseException): pass class Stack: """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out (LIFO). https://en.wikipedia.org/wiki/Stack_(abstract_data_type) """ def __init__(self, limit: int = 10): self.stack = [] self.limit = limit def __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data): """Push an element to the top of the stack.""" if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self): """Pop an element off of the top of the stack.""" return self.stack.pop() def peek(self): """Peek at the top-most element of the stack.""" return self.stack[-1] def is_empty(self) -> bool: """Check if a stack is empty.""" return not bool(self.stack) def is_full(self) -> bool: return self.size() == self.limit def size(self) -> int: """Return the size of the stack.""" return len(self.stack) def __contains__(self, item) -> bool: """Check if item is in stack""" return item in self.stack def test_stack() -> None: """ >>> test_stack() """ stack = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() assert False # This should not happen except IndexError: assert True # This should happen try: _ = stack.peek() assert False # This should not happen except IndexError: assert True # This should happen for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) is True assert stack.is_empty() is False assert stack.is_full() is True assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) assert False # This should not happen except StackOverflowError: assert True # This should happen assert stack.is_empty() is False assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """ Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math def rearrange(bitString32): """[summary] Regroups the given binary string. Arguments: bitString32 {[string]} -- [32 bit binary] Raises: ValueError -- [if the given string not are 32 bit binary string] Returns: [string] -- [32 bit binary string] >>> rearrange('1234567890abcdfghijklmnopqrstuvw') 'pqrstuvwhijklmno90abcdfg12345678' """ if len(bitString32) != 32: raise ValueError("Need length 32") newString = "" for i in [3, 2, 1, 0]: newString += bitString32[8 * i : 8 * i + 8] return newString def reformatHex(i): """[summary] Converts the given integer into 8-digit hex number. Arguments: i {[int]} -- [integer] >>> reformatHex(666) '9a020000' """ hexrep = format(i, "08x") thing = "" for i in [3, 2, 1, 0]: thing += hexrep[2 * i : 2 * i + 2] return thing def pad(bitString): """[summary] Fills up the binary string to a 512 bit binary string Arguments: bitString {[string]} -- [binary string] Returns: [string] -- [binary string] """ startLength = len(bitString) bitString += "1" while len(bitString) % 512 != 448: bitString += "0" lastPart = format(startLength, "064b") bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32]) return bitString def getBlock(bitString): """[summary] Iterator: Returns by each call a list of length 16 with the 32 bit integer blocks. Arguments: bitString {[string]} -- [binary string >= 512] """ currPos = 0 while currPos < len(bitString): currPart = bitString[currPos : currPos + 512] mySplits = [] for i in range(16): mySplits.append(int(rearrange(currPart[32 * i : 32 * i + 32]), 2)) yield mySplits currPos += 512 def not32(i): """ >>> not32(34) 4294967261 """ i_str = format(i, "032b") new_str = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(new_str, 2) def sum32(a, b): """""" return (a + b) % 2 ** 32 def leftrot32(i, s): return (i << s) ^ (i >> (32 - s)) def md5me(testString): """[summary] Returns a 32-bit hash code of the string 'testString' Arguments: testString {[string]} -- [message] """ bs = "" for i in testString: bs += format(ord(i), "08b") bs = pad(bs) tvals = [int(2 ** 32 * abs(math.sin(i + 1))) for i in range(64)] a0 = 0x67452301 b0 = 0xEFCDAB89 c0 = 0x98BADCFE d0 = 0x10325476 s = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] for m in getBlock(bs): A = a0 B = b0 C = c0 D = d0 for i in range(64): if i <= 15: # f = (B & C) | (not32(B) & D) f = D ^ (B & (C ^ D)) g = i elif i <= 31: # f = (D & B) | (not32(D) & C) f = C ^ (D & (B ^ C)) g = (5 * i + 1) % 16 elif i <= 47: f = B ^ C ^ D g = (3 * i + 5) % 16 else: f = C ^ (B | not32(D)) g = (7 * i) % 16 dtemp = D D = C C = B B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2 ** 32, s[i])) A = dtemp a0 = sum32(a0, A) b0 = sum32(b0, B) c0 = sum32(c0, C) d0 = sum32(d0, D) digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0) return digest def test(): assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e" assert ( md5me("The quick brown fox jumps over the lazy dog") == "9e107d9d372bb6826bd81d3542a419d6" ) print("Success.") if __name__ == "__main__": test() import doctest doctest.testmod()
import math def rearrange(bitString32): """[summary] Regroups the given binary string. Arguments: bitString32 {[string]} -- [32 bit binary] Raises: ValueError -- [if the given string not are 32 bit binary string] Returns: [string] -- [32 bit binary string] >>> rearrange('1234567890abcdfghijklmnopqrstuvw') 'pqrstuvwhijklmno90abcdfg12345678' """ if len(bitString32) != 32: raise ValueError("Need length 32") newString = "" for i in [3, 2, 1, 0]: newString += bitString32[8 * i : 8 * i + 8] return newString def reformatHex(i): """[summary] Converts the given integer into 8-digit hex number. Arguments: i {[int]} -- [integer] >>> reformatHex(666) '9a020000' """ hexrep = format(i, "08x") thing = "" for i in [3, 2, 1, 0]: thing += hexrep[2 * i : 2 * i + 2] return thing def pad(bitString): """[summary] Fills up the binary string to a 512 bit binary string Arguments: bitString {[string]} -- [binary string] Returns: [string] -- [binary string] """ startLength = len(bitString) bitString += "1" while len(bitString) % 512 != 448: bitString += "0" lastPart = format(startLength, "064b") bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32]) return bitString def getBlock(bitString): """[summary] Iterator: Returns by each call a list of length 16 with the 32 bit integer blocks. Arguments: bitString {[string]} -- [binary string >= 512] """ currPos = 0 while currPos < len(bitString): currPart = bitString[currPos : currPos + 512] mySplits = [] for i in range(16): mySplits.append(int(rearrange(currPart[32 * i : 32 * i + 32]), 2)) yield mySplits currPos += 512 def not32(i): """ >>> not32(34) 4294967261 """ i_str = format(i, "032b") new_str = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(new_str, 2) def sum32(a, b): return (a + b) % 2 ** 32 def leftrot32(i, s): return (i << s) ^ (i >> (32 - s)) def md5me(testString): """[summary] Returns a 32-bit hash code of the string 'testString' Arguments: testString {[string]} -- [message] """ bs = "" for i in testString: bs += format(ord(i), "08b") bs = pad(bs) tvals = [int(2 ** 32 * abs(math.sin(i + 1))) for i in range(64)] a0 = 0x67452301 b0 = 0xEFCDAB89 c0 = 0x98BADCFE d0 = 0x10325476 s = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] for m in getBlock(bs): A = a0 B = b0 C = c0 D = d0 for i in range(64): if i <= 15: # f = (B & C) | (not32(B) & D) f = D ^ (B & (C ^ D)) g = i elif i <= 31: # f = (D & B) | (not32(D) & C) f = C ^ (D & (B ^ C)) g = (5 * i + 1) % 16 elif i <= 47: f = B ^ C ^ D g = (3 * i + 5) % 16 else: f = C ^ (B | not32(D)) g = (7 * i) % 16 dtemp = D D = C C = B B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2 ** 32, s[i])) A = dtemp a0 = sum32(a0, A) b0 = sum32(b0, B) c0 = sum32(c0, C) d0 = sum32(d0, D) digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0) return digest def test(): assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e" assert ( md5me("The quick brown fox jumps over the lazy dog") == "9e107d9d372bb6826bd81d3542a419d6" ) print("Success.") if __name__ == "__main__": test() import doctest doctest.testmod()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) Calculate the class probabilities : P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. ------------------------------------------------ Squared_Difference = (x - mean(k)) ** 2 Variance = (1 / (count(x) - count(classes))) * (for i = 1 to i = n --> sum(Squared_Difference(xi))) Making Predictions : discriminant(x) = x * (mean / variance) - ((mean ** 2) / (2 * variance)) + Ln(probability) --------------------------------------------------------------------------- After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: @EverLookNeverSee """ from math import log from os import name, system from random import gauss, seed from typing import Callable, TypeVar # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: """ Generate gaussian distribution instances based-on given mean and standard deviation :param mean: mean value of class :param std_dev: value of standard deviation entered by usr or default value of it :param instance_count: instance number of class :return: a list containing generated values based-on given mean, std_dev and instance_count >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079] """ seed(1) return [gauss(mean, std_dev) for _ in range(instance_count)] # Make corresponding Y flags to detecting classes def y_generator(class_count: int, instance_count: list) -> list: """ Generate y values for corresponding classes :param class_count: Number of classes(data groupings) in dataset :param instance_count: number of instances in class :return: corresponding values for data groupings in dataset >>> y_generator(1, [10]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> y_generator(2, [5, 10]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] """ return [k for k in range(class_count) for _ in range(instance_count[k])] # Calculate the class means def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class >>> items = gaussian_distribution(5.0, 1.0, 20) >>> calculate_mean(len(items), items) 5.011267842911003 """ # the sum of all items divided by number of instances return sum(items) / instance_count # Calculate the class probabilities def calculate_probabilities(instance_count: int, total_count: int) -> float: """ Calculate the probability that a given instance will belong to which class :param instance_count: number of instances in class :param total_count: the number of all instances :return: value of probability for considered class >>> calculate_probabilities(20, 60) 0.3333333333333333 >>> calculate_probabilities(30, 100) 0.3 """ # number of instances in specific class divided by number of all instances return instance_count / total_count # Calculate the variance def calculate_variance(items: list, means: list, total_count: int) -> float: """ Calculate the variance :param items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param total_count: the number of all instances :return: calculated variance for considered dataset >>> items = gaussian_distribution(5.0, 1.0, 20) >>> means = [5.011267842911003] >>> total_count = 20 >>> calculate_variance([items], means, total_count) 0.9618530973487491 """ squared_diff = [] # An empty list to store all squared differences # iterate over number of elements in items for i in range(len(items)): # for loop iterates over number of elements in inner layer of items for j in range(len(items[i])): # appending squared differences to 'squared_diff' list squared_diff.append((items[i][j] - means[i]) ** 2) # one divided by (the number of all instances - number of classes) multiplied by # sum of all squared differences n_classes = len(means) # Number of classes in dataset return 1 / (total_count - n_classes) * sum(squared_diff) # Making predictions def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079], [11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508], [16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508]] >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002] >>> variance = 0.9618530973487494 >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333] >>> predict_y_values(x_items, means, variance, ... probabilities) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ # An empty list to store generated discriminant values of all items in dataset for # each class results = [] # for loop iterates over number of elements in list for i in range(len(x_items)): # for loop iterates over number of inner items of each element for j in range(len(x_items[i])): temp = [] # to store all discriminant values of each item as a list # for loop iterates over number of classes we have in our dataset for k in range(len(x_items)): # appending values of discriminants for each class to 'temp' list temp.append( x_items[i][j] * (means[k] / variance) - (means[k] ** 2 / (2 * variance)) + log(probabilities[k]) ) # appending discriminant values of each item to 'results' list results.append(temp) return [result.index(max(result)) for result in results] # Calculating Accuracy def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_values' function :return: percentage of accuracy >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1] >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1] >>> accuracy(actual_y, predicted_y) 50.0 >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> accuracy(actual_y, predicted_y) 100.0 """ # iterate over one element of each list at a time (zip mode) # prediction is correct if actual Y value equals to predicted Y value correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j) # percentage of accuracy equals to number of correct predictions divided by number # of all data and multiplied by 100 return (correct / len(actual_y)) * 100 num = TypeVar("num") def valid_input( input_type: Callable[[object], num], # Usually float or int input_msg: str, err_msg: str, condition: Callable[[num], bool] = lambda x: True, default: str = None, ) -> num: """ Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input """ while True: try: user_input = input_type(input(input_msg).strip() or default) if condition(user_input): return user_input else: print(f"{user_input}: {err_msg}") continue except ValueError: print( f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" ) # Main Function def main(): """ This function starts execution phase """ while True: print(" Linear Discriminant Analysis ".center(50, "*")) print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes n_classes = valid_input( input_type=int, condition=lambda x: x > 0, input_msg="Enter the number of classes (Data Groupings): ", err_msg="Number of classes should be positive!", ) print("-" * 100) # Trying to get the value of standard deviation std_dev = valid_input( input_type=float, condition=lambda x: x >= 0, input_msg=( "Enter the value of standard deviation" "(Default value is 1.0 for all classes): " ), err_msg="Standard deviation should not be negative!", default="1.0", ) print("-" * 100) # Trying to get number of instances in classes and theirs means to generate # dataset counts = [] # An empty list to store instance counts of classes in dataset for i in range(n_classes): user_count = valid_input( input_type=int, condition=lambda x: x > 0, input_msg=(f"Enter The number of instances for class_{i+1}: "), err_msg="Number of instances should be positive!", ) counts.append(user_count) print("-" * 100) # An empty list to store values of user-entered means of classes user_means = [] for a in range(n_classes): user_mean = valid_input( input_type=float, input_msg=(f"Enter the value of mean for class_{a+1}: "), err_msg="This is an invalid value.", ) user_means.append(user_mean) print("-" * 100) print("Standard deviation: ", std_dev) # print out the number of instances in classes in separated line for i, count in enumerate(counts, 1): print(f"Number of instances in class_{i} is: {count}") print("-" * 100) # print out mean values of classes separated line for i, user_mean in enumerate(user_means, 1): print(f"Mean of class_{i} is: {user_mean}") print("-" * 100) # Generating training dataset drawn from gaussian distribution x = [ gaussian_distribution(user_means[j], std_dev, counts[j]) for j in range(n_classes) ] print("Generated Normal Distribution: \n", x) print("-" * 100) # Generating Ys to detecting corresponding classes y = y_generator(n_classes, counts) print("Generated Corresponding Ys: \n", y) print("-" * 100) # Calculating the value of actual mean for each class actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)] # for loop iterates over number of elements in 'actual_means' list and print # out them in separated line for i, actual_mean in enumerate(actual_means, 1): print(f"Actual(Real) mean of class_{i} is: {actual_mean}") print("-" * 100) # Calculating the value of probabilities for each class probabilities = [ calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes) ] # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class variance = calculate_variance(x, actual_means, sum(counts)) print("Variance: ", variance) print("-" * 100) # Predicting Y values # storing predicted Y values in 'pre_indexes' variable pre_indexes = predict_y_values(x, actual_means, variance, probabilities) print("-" * 100) # Calculating Accuracy of the model print(f"Accuracy: {accuracy(y, pre_indexes)}") print("-" * 100) print(" DONE ".center(100, "+")) if input("Press any key to restart or 'q' for quit: ").strip().lower() == "q": print("\n" + "GoodBye!".center(100, "-") + "\n") break system("cls" if name == "nt" else "clear") if __name__ == "__main__": main()
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) Calculate the class probabilities : P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. ------------------------------------------------ Squared_Difference = (x - mean(k)) ** 2 Variance = (1 / (count(x) - count(classes))) * (for i = 1 to i = n --> sum(Squared_Difference(xi))) Making Predictions : discriminant(x) = x * (mean / variance) - ((mean ** 2) / (2 * variance)) + Ln(probability) --------------------------------------------------------------------------- After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: @EverLookNeverSee """ from math import log from os import name, system from random import gauss, seed from typing import Callable, TypeVar # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: """ Generate gaussian distribution instances based-on given mean and standard deviation :param mean: mean value of class :param std_dev: value of standard deviation entered by usr or default value of it :param instance_count: instance number of class :return: a list containing generated values based-on given mean, std_dev and instance_count >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079] """ seed(1) return [gauss(mean, std_dev) for _ in range(instance_count)] # Make corresponding Y flags to detecting classes def y_generator(class_count: int, instance_count: list) -> list: """ Generate y values for corresponding classes :param class_count: Number of classes(data groupings) in dataset :param instance_count: number of instances in class :return: corresponding values for data groupings in dataset >>> y_generator(1, [10]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> y_generator(2, [5, 10]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] """ return [k for k in range(class_count) for _ in range(instance_count[k])] # Calculate the class means def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class >>> items = gaussian_distribution(5.0, 1.0, 20) >>> calculate_mean(len(items), items) 5.011267842911003 """ # the sum of all items divided by number of instances return sum(items) / instance_count # Calculate the class probabilities def calculate_probabilities(instance_count: int, total_count: int) -> float: """ Calculate the probability that a given instance will belong to which class :param instance_count: number of instances in class :param total_count: the number of all instances :return: value of probability for considered class >>> calculate_probabilities(20, 60) 0.3333333333333333 >>> calculate_probabilities(30, 100) 0.3 """ # number of instances in specific class divided by number of all instances return instance_count / total_count # Calculate the variance def calculate_variance(items: list, means: list, total_count: int) -> float: """ Calculate the variance :param items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param total_count: the number of all instances :return: calculated variance for considered dataset >>> items = gaussian_distribution(5.0, 1.0, 20) >>> means = [5.011267842911003] >>> total_count = 20 >>> calculate_variance([items], means, total_count) 0.9618530973487491 """ squared_diff = [] # An empty list to store all squared differences # iterate over number of elements in items for i in range(len(items)): # for loop iterates over number of elements in inner layer of items for j in range(len(items[i])): # appending squared differences to 'squared_diff' list squared_diff.append((items[i][j] - means[i]) ** 2) # one divided by (the number of all instances - number of classes) multiplied by # sum of all squared differences n_classes = len(means) # Number of classes in dataset return 1 / (total_count - n_classes) * sum(squared_diff) # Making predictions def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079], [11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508], [16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508]] >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002] >>> variance = 0.9618530973487494 >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333] >>> predict_y_values(x_items, means, variance, ... probabilities) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ # An empty list to store generated discriminant values of all items in dataset for # each class results = [] # for loop iterates over number of elements in list for i in range(len(x_items)): # for loop iterates over number of inner items of each element for j in range(len(x_items[i])): temp = [] # to store all discriminant values of each item as a list # for loop iterates over number of classes we have in our dataset for k in range(len(x_items)): # appending values of discriminants for each class to 'temp' list temp.append( x_items[i][j] * (means[k] / variance) - (means[k] ** 2 / (2 * variance)) + log(probabilities[k]) ) # appending discriminant values of each item to 'results' list results.append(temp) return [result.index(max(result)) for result in results] # Calculating Accuracy def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_values' function :return: percentage of accuracy >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1] >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1] >>> accuracy(actual_y, predicted_y) 50.0 >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> accuracy(actual_y, predicted_y) 100.0 """ # iterate over one element of each list at a time (zip mode) # prediction is correct if actual Y value equals to predicted Y value correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j) # percentage of accuracy equals to number of correct predictions divided by number # of all data and multiplied by 100 return (correct / len(actual_y)) * 100 num = TypeVar("num") def valid_input( input_type: Callable[[object], num], # Usually float or int input_msg: str, err_msg: str, condition: Callable[[num], bool] = lambda x: True, default: str = None, ) -> num: """ Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input """ while True: try: user_input = input_type(input(input_msg).strip() or default) if condition(user_input): return user_input else: print(f"{user_input}: {err_msg}") continue except ValueError: print( f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" ) # Main Function def main(): """This function starts execution phase""" while True: print(" Linear Discriminant Analysis ".center(50, "*")) print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes n_classes = valid_input( input_type=int, condition=lambda x: x > 0, input_msg="Enter the number of classes (Data Groupings): ", err_msg="Number of classes should be positive!", ) print("-" * 100) # Trying to get the value of standard deviation std_dev = valid_input( input_type=float, condition=lambda x: x >= 0, input_msg=( "Enter the value of standard deviation" "(Default value is 1.0 for all classes): " ), err_msg="Standard deviation should not be negative!", default="1.0", ) print("-" * 100) # Trying to get number of instances in classes and theirs means to generate # dataset counts = [] # An empty list to store instance counts of classes in dataset for i in range(n_classes): user_count = valid_input( input_type=int, condition=lambda x: x > 0, input_msg=(f"Enter The number of instances for class_{i+1}: "), err_msg="Number of instances should be positive!", ) counts.append(user_count) print("-" * 100) # An empty list to store values of user-entered means of classes user_means = [] for a in range(n_classes): user_mean = valid_input( input_type=float, input_msg=(f"Enter the value of mean for class_{a+1}: "), err_msg="This is an invalid value.", ) user_means.append(user_mean) print("-" * 100) print("Standard deviation: ", std_dev) # print out the number of instances in classes in separated line for i, count in enumerate(counts, 1): print(f"Number of instances in class_{i} is: {count}") print("-" * 100) # print out mean values of classes separated line for i, user_mean in enumerate(user_means, 1): print(f"Mean of class_{i} is: {user_mean}") print("-" * 100) # Generating training dataset drawn from gaussian distribution x = [ gaussian_distribution(user_means[j], std_dev, counts[j]) for j in range(n_classes) ] print("Generated Normal Distribution: \n", x) print("-" * 100) # Generating Ys to detecting corresponding classes y = y_generator(n_classes, counts) print("Generated Corresponding Ys: \n", y) print("-" * 100) # Calculating the value of actual mean for each class actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)] # for loop iterates over number of elements in 'actual_means' list and print # out them in separated line for i, actual_mean in enumerate(actual_means, 1): print(f"Actual(Real) mean of class_{i} is: {actual_mean}") print("-" * 100) # Calculating the value of probabilities for each class probabilities = [ calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes) ] # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class variance = calculate_variance(x, actual_means, sum(counts)) print("Variance: ", variance) print("-" * 100) # Predicting Y values # storing predicted Y values in 'pre_indexes' variable pre_indexes = predict_y_values(x, actual_means, variance, probabilities) print("-" * 100) # Calculating Accuracy of the model print(f"Accuracy: {accuracy(y, pre_indexes)}") print("-" * 100) print(" DONE ".center(100, "+")) if input("Press any key to restart or 'q' for quit: ").strip().lower() == "q": print("\n" + "GoodBye!".center(100, "-") + "\n") break system("cls" if name == "nt" else "clear") if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import numpy as np import requests def collect_dataset(): """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get( "https://raw.githubusercontent.com/yashLadha/" + "The_Math_of_Intelligence/master/Week1/ADRvs" + "Rating.csv" ) lines = response.text.splitlines() data = [] for item in lines: item = item.split(",") data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print("At Iteration %d - Error is %.5f " % (i + 1, error)) return theta def main(): """ Driver function """ data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): print("%.5f" % (theta[0, i])) if __name__ == "__main__": main()
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import numpy as np import requests def collect_dataset(): """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get( "https://raw.githubusercontent.com/yashLadha/" + "The_Math_of_Intelligence/master/Week1/ADRvs" + "Rating.csv" ) lines = response.text.splitlines() data = [] for item in lines: item = item.split(",") data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print("At Iteration %d - Error is %.5f " % (i + 1, error)) return theta def main(): """Driver function""" data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): print("%.5f" % (theta[0, i])) if __name__ == "__main__": main()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """ Initialize a six sided dice """ self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def _str_(self): return "Fair Dice" def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for i in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def _str_(self): return "Fair Dice" def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for i in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import sys from abc import abstractmethod from collections import deque class LRUCache: """ Page Replacement Algorithm, Least Recently Used (LRU) Caching.""" dq_store = object() # Cache store of keys key_reference_map = object() # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache @abstractmethod def __init__(self, n: int): """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference_map = 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): """ 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_map: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference_map.remove(last_element) else: index_remove = 0 for idx, key in enumerate(self.dq_store): if key == x: index_remove = idx break self.dq_store.remove(index_remove) self.dq_store.appendleft(x) self.key_reference_map.add(x) def display(self): """ Prints all the elements in the store. """ for k in self.dq_store: print(k) if __name__ == "__main__": lru_cache = LRUCache(4) lru_cache.refer(1) lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer(1) lru_cache.refer(4) lru_cache.refer(5) lru_cache.display()
import sys from abc import abstractmethod from collections import deque class LRUCache: """Page Replacement Algorithm, Least Recently Used (LRU) Caching.""" dq_store = object() # Cache store of keys key_reference_map = object() # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache @abstractmethod def __init__(self, n: int): """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference_map = 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): """ 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_map: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference_map.remove(last_element) else: index_remove = 0 for idx, key in enumerate(self.dq_store): if key == x: index_remove = idx break self.dq_store.remove(index_remove) self.dq_store.appendleft(x) self.key_reference_map.add(x) def display(self): """ Prints all the elements in the store. """ for k in self.dq_store: print(k) if __name__ == "__main__": lru_cache = LRUCache(4) lru_cache.refer(1) lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer(1) lru_cache.refer(4) lru_cache.refer(5) lru_cache.display()
1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots can be perceived as tools for penalizing big errors. However, using appropriate metrics depends on the situations, and types of data """ # Mean Absolute Error def mae(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mae(predict,actual),decimals = 2) 0.67 >>> actual = [1,1,1];predict = [1,1,1] >>> mae(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = abs(predict - actual) score = difference.mean() return score # Mean Squared Error def mse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mse(predict,actual),decimals = 2) 1.33 >>> actual = [1,1,1];predict = [1,1,1] >>> mse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) score = square_diff.mean() return score # Root Mean Squared Error def rmse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(rmse(predict,actual),decimals = 2) 1.15 >>> actual = [1,1,1];predict = [1,1,1] >>> rmse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Root Mean Square Logarithmic Error def rmsle(predict, actual): """ Examples(rounded for precision): >>> actual = [10,10,30];predict = [10,2,30] >>> np.around(rmsle(predict,actual),decimals = 2) 0.75 >>> actual = [1,1,1];predict = [1,1,1] >>> rmsle(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) log_predict = np.log(predict + 1) log_actual = np.log(actual + 1) difference = log_predict - log_actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Mean Bias Deviation def mbd(predict, actual): """ This value is Negative, if the model underpredicts, positive, if it overpredicts. Example(rounded for precision): Here the model overpredicts >>> actual = [1,2,3];predict = [2,3,4] >>> np.around(mbd(predict,actual),decimals = 2) 50.0 Here the model underpredicts >>> actual = [1,2,3];predict = [0,1,1] >>> np.around(mbd(predict,actual),decimals = 2) -66.67 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual numerator = np.sum(difference) / len(predict) denumerator = np.sum(actual) / len(predict) # print(numerator, denumerator) score = float(numerator) / denumerator * 100 return score def manual_accuracy(predict, actual): return np.mean(np.array(actual) == np.array(predict))
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots can be perceived as tools for penalizing big errors. However, using appropriate metrics depends on the situations, and types of data """ # Mean Absolute Error def mae(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mae(predict,actual),decimals = 2) 0.67 >>> actual = [1,1,1];predict = [1,1,1] >>> mae(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = abs(predict - actual) score = difference.mean() return score # Mean Squared Error def mse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mse(predict,actual),decimals = 2) 1.33 >>> actual = [1,1,1];predict = [1,1,1] >>> mse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) score = square_diff.mean() return score # Root Mean Squared Error def rmse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(rmse(predict,actual),decimals = 2) 1.15 >>> actual = [1,1,1];predict = [1,1,1] >>> rmse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Root Mean Square Logarithmic Error def rmsle(predict, actual): """ Examples(rounded for precision): >>> actual = [10,10,30];predict = [10,2,30] >>> np.around(rmsle(predict,actual),decimals = 2) 0.75 >>> actual = [1,1,1];predict = [1,1,1] >>> rmsle(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) log_predict = np.log(predict + 1) log_actual = np.log(actual + 1) difference = log_predict - log_actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Mean Bias Deviation def mbd(predict, actual): """ This value is Negative, if the model underpredicts, positive, if it overpredicts. Example(rounded for precision): Here the model overpredicts >>> actual = [1,2,3];predict = [2,3,4] >>> np.around(mbd(predict,actual),decimals = 2) 50.0 Here the model underpredicts >>> actual = [1,2,3];predict = [0,1,1] >>> np.around(mbd(predict,actual),decimals = 2) -66.67 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual numerator = np.sum(difference) / len(predict) denumerator = np.sum(actual) / len(predict) # print(numerator, denumerator) score = float(numerator) / denumerator * 100 return score def manual_accuracy(predict, actual): return np.mean(np.array(actual) == np.array(predict))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In physics and astronomy, a gravitational N-body simulation is a simulation of a dynamical system of particles under the influence of gravity. The system consists of a number of bodies, each of which exerts a gravitational force on all other bodies. These forces are calculated using Newton's law of universal gravitation. The Euler method is used at each time-step to calculate the change in velocity and position brought about by these forces. Softening is used to prevent numerical divergences when a particle comes too close to another (and the force goes to infinity). (Description adapted from https://en.wikipedia.org/wiki/N-body_simulation ) (See also http://www.shodor.org/refdesk/Resources/Algorithms/EulersMethod/ ) """ from __future__ import annotations import random from matplotlib import animation from matplotlib import pyplot as plt class Body: def __init__( self, position_x: float, position_y: float, velocity_x: float, velocity_y: float, mass: float = 1.0, size: float = 1.0, color: str = "blue", ) -> None: """ The parameters "size" & "color" are not relevant for the simulation itself, they are only used for plotting. """ self.position_x = position_x self.position_y = position_y self.velocity_x = velocity_x self.velocity_y = velocity_y self.mass = mass self.size = size self.color = color @property def position(self) -> tuple[float, float]: return self.position_x, self.position_y @property def velocity(self) -> tuple[float, float]: return self.velocity_x, self.velocity_y def update_velocity( self, force_x: float, force_y: float, delta_time: float ) -> None: """ Euler algorithm for velocity >>> body_1 = Body(0.,0.,0.,0.) >>> body_1.update_velocity(1.,0.,1.) >>> body_1.velocity (1.0, 0.0) >>> body_1.update_velocity(1.,0.,1.) >>> body_1.velocity (2.0, 0.0) >>> body_2 = Body(0.,0.,5.,0.) >>> body_2.update_velocity(0.,-10.,10.) >>> body_2.velocity (5.0, -100.0) >>> body_2.update_velocity(0.,-10.,10.) >>> body_2.velocity (5.0, -200.0) """ self.velocity_x += force_x * delta_time self.velocity_y += force_y * delta_time def update_position(self, delta_time: float) -> None: """ Euler algorithm for position >>> body_1 = Body(0.,0.,1.,0.) >>> body_1.update_position(1.) >>> body_1.position (1.0, 0.0) >>> body_1.update_position(1.) >>> body_1.position (2.0, 0.0) >>> body_2 = Body(10.,10.,0.,-2.) >>> body_2.update_position(1.) >>> body_2.position (10.0, 8.0) >>> body_2.update_position(1.) >>> body_2.position (10.0, 6.0) """ self.position_x += self.velocity_x * delta_time self.position_y += self.velocity_y * delta_time class BodySystem: """ This class is used to hold the bodies, the gravitation constant, the time factor and the softening factor. The time factor is used to control the speed of the simulation. The softening factor is used for softening, a numerical trick for N-body simulations to prevent numerical divergences when two bodies get too close to each other. """ def __init__( self, bodies: list[Body], gravitation_constant: float = 1.0, time_factor: float = 1.0, softening_factor: float = 0.0, ) -> None: self.bodies = bodies self.gravitation_constant = gravitation_constant self.time_factor = time_factor self.softening_factor = softening_factor def __len__(self) -> int: return len(self.bodies) def update_system(self, delta_time: float) -> None: """ For each body, loop through all other bodies to calculate the total force they exert on it. Use that force to update the body's velocity. >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) >>> len(body_system_1) 2 >>> body_system_1.update_system(1) >>> body_system_1.bodies[0].position (0.01, 0.0) >>> body_system_1.bodies[0].velocity (0.01, 0.0) >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) >>> body_system_2.update_system(1) >>> body_system_2.bodies[0].position (-9.0, 0.0) >>> body_system_2.bodies[0].velocity (0.1, 0.0) """ for body1 in self.bodies: force_x = 0.0 force_y = 0.0 for body2 in self.bodies: if body1 != body2: dif_x = body2.position_x - body1.position_x dif_y = body2.position_y - body1.position_y # Calculation of the distance using Pythagoras's theorem # Extra factor due to the softening technique distance = (dif_x ** 2 + dif_y ** 2 + self.softening_factor) ** ( 1 / 2 ) # Newton's law of universal gravitation. force_x += ( self.gravitation_constant * body2.mass * dif_x / distance ** 3 ) force_y += ( self.gravitation_constant * body2.mass * dif_y / distance ** 3 ) # Update the body's velocity once all the force components have been added body1.update_velocity(force_x, force_y, delta_time * self.time_factor) # Update the positions only after all the velocities have been updated for body in self.bodies: body.update_position(delta_time * self.time_factor) def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: """ Updates the body-system and applies the change to the patch-list used for plotting >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) >>> patches_1 = [plt.Circle((body.position_x, body.position_y), body.size, ... fc=body.color)for body in body_system_1.bodies] #doctest: +ELLIPSIS >>> update_step(body_system_1, 1, patches_1) >>> patches_1[0].center (0.01, 0.0) >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) >>> patches_2 = [plt.Circle((body.position_x, body.position_y), body.size, ... fc=body.color)for body in body_system_2.bodies] #doctest: +ELLIPSIS >>> update_step(body_system_2, 1, patches_2) >>> patches_2[0].center (-9.0, 0.0) """ # Update the positions of the bodies body_system.update_system(delta_time) # Update the positions of the patches for patch, body in zip(patches, body_system.bodies): patch.center = (body.position_x, body.position_y) def plot( title: str, body_system: BodySystem, x_start: float = -1, x_end: float = 1, y_start: float = -1, y_end: float = 1, ) -> None: """ Utility function to plot how the given body-system evolves over time. No doctest provided since this function does not have a return value. """ INTERVAL = 20 # Frame rate of the animation DELTA_TIME = INTERVAL / 1000 # Time between time steps in seconds fig = plt.figure() fig.canvas.set_window_title(title) ax = plt.axes( xlim=(x_start, x_end), ylim=(y_start, y_end) ) # Set section to be plotted plt.gca().set_aspect("equal") # Fix aspect ratio # Each body is drawn as a patch by the plt-function patches = [ plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) for body in body_system.bodies ] for patch in patches: ax.add_patch(patch) # Function called at each step of the animation def update(frame: int) -> list[plt.Circle]: update_step(body_system, DELTA_TIME, patches) return patches anim = animation.FuncAnimation( # noqa: F841 fig, update, interval=INTERVAL, blit=True ) plt.show() def example_1() -> BodySystem: """ Example 1: figure-8 solution to the 3-body-problem This example can be seen as a test of the implementation: given the right initial conditions, the bodies should move in a figure-8. (initial conditions taken from http://www.artcompsci.org/vol_1/v1_web/node56.html) >>> body_system = example_1() >>> len(body_system) 3 """ position_x = 0.9700436 position_y = -0.24308753 velocity_x = 0.466203685 velocity_y = 0.43236573 bodies1 = [ Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), ] return BodySystem(bodies1, time_factor=3) def example_2() -> BodySystem: """ Example 2: Moon's orbit around the earth This example can be seen as a test of the implementation: given the right initial conditions, the moon should orbit around the earth as it actually does. (mass, velocity and distance taken from https://en.wikipedia.org/wiki/Earth and https://en.wikipedia.org/wiki/Moon) No doctest provided since this function does not have a return value. """ moon_mass = 7.3476e22 earth_mass = 5.972e24 velocity_dif = 1022 earth_moon_distance = 384399000 gravitation_constant = 6.674e-11 # Calculation of the respective velocities so that total impulse is zero, # i.e. the two bodies together don't move moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) earth_velocity = moon_velocity - velocity_dif moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) def example_3() -> BodySystem: """ Example 3: Random system with many bodies. No doctest provided since this function does not have a return value. """ bodies = [] for i in range(10): velocity_x = random.uniform(-0.5, 0.5) velocity_y = random.uniform(-0.5, 0.5) # Bodies are created pairwise with opposite velocities so that the # total impulse remains zero bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), velocity_x, velocity_y, size=0.05, ) ) bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), -velocity_x, -velocity_y, size=0.05, ) ) return BodySystem(bodies, 0.01, 10, 0.1) if __name__ == "__main__": plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) plot( "Moon's orbit around the earth", example_2(), -430000000, 430000000, -430000000, 430000000, ) plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
""" In physics and astronomy, a gravitational N-body simulation is a simulation of a dynamical system of particles under the influence of gravity. The system consists of a number of bodies, each of which exerts a gravitational force on all other bodies. These forces are calculated using Newton's law of universal gravitation. The Euler method is used at each time-step to calculate the change in velocity and position brought about by these forces. Softening is used to prevent numerical divergences when a particle comes too close to another (and the force goes to infinity). (Description adapted from https://en.wikipedia.org/wiki/N-body_simulation ) (See also http://www.shodor.org/refdesk/Resources/Algorithms/EulersMethod/ ) """ from __future__ import annotations import random from matplotlib import animation from matplotlib import pyplot as plt class Body: def __init__( self, position_x: float, position_y: float, velocity_x: float, velocity_y: float, mass: float = 1.0, size: float = 1.0, color: str = "blue", ) -> None: """ The parameters "size" & "color" are not relevant for the simulation itself, they are only used for plotting. """ self.position_x = position_x self.position_y = position_y self.velocity_x = velocity_x self.velocity_y = velocity_y self.mass = mass self.size = size self.color = color @property def position(self) -> tuple[float, float]: return self.position_x, self.position_y @property def velocity(self) -> tuple[float, float]: return self.velocity_x, self.velocity_y def update_velocity( self, force_x: float, force_y: float, delta_time: float ) -> None: """ Euler algorithm for velocity >>> body_1 = Body(0.,0.,0.,0.) >>> body_1.update_velocity(1.,0.,1.) >>> body_1.velocity (1.0, 0.0) >>> body_1.update_velocity(1.,0.,1.) >>> body_1.velocity (2.0, 0.0) >>> body_2 = Body(0.,0.,5.,0.) >>> body_2.update_velocity(0.,-10.,10.) >>> body_2.velocity (5.0, -100.0) >>> body_2.update_velocity(0.,-10.,10.) >>> body_2.velocity (5.0, -200.0) """ self.velocity_x += force_x * delta_time self.velocity_y += force_y * delta_time def update_position(self, delta_time: float) -> None: """ Euler algorithm for position >>> body_1 = Body(0.,0.,1.,0.) >>> body_1.update_position(1.) >>> body_1.position (1.0, 0.0) >>> body_1.update_position(1.) >>> body_1.position (2.0, 0.0) >>> body_2 = Body(10.,10.,0.,-2.) >>> body_2.update_position(1.) >>> body_2.position (10.0, 8.0) >>> body_2.update_position(1.) >>> body_2.position (10.0, 6.0) """ self.position_x += self.velocity_x * delta_time self.position_y += self.velocity_y * delta_time class BodySystem: """ This class is used to hold the bodies, the gravitation constant, the time factor and the softening factor. The time factor is used to control the speed of the simulation. The softening factor is used for softening, a numerical trick for N-body simulations to prevent numerical divergences when two bodies get too close to each other. """ def __init__( self, bodies: list[Body], gravitation_constant: float = 1.0, time_factor: float = 1.0, softening_factor: float = 0.0, ) -> None: self.bodies = bodies self.gravitation_constant = gravitation_constant self.time_factor = time_factor self.softening_factor = softening_factor def __len__(self) -> int: return len(self.bodies) def update_system(self, delta_time: float) -> None: """ For each body, loop through all other bodies to calculate the total force they exert on it. Use that force to update the body's velocity. >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) >>> len(body_system_1) 2 >>> body_system_1.update_system(1) >>> body_system_1.bodies[0].position (0.01, 0.0) >>> body_system_1.bodies[0].velocity (0.01, 0.0) >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) >>> body_system_2.update_system(1) >>> body_system_2.bodies[0].position (-9.0, 0.0) >>> body_system_2.bodies[0].velocity (0.1, 0.0) """ for body1 in self.bodies: force_x = 0.0 force_y = 0.0 for body2 in self.bodies: if body1 != body2: dif_x = body2.position_x - body1.position_x dif_y = body2.position_y - body1.position_y # Calculation of the distance using Pythagoras's theorem # Extra factor due to the softening technique distance = (dif_x ** 2 + dif_y ** 2 + self.softening_factor) ** ( 1 / 2 ) # Newton's law of universal gravitation. force_x += ( self.gravitation_constant * body2.mass * dif_x / distance ** 3 ) force_y += ( self.gravitation_constant * body2.mass * dif_y / distance ** 3 ) # Update the body's velocity once all the force components have been added body1.update_velocity(force_x, force_y, delta_time * self.time_factor) # Update the positions only after all the velocities have been updated for body in self.bodies: body.update_position(delta_time * self.time_factor) def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: """ Updates the body-system and applies the change to the patch-list used for plotting >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) >>> patches_1 = [plt.Circle((body.position_x, body.position_y), body.size, ... fc=body.color)for body in body_system_1.bodies] #doctest: +ELLIPSIS >>> update_step(body_system_1, 1, patches_1) >>> patches_1[0].center (0.01, 0.0) >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) >>> patches_2 = [plt.Circle((body.position_x, body.position_y), body.size, ... fc=body.color)for body in body_system_2.bodies] #doctest: +ELLIPSIS >>> update_step(body_system_2, 1, patches_2) >>> patches_2[0].center (-9.0, 0.0) """ # Update the positions of the bodies body_system.update_system(delta_time) # Update the positions of the patches for patch, body in zip(patches, body_system.bodies): patch.center = (body.position_x, body.position_y) def plot( title: str, body_system: BodySystem, x_start: float = -1, x_end: float = 1, y_start: float = -1, y_end: float = 1, ) -> None: """ Utility function to plot how the given body-system evolves over time. No doctest provided since this function does not have a return value. """ INTERVAL = 20 # Frame rate of the animation DELTA_TIME = INTERVAL / 1000 # Time between time steps in seconds fig = plt.figure() fig.canvas.set_window_title(title) ax = plt.axes( xlim=(x_start, x_end), ylim=(y_start, y_end) ) # Set section to be plotted plt.gca().set_aspect("equal") # Fix aspect ratio # Each body is drawn as a patch by the plt-function patches = [ plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) for body in body_system.bodies ] for patch in patches: ax.add_patch(patch) # Function called at each step of the animation def update(frame: int) -> list[plt.Circle]: update_step(body_system, DELTA_TIME, patches) return patches anim = animation.FuncAnimation( # noqa: F841 fig, update, interval=INTERVAL, blit=True ) plt.show() def example_1() -> BodySystem: """ Example 1: figure-8 solution to the 3-body-problem This example can be seen as a test of the implementation: given the right initial conditions, the bodies should move in a figure-8. (initial conditions taken from http://www.artcompsci.org/vol_1/v1_web/node56.html) >>> body_system = example_1() >>> len(body_system) 3 """ position_x = 0.9700436 position_y = -0.24308753 velocity_x = 0.466203685 velocity_y = 0.43236573 bodies1 = [ Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), ] return BodySystem(bodies1, time_factor=3) def example_2() -> BodySystem: """ Example 2: Moon's orbit around the earth This example can be seen as a test of the implementation: given the right initial conditions, the moon should orbit around the earth as it actually does. (mass, velocity and distance taken from https://en.wikipedia.org/wiki/Earth and https://en.wikipedia.org/wiki/Moon) No doctest provided since this function does not have a return value. """ moon_mass = 7.3476e22 earth_mass = 5.972e24 velocity_dif = 1022 earth_moon_distance = 384399000 gravitation_constant = 6.674e-11 # Calculation of the respective velocities so that total impulse is zero, # i.e. the two bodies together don't move moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) earth_velocity = moon_velocity - velocity_dif moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") return BodySystem([earth, moon], gravitation_constant, time_factor=1000000) def example_3() -> BodySystem: """ Example 3: Random system with many bodies. No doctest provided since this function does not have a return value. """ bodies = [] for i in range(10): velocity_x = random.uniform(-0.5, 0.5) velocity_y = random.uniform(-0.5, 0.5) # Bodies are created pairwise with opposite velocities so that the # total impulse remains zero bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), velocity_x, velocity_y, size=0.05, ) ) bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), -velocity_x, -velocity_y, size=0.05, ) ) return BodySystem(bodies, 0.01, 10, 0.1) if __name__ == "__main__": plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) plot( "Moon's orbit around the earth", example_2(), -430000000, 430000000, -430000000, 430000000, ) plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" * Binary Exponentiation for Powers * This is a method to find a^b in a time complexity of O(log b) * This is one of the most commonly used methods of finding powers. * Also useful in cases where solution to (a^b)%c is required, * where a,b,c can be numbers over the computers calculation limits. * Done using iteration, can also be done using recursion * @author chinmoy159 * @version 1.0 dated 10/08/2017 """ def b_expo(a, b): res = 1 while b > 0: if b & 1: res *= a a *= a b >>= 1 return res def b_expo_mod(a, b, c): res = 1 while b > 0: if b & 1: res = ((res % c) * (a % c)) % c a *= a b >>= 1 return res """ * Wondering how this method works ! * It's pretty simple. * Let's say you need to calculate a ^ b * RULE 1 : a ^ b = (a*a) ^ (b/2) ---- example : 4 ^ 4 = (4*4) ^ (4/2) = 16 ^ 2 * RULE 2 : IF b is ODD, then ---- a ^ b = a * (a ^ (b - 1)) :: where (b - 1) is even. * Once b is even, repeat the process to get a ^ b * Repeat the process till b = 1 OR b = 0, because a^1 = a AND a^0 = 1 * * As far as the modulo is concerned, * the fact : (a*b) % c = ((a%c) * (b%c)) % c * Now apply RULE 1 OR 2 whichever is required. """
""" * Binary Exponentiation for Powers * This is a method to find a^b in a time complexity of O(log b) * This is one of the most commonly used methods of finding powers. * Also useful in cases where solution to (a^b)%c is required, * where a,b,c can be numbers over the computers calculation limits. * Done using iteration, can also be done using recursion * @author chinmoy159 * @version 1.0 dated 10/08/2017 """ def b_expo(a, b): res = 1 while b > 0: if b & 1: res *= a a *= a b >>= 1 return res def b_expo_mod(a, b, c): res = 1 while b > 0: if b & 1: res = ((res % c) * (a % c)) % c a *= a b >>= 1 return res """ * Wondering how this method works ! * It's pretty simple. * Let's say you need to calculate a ^ b * RULE 1 : a ^ b = (a*a) ^ (b/2) ---- example : 4 ^ 4 = (4*4) ^ (4/2) = 16 ^ 2 * RULE 2 : IF b is ODD, then ---- a ^ b = a * (a ^ (b - 1)) :: where (b - 1) is even. * Once b is even, repeat the process to get a ^ b * Repeat the process till b = 1 OR b = 0, because a^1 = a AND a^0 = 1 * * As far as the modulo is concerned, * the fact : (a*b) % c = ((a%c) * (b%c)) % c * Now apply RULE 1 OR 2 whichever is required. """
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection): """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = 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(shell_sort(unsorted))
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection): """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = 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(shell_sort(unsorted))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np def explicit_euler(ode_func, y0, x0, step_size, x_end): """ Calculate numeric solution at each step to an ODE using Euler's Method https://en.wikipedia.org/wiki/Euler_method Arguments: ode_func -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x stepsize -- the increment value for x x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
import numpy as np def explicit_euler(ode_func, y0, x0, step_size, x_end): """ Calculate numeric solution at each step to an ODE using Euler's Method https://en.wikipedia.org/wiki/Euler_method Arguments: ode_func -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x stepsize -- the increment value for x x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import requests from bs4 import BeautifulSoup def imdb_top(imdb_top_n): base_url = ( f"https://www.imdb.com/search/title?title_type=" f"feature&sort=num_votes,desc&count={imdb_top_n}" ) source = BeautifulSoup(requests.get(base_url).content, "html.parser") for m in source.findAll("div", class_="lister-item mode-advanced"): print("\n" + m.h3.a.text) # movie's name print(m.find("span", attrs={"class": "genre"}).text) # genre print(m.strong.text) # movie's rating print(f"https://www.imdb.com{m.a.get('href')}") # movie's page link print("*" * 40) if __name__ == "__main__": imdb_top(input("How many movies would you like to see? "))
import requests from bs4 import BeautifulSoup def imdb_top(imdb_top_n): base_url = ( f"https://www.imdb.com/search/title?title_type=" f"feature&sort=num_votes,desc&count={imdb_top_n}" ) source = BeautifulSoup(requests.get(base_url).content, "html.parser") for m in source.findAll("div", class_="lister-item mode-advanced"): print("\n" + m.h3.a.text) # movie's name print(m.find("span", attrs={"class": "genre"}).text) # genre print(m.strong.text) # movie's rating print(f"https://www.imdb.com{m.a.get('href')}") # movie's page link print("*" * 40) if __name__ == "__main__": imdb_top(input("How many movies would you like to see? "))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import deque if __name__ == "__main__": # Accept No. of Nodes and edges n, m = map(int, input().split(" ")) # Initialising Dictionary of edges g = {} for i in range(n): g[i + 1] = [] """ ---------------------------------------------------------------------------- Accepting edges of Unweighted Directed Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y = map(int, input().strip().split(" ")) g[x].append(y) """ ---------------------------------------------------------------------------- Accepting edges of Unweighted Undirected Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y = map(int, input().strip().split(" ")) g[x].append(y) g[y].append(x) """ ---------------------------------------------------------------------------- Accepting edges of Weighted Undirected Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y, r = map(int, input().strip().split(" ")) g[x].append([y, r]) g[y].append([x, r]) """ -------------------------------------------------------------------------------- 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 i 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 i 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 if __name__ == "__main__": # Accept No. of Nodes and edges n, m = map(int, input().split(" ")) # Initialising Dictionary of edges g = {} for i in range(n): g[i + 1] = [] """ ---------------------------------------------------------------------------- Accepting edges of Unweighted Directed Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y = map(int, input().strip().split(" ")) g[x].append(y) """ ---------------------------------------------------------------------------- Accepting edges of Unweighted Undirected Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y = map(int, input().strip().split(" ")) g[x].append(y) g[y].append(x) """ ---------------------------------------------------------------------------- Accepting edges of Weighted Undirected Graphs ---------------------------------------------------------------------------- """ for _ in range(m): x, y, r = map(int, input().strip().split(" ")) g[x].append([y, r]) g[y].append([x, r]) """ -------------------------------------------------------------------------------- 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 i 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 i 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
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}" def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print(f"======= Iteration {i + 1} =======") for j, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( [ranks[ib] / outbounds[ib] for ib in node.inbound] ) print(ranks) def main(): names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == "__main__": main()
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}" def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print(f"======= Iteration {i + 1} =======") for j, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( [ranks[ib] / outbounds[ib] for ib in node.inbound] ) print(ranks) def main(): names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial f(x) at specified point x and return the value. Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ return sum(c * (x ** i) for i, c in enumerate(poly)) def horner(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial at specified point using Horner's method. In terms of computational complexity, Horner's method is an efficient method of evaluating a polynomial. It avoids the use of expensive exponentiation, and instead uses only multiplication and addition to evaluate the polynomial in O(n), where n is the degree of the polynomial. https://en.wikipedia.org/wiki/Horner's_method Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ result = 0.0 for coeff in reversed(poly): result = result * x + coeff return result if __name__ == "__main__": """ Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2 >>> x = -13.0 >>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9 >>> print(evaluate_poly(poly, x)) 180339.9 """ poly = (0.0, 0.0, 5.0, 9.3, 7.0) x = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
from typing import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial f(x) at specified point x and return the value. Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ return sum(c * (x ** i) for i, c in enumerate(poly)) def horner(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial at specified point using Horner's method. In terms of computational complexity, Horner's method is an efficient method of evaluating a polynomial. It avoids the use of expensive exponentiation, and instead uses only multiplication and addition to evaluate the polynomial in O(n), where n is the degree of the polynomial. https://en.wikipedia.org/wiki/Horner's_method Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ result = 0.0 for coeff in reversed(poly): result = result * x + coeff return result if __name__ == "__main__": """ Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2 >>> x = -13.0 >>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9 >>> print(evaluate_poly(poly, x)) 180339.9 """ poly = (0.0, 0.0, 5.0, 9.3, 7.0) x = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def largest_product(grid): nColumns = len(grid[0]) nRows = len(grid) largest = 0 lrDiagProduct = 0 rlDiagProduct = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(nColumns): for j in range(nRows - 3): vertProduct = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] horzProduct = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < nColumns - 3: lrDiagProduct = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: rlDiagProduct = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) maxProduct = max(vertProduct, horzProduct, lrDiagProduct, rlDiagProduct) if maxProduct > largest: largest = maxProduct return largest def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ grid = [] with open(os.path.dirname(__file__) + "/grid.txt") as file: for line in file: grid.append(line.strip("\n").split(" ")) grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) if __name__ == "__main__": print(solution())
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def largest_product(grid): nColumns = len(grid[0]) nRows = len(grid) largest = 0 lrDiagProduct = 0 rlDiagProduct = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(nColumns): for j in range(nRows - 3): vertProduct = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] horzProduct = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < nColumns - 3: lrDiagProduct = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: rlDiagProduct = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) maxProduct = max(vertProduct, horzProduct, lrDiagProduct, rlDiagProduct) if maxProduct > largest: largest = maxProduct return largest def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ grid = [] with open(os.path.dirname(__file__) + "/grid.txt") as file: for line in file: grid.append(line.strip("\n").split(" ")) grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Segmented Sieve.""" import math def sieve(n): """Segmented Sieve.""" in_prime = [] start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] while start <= end: if temp[start] is True: in_prime.append(start) for i in range(start * start, end + 1, start): if temp[i] is True: temp[i] = False start += 1 prime += in_prime low = end + 1 high = low + end - 1 if high > n: high = n while low <= n: temp = [True] * (high - low + 1) for each in in_prime: t = math.floor(low / each) * each if t < low: t += each for j in range(t, high + 1, each): temp[j - low] = False for j in range(len(temp)): if temp[j] is True: prime.append(j + low) low = high + 1 high = low + end - 1 if high > n: high = n return prime print(sieve(10 ** 6))
"""Segmented Sieve.""" import math def sieve(n): """Segmented Sieve.""" in_prime = [] start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] while start <= end: if temp[start] is True: in_prime.append(start) for i in range(start * start, end + 1, start): if temp[i] is True: temp[i] = False start += 1 prime += in_prime low = end + 1 high = low + end - 1 if high > n: high = n while low <= n: temp = [True] * (high - low + 1) for each in in_prime: t = math.floor(low / each) * each if t < low: t += each for j in range(t, high + 1, each): temp[j - low] = False for j in range(len(temp)): if temp[j] is True: prime.append(j + low) low = high + 1 high = low + end - 1 if high > n: high = n return prime print(sieve(10 ** 6))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 36 https://projecteuler.net/problem=36 Problem Statement: Double-base palindromes Problem 36 The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ from typing import Union def is_palindrome(n: Union[int, str]) -> bool: """ Return true if the input n is a palindrome. Otherwise return false. n can be an integer or a string. >>> is_palindrome(909) True >>> is_palindrome(908) False >>> is_palindrome('10101') True >>> is_palindrome('10111') False """ n = str(n) return True if n == n[::-1] else False def solution(n: int = 1000000): """Return the sum of all numbers, less than n , which are palindromic in base 10 and base 2. >>> solution(1000000) 872187 >>> solution(500000) 286602 >>> solution(100000) 286602 >>> solution(1000) 1772 >>> solution(100) 157 >>> solution(10) 25 >>> solution(2) 1 >>> solution(1) 0 """ total = 0 for i in range(1, n): if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
""" Project Euler Problem 36 https://projecteuler.net/problem=36 Problem Statement: Double-base palindromes Problem 36 The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ from typing import Union def is_palindrome(n: Union[int, str]) -> bool: """ Return true if the input n is a palindrome. Otherwise return false. n can be an integer or a string. >>> is_palindrome(909) True >>> is_palindrome(908) False >>> is_palindrome('10101') True >>> is_palindrome('10111') False """ n = str(n) return True if n == n[::-1] else False def solution(n: int = 1000000): """Return the sum of all numbers, less than n , which are palindromic in base 10 and base 2. >>> solution(1000000) 872187 >>> solution(500000) 286602 >>> solution(100000) 286602 >>> solution(1000) 1772 >>> solution(100) 157 >>> solution(10) 25 >>> solution(2) 1 >>> solution(1) 0 """ total = 0 for i in range(1, n): if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a and c(dABCd) -> remove d (ABC) """ def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
""" https://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a and c(dABCd) -> remove d (ABC) """ def abbr(a: str, b: str) -> bool: """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Tuple def diophantine(a: int, b: int, c: int) -> Tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
from typing import Tuple def diophantine(a: int, b: int, c: int) -> Tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b def extended_gcd(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected]) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_nama <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size): canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas): for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas): """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(canvas.shape[0])) for r, row in enumerate(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) next_gen_canvas[r][c] = __judge_point( pt, canvas[r - 1 : r + 2, c - 1 : c + 2] ) canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return canvas.tolist() def __judge_point(pt, neighbours): dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive == 2 or alive == 3: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
"""Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected]) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_nama <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size): canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas): for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas): """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(canvas.shape[0])) for r, row in enumerate(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) next_gen_canvas[r][c] = __judge_point( pt, canvas[r - 1 : r + 2, c - 1 : c + 2] ) canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return canvas.tolist() def __judge_point(pt, neighbours): dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive == 2 or alive == 3: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(S, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in S: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(S, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in S: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" One of the several implementations of Lempel–Ziv–Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict, curr_string: str, index: int, last_match_id: str ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
""" One of the several implementations of Lempel–Ziv–Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict, curr_string: str, index: int, last_match_id: str ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel–Ziv–Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Created by sarathkaul on 12/11/19 import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: # fetching a list of articles in json format bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
# Created by sarathkaul on 12/11/19 import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: # fetching a list of articles in json format bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from typing import Optional def slowsort( sequence: list, start: Optional[int] = None, end: Optional[int] = None ) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from typing import Optional def slowsort( sequence: list, start: Optional[int] = None, end: Optional[int] = None ) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: raise TypeError(f"Unsupported type given for another ({type(another)})") def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") def test2(): import doctest doctest.testmod() test2()
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: raise TypeError(f"Unsupported type given for another ({type(another)})") def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") def test2(): import doctest doctest.testmod() test2()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 72: https://projecteuler.net/problem=72 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 there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? """ def solution(limit: int = 1000000) -> int: """ Return the number of reduced proper fractions with denominator less than limit. >>> solution(8) 21 >>> solution(1000) 304191 """ primes = set(range(3, limit, 2)) primes.add(2) for p in range(3, limit, 2): if p not in primes: continue primes.difference_update(set(range(p * p, limit, p))) phi = [float(n) for n in range(limit + 1)] for p in primes: for n in range(p, limit + 1, p): phi[n] *= 1 - 1 / p return int(sum(phi[2:])) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 72: https://projecteuler.net/problem=72 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 there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? """ def solution(limit: int = 1000000) -> int: """ Return the number of reduced proper fractions with denominator less than limit. >>> solution(8) 21 >>> solution(1000) 304191 """ primes = set(range(3, limit, 2)) primes.add(2) for p in range(3, limit, 2): if p not in primes: continue primes.difference_update(set(range(p * p, limit, p))) phi = [float(n) for n in range(limit + 1)] for p in primes: for n in range(p, limit + 1, p): phi[n] *= 1 - 1 / p return int(sum(phi[2:])) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ import numpy # List of input, output pairs train_data = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) test_data = (((515, 22, 13), 555), ((61, 35, 49), 150)) parameter_vector = [2, 4, 1, 5] m = len(train_data) LEARNING_RATE = 0.009 def _error(example_no, data_set="train"): """ :param data_set: train data or test data :param example_no: example number whose error has to be checked :return: error in example pointed by example number. """ return calculate_hypothesis_value(example_no, data_set) - output( example_no, data_set ) def _hypothesis_value(data_input_tuple): """ Calculates hypothesis function value for a given input :param data_input_tuple: Input tuple of a particular example :return: Value of hypothesis function at that point. Note that there is an 'biased input' whose value is fixed as 1. It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it. """ hyp_val = 0 for i in range(len(parameter_vector) - 1): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def output(example_no, data_set): """ :param data_set: test data or train data :param example_no: example whose output is to be fetched :return: output for that example """ if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] def calculate_hypothesis_value(example_no, data_set): """ Calculates hypothesis value for a given example :param data_set: test data or train_data :param example_no: example whose hypothesis value is to be calculated :return: hypothesis value for that example """ if data_set == "train": return _hypothesis_value(train_data[example_no][0]) elif data_set == "test": return _hypothesis_value(test_data[example_no][0]) def summation_of_cost_derivative(index, end=m): """ Calculates the sum of cost function derivative :param index: index wrt derivative is being calculated :param end: value where summation ends, default is m, number of examples :return: Returns the summation of cost derivative Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ summation_value = 0 for i in range(end): if index == -1: summation_value += _error(i) else: summation_value += _error(i) * train_data[i][0][index] return summation_value def get_cost_derivative(index): """ :param index: index of the parameter vector wrt to derivative is to be calculated :return: derivative wrt to that index Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ cost_derivative_value = summation_of_cost_derivative(index, m) / m return cost_derivative_value def run_gradient_descent(): global parameter_vector # Tune these values to set a tolerance value for predicted output absolute_error_limit = 0.000002 relative_error_limit = 0 j = 0 while True: j += 1 temp_parameter_vector = [0, 0, 0, 0] for i in range(0, len(parameter_vector)): cost_derivative = get_cost_derivative(i - 1) temp_parameter_vector[i] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( parameter_vector, temp_parameter_vector, atol=absolute_error_limit, rtol=relative_error_limit, ): break parameter_vector = temp_parameter_vector print(("Number of iterations:", j)) def test_gradient_descent(): for i in range(len(test_data)): print(("Actual output value:", output(i, "test"))) print(("Hypothesis output:", calculate_hypothesis_value(i, "test"))) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
""" Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ import numpy # List of input, output pairs train_data = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) test_data = (((515, 22, 13), 555), ((61, 35, 49), 150)) parameter_vector = [2, 4, 1, 5] m = len(train_data) LEARNING_RATE = 0.009 def _error(example_no, data_set="train"): """ :param data_set: train data or test data :param example_no: example number whose error has to be checked :return: error in example pointed by example number. """ return calculate_hypothesis_value(example_no, data_set) - output( example_no, data_set ) def _hypothesis_value(data_input_tuple): """ Calculates hypothesis function value for a given input :param data_input_tuple: Input tuple of a particular example :return: Value of hypothesis function at that point. Note that there is an 'biased input' whose value is fixed as 1. It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it. """ hyp_val = 0 for i in range(len(parameter_vector) - 1): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def output(example_no, data_set): """ :param data_set: test data or train data :param example_no: example whose output is to be fetched :return: output for that example """ if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] def calculate_hypothesis_value(example_no, data_set): """ Calculates hypothesis value for a given example :param data_set: test data or train_data :param example_no: example whose hypothesis value is to be calculated :return: hypothesis value for that example """ if data_set == "train": return _hypothesis_value(train_data[example_no][0]) elif data_set == "test": return _hypothesis_value(test_data[example_no][0]) def summation_of_cost_derivative(index, end=m): """ Calculates the sum of cost function derivative :param index: index wrt derivative is being calculated :param end: value where summation ends, default is m, number of examples :return: Returns the summation of cost derivative Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ summation_value = 0 for i in range(end): if index == -1: summation_value += _error(i) else: summation_value += _error(i) * train_data[i][0][index] return summation_value def get_cost_derivative(index): """ :param index: index of the parameter vector wrt to derivative is to be calculated :return: derivative wrt to that index Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ cost_derivative_value = summation_of_cost_derivative(index, m) / m return cost_derivative_value def run_gradient_descent(): global parameter_vector # Tune these values to set a tolerance value for predicted output absolute_error_limit = 0.000002 relative_error_limit = 0 j = 0 while True: j += 1 temp_parameter_vector = [0, 0, 0, 0] for i in range(0, len(parameter_vector)): cost_derivative = get_cost_derivative(i - 1) temp_parameter_vector[i] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( parameter_vector, temp_parameter_vector, atol=absolute_error_limit, rtol=relative_error_limit, ): break parameter_vector = temp_parameter_vector print(("Number of iterations:", j)) def test_gradient_descent(): for i in range(len(test_data)): print(("Actual output value:", output(i, "test"))) print(("Hypothesis output:", calculate_hypothesis_value(i, "test"))) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/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
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Combinatoric selections Problem 53 There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation, 5C3 = 10. In general, nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1. It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million? """ from math import factorial def combinations(n, r): return factorial(n) / (factorial(r) * factorial(n - r)) def solution(): """Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than one-million >>> solution() 4075 """ total = 0 for i in range(1, 101): for j in range(1, i + 1): if combinations(i, j) > 1e6: total += 1 return total if __name__ == "__main__": print(solution())
""" Combinatoric selections Problem 53 There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation, 5C3 = 10. In general, nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1. It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million? """ from math import factorial def combinations(n, r): return factorial(n) / (factorial(r) * factorial(n - r)) def solution(): """Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than one-million >>> solution() 4075 """ total = 0 for i in range(1, 101): for j in range(1, i + 1): if combinations(i, j) > 1e6: total += 1 return total if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author: 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
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Newton's Method.""" # Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method from typing import Callable RealFunc = Callable[[float], float] # type alias for a real -> real function # function is the f(x) and derivative is the f'(x) def newton( function: RealFunc, derivative: RealFunc, starting_int: int, ) -> float: """ >>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3) 2.0945514815423474 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2) 1.0 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4) 1.0000000000000102 >>> import math >>> newton(math.sin, math.cos, 1) 0.0 >>> newton(math.sin, math.cos, 2) 3.141592653589793 >>> newton(math.cos, lambda x: -math.sin(x), 2) 1.5707963267948966 >>> newton(math.cos, lambda x: -math.sin(x), 0) Traceback (most recent call last): ... ZeroDivisionError: Could not find root """ prev_guess = float(starting_int) while True: try: next_guess = prev_guess - function(prev_guess) / derivative(prev_guess) except ZeroDivisionError: raise ZeroDivisionError("Could not find root") from None if abs(prev_guess - next_guess) < 10 ** -5: return next_guess prev_guess = next_guess def f(x: float) -> float: return (x ** 3) - (2 * x) - 5 def f1(x: float) -> float: return 3 * (x ** 2) - 2 if __name__ == "__main__": print(newton(f, f1, 3))
"""Newton's Method.""" # Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method from typing import Callable RealFunc = Callable[[float], float] # type alias for a real -> real function # function is the f(x) and derivative is the f'(x) def newton( function: RealFunc, derivative: RealFunc, starting_int: int, ) -> float: """ >>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3) 2.0945514815423474 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2) 1.0 >>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4) 1.0000000000000102 >>> import math >>> newton(math.sin, math.cos, 1) 0.0 >>> newton(math.sin, math.cos, 2) 3.141592653589793 >>> newton(math.cos, lambda x: -math.sin(x), 2) 1.5707963267948966 >>> newton(math.cos, lambda x: -math.sin(x), 0) Traceback (most recent call last): ... ZeroDivisionError: Could not find root """ prev_guess = float(starting_int) while True: try: next_guess = prev_guess - function(prev_guess) / derivative(prev_guess) except ZeroDivisionError: raise ZeroDivisionError("Could not find root") from None if abs(prev_guess - next_guess) < 10 ** -5: return next_guess prev_guess = next_guess def f(x: float) -> float: return (x ** 3) - (2 * x) - 5 def f1(x: float) -> float: return 3 * (x ** 2) - 2 if __name__ == "__main__": print(newton(f, f1, 3))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Finding Bridges in Undirected Graph def computeBridges(graph): id = 0 n = len(graph) # No of vertices in graph low = [0] * n visited = [False] * n def dfs(at, parent, bridges, id): visited[at] = True low[at] = id id += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(to, at, bridges, id) low[at] = min(low[at], low[to]) if at < low[to]: bridges.append([at, to]) else: # This edge is a back edge and cannot be a bridge low[at] = min(low[at], to) bridges = [] for i in range(n): if not visited[i]: dfs(i, -1, bridges, id) print(bridges) graph = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } computeBridges(graph)
# Finding Bridges in Undirected Graph def computeBridges(graph): id = 0 n = len(graph) # No of vertices in graph low = [0] * n visited = [False] * n def dfs(at, parent, bridges, id): visited[at] = True low[at] = id id += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(to, at, bridges, id) low[at] = min(low[at], low[to]) if at < low[to]: bridges.append([at, to]) else: # This edge is a back edge and cannot be a bridge low[at] = min(low[at], to) bridges = [] for i in range(n): if not visited[i]: dfs(i, -1, bridges, id) print(bridges) graph = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } computeBridges(graph)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def prime_check(number: int) -> bool: """ Determines whether a given number is prime or not >>> prime_check(2) True >>> prime_check(15) False >>> prime_check(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if prime_check(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" author : Mayank Kumar Jha (mk9440) """ from __future__ import annotations def find_max_sub_array(A, low, high): if low == high: return low, high, A[low] else: mid = (low + high) // 2 left_low, left_high, left_sum = find_max_sub_array(A, low, mid) right_low, right_high, right_sum = find_max_sub_array(A, mid + 1, high) cross_left, cross_right, cross_sum = find_max_cross_sum(A, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_left, cross_right, cross_sum def find_max_cross_sum(A, low, mid, high): left_sum, max_left = -999999999, -1 right_sum, max_right = -999999999, -1 summ = 0 for i in range(mid, low - 1, -1): summ += A[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += A[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def max_sub_array(nums: list[int]) -> int: """ Finds the contiguous subarray which has the largest sum and return its sum. >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 An empty (sub)array has sum 0. >>> max_sub_array([]) 0 If all elements are negative, the largest subarray would be the empty array, having the sum 0. >>> max_sub_array([-1, -2, -3]) 0 >>> max_sub_array([5, -2, -3]) 5 >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) 187 """ best = 0 current = 0 for i in nums: current += i if current < 0: current = 0 best = max(best, current) return best if __name__ == "__main__": """ A random simulation of this algorithm. """ import time from random import randint from matplotlib import pyplot as plt inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: li = [randint(1, i) for j in range(i)] strt = time.time() (find_max_sub_array(li, 0, len(li) - 1)) end = time.time() tim.append(end - strt) print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i], "\t\t", tim[i]) plt.plot(inputs, tim) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds ") plt.show()
""" author : Mayank Kumar Jha (mk9440) """ from __future__ import annotations def find_max_sub_array(A, low, high): if low == high: return low, high, A[low] else: mid = (low + high) // 2 left_low, left_high, left_sum = find_max_sub_array(A, low, mid) right_low, right_high, right_sum = find_max_sub_array(A, mid + 1, high) cross_left, cross_right, cross_sum = find_max_cross_sum(A, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_left, cross_right, cross_sum def find_max_cross_sum(A, low, mid, high): left_sum, max_left = -999999999, -1 right_sum, max_right = -999999999, -1 summ = 0 for i in range(mid, low - 1, -1): summ += A[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += A[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def max_sub_array(nums: list[int]) -> int: """ Finds the contiguous subarray which has the largest sum and return its sum. >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 An empty (sub)array has sum 0. >>> max_sub_array([]) 0 If all elements are negative, the largest subarray would be the empty array, having the sum 0. >>> max_sub_array([-1, -2, -3]) 0 >>> max_sub_array([5, -2, -3]) 5 >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) 187 """ best = 0 current = 0 for i in nums: current += i if current < 0: current = 0 best = max(best, current) return best if __name__ == "__main__": """ A random simulation of this algorithm. """ import time from random import randint from matplotlib import pyplot as plt inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: li = [randint(1, i) for j in range(i)] strt = time.time() (find_max_sub_array(li, 0, len(li) - 1)) end = time.time() tim.append(end - strt) print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i], "\t\t", tim[i]) plt.plot(inputs, tim) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds ") plt.show()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# DarkCoder def sum_of_series(first_term, common_diff, num_of_terms): """ 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 """ sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return sum def main(): print(sum_of_series(1, 1, 10)) if __name__ == "__main__": import doctest doctest.testmod()
# DarkCoder def sum_of_series(first_term, common_diff, num_of_terms): """ 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 """ sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return sum def main(): print(sum_of_series(1, 1, 10)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://cp-algorithms.com/string/z-function.html Z-function or Z algorithm Efficient algorithm for pattern occurrence in a string Time Complexity: O(n) - where n is the length of the string """ def z_function(input_str: str) -> list: """ For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element the algorithm always returns 0 >>> z_function("abracadabra") [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1] >>> z_function("aaaa") [0, 3, 2, 1] >>> z_function("zxxzxxz") [0, 0, 0, 4, 0, 0, 1] """ z_result = [0] * len(input_str) # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i, z_result, s): """ Check if we have to move forward to the next characters or not """ return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: """ Example of using z-function for pattern occurrence Given function returns the number of times 'pattern' appears in 'input_str' as a substring >>> find_pattern("abr", "abracadabra") 2 >>> find_pattern("a", "aaaa") 4 >>> find_pattern("xz", "zxxzxxz") 2 """ answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
""" https://cp-algorithms.com/string/z-function.html Z-function or Z algorithm Efficient algorithm for pattern occurrence in a string Time Complexity: O(n) - where n is the length of the string """ def z_function(input_str: str) -> list: """ For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element the algorithm always returns 0 >>> z_function("abracadabra") [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1] >>> z_function("aaaa") [0, 3, 2, 1] >>> z_function("zxxzxxz") [0, 0, 0, 4, 0, 0, 1] """ z_result = [0] * len(input_str) # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i, z_result, s): """ Check if we have to move forward to the next characters or not """ return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: """ Example of using z-function for pattern occurrence Given function returns the number of times 'pattern' appears in 'input_str' as a substring >>> find_pattern("abr", "abracadabra") 2 >>> find_pattern("a", "aaaa") 4 >>> find_pattern("xz", "zxxzxxz") 2 """ answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class Node: def __init__(self, data: int) -> int: self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data: int) -> int: new_node = Node(new_data) new_node.next = self.head self.head = new_node return self.head.data def middle_element(self) -> int: """ >>> link = LinkedList() >>> link.middle_element() No element found. >>> link.push(5) 5 >>> link.push(6) 6 >>> link.push(8) 8 >>> link.push(8) 8 >>> link.push(10) 10 >>> link.push(12) 12 >>> link.push(17) 17 >>> link.push(7) 7 >>> link.push(3) 3 >>> link.push(20) 20 >>> link.push(-20) -20 >>> link.middle_element() 12 >>> """ slow_pointer = self.head fast_pointer = self.head if self.head: while fast_pointer and fast_pointer.next: fast_pointer = fast_pointer.next.next slow_pointer = slow_pointer.next return slow_pointer.data else: print("No element found.") if __name__ == "__main__": link = LinkedList() for i in range(int(input().strip())): data = int(input().strip()) link.push(data) print(link.middle_element())
class Node: def __init__(self, data: int) -> int: self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data: int) -> int: new_node = Node(new_data) new_node.next = self.head self.head = new_node return self.head.data def middle_element(self) -> int: """ >>> link = LinkedList() >>> link.middle_element() No element found. >>> link.push(5) 5 >>> link.push(6) 6 >>> link.push(8) 8 >>> link.push(8) 8 >>> link.push(10) 10 >>> link.push(12) 12 >>> link.push(17) 17 >>> link.push(7) 7 >>> link.push(3) 3 >>> link.push(20) 20 >>> link.push(-20) -20 >>> link.middle_element() 12 >>> """ slow_pointer = self.head fast_pointer = self.head if self.head: while fast_pointer and fast_pointer.next: fast_pointer = fast_pointer.next.next slow_pointer = slow_pointer.next return slow_pointer.data else: print("No element found.") if __name__ == "__main__": link = LinkedList() for i in range(int(input().strip())): data = int(input().strip()) link.push(data) print(link.middle_element())
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes, num_edges = 9, 14 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, num_edges, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes, num_edges = 9, 14 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, num_edges, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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([character for character in 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([character for character in 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
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Given an array-like data structure A[1..n], how many pairs (i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are called inversions. Counting the number of such inversions in an array-like object is the important. Among other things, counting inversions can help us determine how close a given array is to being sorted In this implementation, I provide two algorithms, a divide-and-conquer algorithm which runs in nlogn and the brute-force n^2 algorithm. """ def count_inversions_bf(arr): """ Counts the number of inversions using a a naive brute-force algorithm Parameters ---------- arr: arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- num_inversions: The total number of inversions in `arr` Examples --------- >>> count_inversions_bf([1, 4, 2, 4, 1]) 4 >>> count_inversions_bf([1, 1, 2, 4, 4]) 0 >>> count_inversions_bf([]) 0 """ num_inversions = 0 n = len(arr) for i in range(n - 1): for j in range(i + 1, n): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def count_inversions_recursive(arr): """ Counts the number of inversions using a divide-and-conquer algorithm Parameters ----------- arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- C: a sorted copy of `arr`. num_inversions: int, the total number of inversions in 'arr' Examples -------- >>> count_inversions_recursive([1, 4, 2, 4, 1]) ([1, 1, 2, 4, 4], 4) >>> count_inversions_recursive([1, 1, 2, 4, 4]) ([1, 1, 2, 4, 4], 0) >>> count_inversions_recursive([]) ([], 0) """ if len(arr) <= 1: return arr, 0 else: mid = len(arr) // 2 P = arr[0:mid] Q = arr[mid:] A, inversion_p = count_inversions_recursive(P) B, inversions_q = count_inversions_recursive(Q) C, cross_inversions = _count_cross_inversions(A, B) num_inversions = inversion_p + inversions_q + cross_inversions return C, num_inversions def _count_cross_inversions(P, Q): """ Counts the inversions across two sorted arrays. And combine the two arrays into one sorted array For all 1<= i<=len(P) and for all 1 <= j <= len(Q), if P[i] > Q[j], then (i, j) is a cross inversion Parameters ---------- P: array-like, sorted in non-decreasing order Q: array-like, sorted in non-decreasing order Returns ------ R: array-like, a sorted array of the elements of `P` and `Q` num_inversion: int, the number of inversions across `P` and `Q` Examples -------- >>> _count_cross_inversions([1, 2, 3], [0, 2, 5]) ([0, 1, 2, 2, 3, 5], 4) >>> _count_cross_inversions([1, 2, 3], [3, 4, 5]) ([1, 2, 3, 3, 4, 5], 0) """ R = [] i = j = num_inversion = 0 while i < len(P) and j < len(Q): if P[i] > Q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(P) - i R.append(Q[j]) j += 1 else: R.append(P[i]) i += 1 if i < len(P): R.extend(P[i:]) else: R.extend(Q[j:]) return R, num_inversion def main(): arr_1 = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = ", num_inversions_bf) # testing an array with zero inversion (a sorted arr_1) arr_1.sort() num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) # an empty list should also have zero inversions arr_1 = [] num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) if __name__ == "__main__": main()
""" Given an array-like data structure A[1..n], how many pairs (i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are called inversions. Counting the number of such inversions in an array-like object is the important. Among other things, counting inversions can help us determine how close a given array is to being sorted In this implementation, I provide two algorithms, a divide-and-conquer algorithm which runs in nlogn and the brute-force n^2 algorithm. """ def count_inversions_bf(arr): """ Counts the number of inversions using a a naive brute-force algorithm Parameters ---------- arr: arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- num_inversions: The total number of inversions in `arr` Examples --------- >>> count_inversions_bf([1, 4, 2, 4, 1]) 4 >>> count_inversions_bf([1, 1, 2, 4, 4]) 0 >>> count_inversions_bf([]) 0 """ num_inversions = 0 n = len(arr) for i in range(n - 1): for j in range(i + 1, n): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def count_inversions_recursive(arr): """ Counts the number of inversions using a divide-and-conquer algorithm Parameters ----------- arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- C: a sorted copy of `arr`. num_inversions: int, the total number of inversions in 'arr' Examples -------- >>> count_inversions_recursive([1, 4, 2, 4, 1]) ([1, 1, 2, 4, 4], 4) >>> count_inversions_recursive([1, 1, 2, 4, 4]) ([1, 1, 2, 4, 4], 0) >>> count_inversions_recursive([]) ([], 0) """ if len(arr) <= 1: return arr, 0 else: mid = len(arr) // 2 P = arr[0:mid] Q = arr[mid:] A, inversion_p = count_inversions_recursive(P) B, inversions_q = count_inversions_recursive(Q) C, cross_inversions = _count_cross_inversions(A, B) num_inversions = inversion_p + inversions_q + cross_inversions return C, num_inversions def _count_cross_inversions(P, Q): """ Counts the inversions across two sorted arrays. And combine the two arrays into one sorted array For all 1<= i<=len(P) and for all 1 <= j <= len(Q), if P[i] > Q[j], then (i, j) is a cross inversion Parameters ---------- P: array-like, sorted in non-decreasing order Q: array-like, sorted in non-decreasing order Returns ------ R: array-like, a sorted array of the elements of `P` and `Q` num_inversion: int, the number of inversions across `P` and `Q` Examples -------- >>> _count_cross_inversions([1, 2, 3], [0, 2, 5]) ([0, 1, 2, 2, 3, 5], 4) >>> _count_cross_inversions([1, 2, 3], [3, 4, 5]) ([1, 2, 3, 3, 4, 5], 0) """ R = [] i = j = num_inversion = 0 while i < len(P) and j < len(Q): if P[i] > Q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(P) - i R.append(Q[j]) j += 1 else: R.append(P[i]) i += 1 if i < len(P): R.extend(P[i:]) else: R.extend(Q[j:]) return R, num_inversion def main(): arr_1 = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = ", num_inversions_bf) # testing an array with zero inversion (a sorted arr_1) arr_1.sort() num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) # an empty list should also have zero inversions arr_1 = [] num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/Trifid_cipher def __encryptPart(messagePart: str, character2Number: dict[str, str]) -> str: one, two, three = "", "", "" tmp = [] for character in messagePart: tmp.append(character2Number[character]) for each in tmp: one += each[0] two += each[1] three += each[2] return one + two + three def __decryptPart( messagePart: str, character2Number: dict[str, str] ) -> tuple[str, str, str]: tmp, thisPart = "", "" result = [] for character in messagePart: thisPart += character2Number[character] for digit in thisPart: tmp += digit if len(tmp) == len(messagePart): result.append(tmp) tmp = "" return result[0], result[1], result[2] def __prepare( message: str, alphabet: str ) -> tuple[str, str, dict[str, str], dict[str, str]]: # Validate message and alphabet, set to upper and remove spaces alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() # Check length and characters if len(alphabet) != 27: raise KeyError("Length of alphabet has to be 27.") for each in message: if each not in alphabet: raise ValueError("Each message character has to be included in alphabet!") # Generate dictionares numbers = ( "111", "112", "113", "121", "122", "123", "131", "132", "133", "211", "212", "213", "221", "222", "223", "231", "232", "233", "311", "312", "313", "321", "322", "323", "331", "332", "333", ) character2Number = {} number2Character = {} for letter, number in zip(alphabet, numbers): character2Number[letter] = number number2Character[number] = letter return message, alphabet, character2Number, number2Character def encryptMessage( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character2Number, number2Character = __prepare(message, alphabet) encrypted, encrypted_numeric = "", "" for i in range(0, len(message) + 1, period): encrypted_numeric += __encryptPart(message[i : i + period], character2Number) for i in range(0, len(encrypted_numeric), 3): encrypted += number2Character[encrypted_numeric[i : i + 3]] return encrypted def decryptMessage( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character2Number, number2Character = __prepare(message, alphabet) decrypted_numeric = [] decrypted = "" for i in range(0, len(message) + 1, period): a, b, c = __decryptPart(message[i : i + period], character2Number) for j in range(0, len(a)): decrypted_numeric.append(a[j] + b[j] + c[j]) for each in decrypted_numeric: decrypted += number2Character[each] return decrypted if __name__ == "__main__": msg = "DEFEND THE EAST WALL OF THE CASTLE." encrypted = encryptMessage(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")
# https://en.wikipedia.org/wiki/Trifid_cipher def __encryptPart(messagePart: str, character2Number: dict[str, str]) -> str: one, two, three = "", "", "" tmp = [] for character in messagePart: tmp.append(character2Number[character]) for each in tmp: one += each[0] two += each[1] three += each[2] return one + two + three def __decryptPart( messagePart: str, character2Number: dict[str, str] ) -> tuple[str, str, str]: tmp, thisPart = "", "" result = [] for character in messagePart: thisPart += character2Number[character] for digit in thisPart: tmp += digit if len(tmp) == len(messagePart): result.append(tmp) tmp = "" return result[0], result[1], result[2] def __prepare( message: str, alphabet: str ) -> tuple[str, str, dict[str, str], dict[str, str]]: # Validate message and alphabet, set to upper and remove spaces alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() # Check length and characters if len(alphabet) != 27: raise KeyError("Length of alphabet has to be 27.") for each in message: if each not in alphabet: raise ValueError("Each message character has to be included in alphabet!") # Generate dictionares numbers = ( "111", "112", "113", "121", "122", "123", "131", "132", "133", "211", "212", "213", "221", "222", "223", "231", "232", "233", "311", "312", "313", "321", "322", "323", "331", "332", "333", ) character2Number = {} number2Character = {} for letter, number in zip(alphabet, numbers): character2Number[letter] = number number2Character[number] = letter return message, alphabet, character2Number, number2Character def encryptMessage( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character2Number, number2Character = __prepare(message, alphabet) encrypted, encrypted_numeric = "", "" for i in range(0, len(message) + 1, period): encrypted_numeric += __encryptPart(message[i : i + period], character2Number) for i in range(0, len(encrypted_numeric), 3): encrypted += number2Character[encrypted_numeric[i : i + 3]] return encrypted def decryptMessage( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character2Number, number2Character = __prepare(message, alphabet) decrypted_numeric = [] decrypted = "" for i in range(0, len(message) + 1, period): a, b, c = __decryptPart(message[i : i + period], character2Number) for j in range(0, len(a)): decrypted_numeric.append(a[j] + b[j] + c[j]) for each in decrypted_numeric: decrypted += number2Character[each] return decrypted if __name__ == "__main__": msg = "DEFEND THE EAST WALL OF THE CASTLE." encrypted = encryptMessage(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 """ def solution(): """Returns >>> solution() 210 """ constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
""" Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 """ def solution(): """Returns >>> solution() 210 """ constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Check whether Graph is Bipartite or Not using BFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def checkBipartite(graph): queue = [] visited = [False] * len(graph) color = [-1] * len(graph) def bfs(): while queue: u = queue.pop(0) visited[u] = True for neighbour in graph[u]: if neighbour == u: return False if color[neighbour] == -1: color[neighbour] = 1 - color[u] queue.append(neighbour) elif color[neighbour] == color[u]: return False return True for i in range(len(graph)): if not visited[i]: queue.append(i) color[i] = 0 if bfs() is False: return False return True if __name__ == "__main__": # Adjacency List of graph print(checkBipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))
# Check whether Graph is Bipartite or Not using BFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def checkBipartite(graph): queue = [] visited = [False] * len(graph) color = [-1] * len(graph) def bfs(): while queue: u = queue.pop(0) visited[u] = True for neighbour in graph[u]: if neighbour == u: return False if color[neighbour] == -1: color[neighbour] = 1 - color[u] queue.append(neighbour) elif color[neighbour] == color[u]: return False return True for i in range(len(graph)): if not visited[i]: queue.append(i) color[i] = 0 if bfs() is False: return False return True if __name__ == "__main__": # Adjacency List of graph print(checkBipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ def p_series(nth_term: int, power: int) -> list: """Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) [1, '1/4', '1/9', '1/16', '1/25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) [1, '1/0.25', '1/0.1111111111111111', '1/0.0625', '1/0.04'] >>> p_series("", 1000) '' >>> p_series(0, 0) [] >>> p_series(1, 1) [1] """ if nth_term == "": return nth_term nth_term = int(nth_term) power = int(power) series = [] for temp in range(int(nth_term)): series.append(f"1/{pow(temp + 1, int(power))}" if series else 1) return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the P-Series") power = input("Enter the power for P-Series") print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ def p_series(nth_term: int, power: int) -> list: """Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) [1, '1/4', '1/9', '1/16', '1/25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) [1, '1/0.25', '1/0.1111111111111111', '1/0.0625', '1/0.04'] >>> p_series("", 1000) '' >>> p_series(0, 0) [] >>> p_series(1, 1) [1] """ if nth_term == "": return nth_term nth_term = int(nth_term) power = int(power) series = [] for temp in range(int(nth_term)): series.append(f"1/{pow(temp + 1, int(power))}" if series else 1) return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the P-Series") power = input("Enter the power for P-Series") print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: """ Class Instagram crawl instagram user information Usage: (doctest failing on GitHub Actions) # >>> instagram_user = InstagramUser("github") # >>> instagram_user.is_verified True # >>> instagram_user.biography 'Built for developers.' """ def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: """ Return a dict of user information """ html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: """ A self running doctest >>> test_instagram_user() """ import os if os.environ.get("CI"): return None # test failing on GitHub Actions instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: """ Class Instagram crawl instagram user information Usage: (doctest failing on GitHub Actions) # >>> instagram_user = InstagramUser("github") # >>> instagram_user.is_verified True # >>> instagram_user.biography 'Built for developers.' """ def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: """ Return a dict of user information """ html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: """ A self running doctest >>> test_instagram_user() """ import os if os.environ.get("CI"): return None # test failing on GitHub Actions instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from math import pi def radians(degree: float) -> float: """ Coverts the given angle from degrees to radians https://en.wikipedia.org/wiki/Radian >>> radians(180) 3.141592653589793 >>> radians(92) 1.6057029118347832 >>> radians(274) 4.782202150464463 >>> radians(109.82) 1.9167205845401725 >>> from math import radians as math_radians >>> all(abs(radians(i)-math_radians(i)) <= 0.00000001 for i in range(-2, 361)) True """ return degree / (180 / pi) if __name__ == "__main__": from doctest import testmod testmod()
from math import pi def radians(degree: float) -> float: """ Coverts the given angle from degrees to radians https://en.wikipedia.org/wiki/Radian >>> radians(180) 3.141592653589793 >>> radians(92) 1.6057029118347832 >>> radians(274) 4.782202150464463 >>> radians(109.82) 1.9167205845401725 >>> from math import radians as math_radians >>> all(abs(radians(i)-math_radians(i)) <= 0.00000001 for i in range(-2, 361)) True """ return degree / (180 / pi) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import List 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 typing import List 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
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import os UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n" def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} with open(path[0] + "/dictionary.txt") as dictionaryFile: for word in dictionaryFile.read().split("\n"): englishWords[word] = None return englishWords ENGLISH_WORDS = loadDictionary() def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() if possibleWords == []: return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(possibleWords) def removeNonLetters(message): lettersOnly = [] for symbol in message: if symbol in LETTERS_AND_SPACE: lettersOnly.append(symbol) return "".join(lettersOnly) def isEnglish(message, wordPercentage=20, letterPercentage=85): """ >>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False """ wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = (float(numLetters) / len(message)) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch if __name__ == "__main__": import doctest doctest.testmod()
import os UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n" def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} with open(path[0] + "/dictionary.txt") as dictionaryFile: for word in dictionaryFile.read().split("\n"): englishWords[word] = None return englishWords ENGLISH_WORDS = loadDictionary() def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() if possibleWords == []: return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(possibleWords) def removeNonLetters(message): lettersOnly = [] for symbol in message: if symbol in LETTERS_AND_SPACE: lettersOnly.append(symbol) return "".join(lettersOnly) def isEnglish(message, wordPercentage=20, letterPercentage=85): """ >>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False """ wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = (float(numLetters) / len(message)) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. In bubble sort, distance (or gap) between two compared elements is always one. Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values at the end of a list. More info on: https://en.wikipedia.org/wiki/Comb_sort For doctests run following command: python -m doctest -v comb_sort.py or python3 -m doctest -v comb_sort.py For manual testing run: python comb_sort.py """ def comb_sort(data: list) -> list: """Pure implementation of comb sort algorithm in Python :param data: mutable collection with comparable items :return: the same collection in ascending order Examples: >>> comb_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> comb_sort([]) [] >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3]) [-15, -7, 0, 2, 3, 8, 45, 99] """ shrink_factor = 1.3 gap = len(data) completed = False while not completed: # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data): if data[index] > data[index + gap]: # Swap values data[index], data[index + gap] = data[index + gap], data[index] completed = False index += 1 return data if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted))
""" This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. In bubble sort, distance (or gap) between two compared elements is always one. Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values at the end of a list. More info on: https://en.wikipedia.org/wiki/Comb_sort For doctests run following command: python -m doctest -v comb_sort.py or python3 -m doctest -v comb_sort.py For manual testing run: python comb_sort.py """ def comb_sort(data: list) -> list: """Pure implementation of comb sort algorithm in Python :param data: mutable collection with comparable items :return: the same collection in ascending order Examples: >>> comb_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> comb_sort([]) [] >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3]) [-15, -7, 0, 2, 3, 8, 45, 99] """ shrink_factor = 1.3 gap = len(data) completed = False while not completed: # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data): if data[index] > data[index + gap]: # Swap values data[index], data[index + gap] = data[index + gap], data[index] completed = False index += 1 return data if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" python/black : true flake8 : passed """ from typing import Iterator, Optional class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: Optional[int] = None, color: int = 0, parent: Optional["RedBlackTree"] = None, left: Optional["RedBlackTree"] = None, right: Optional["RedBlackTree"] = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> "RedBlackTree": """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() self.left._insert_repair() elif self.is_left(): self.grandparent.rotate_right() self.parent.color = 0 self.parent.right.color = 1 else: self.grandparent.rotate_left() self.parent.color = 0 self.parent.left.color = 1 else: self.parent.color = 0 uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> "RedBlackTree": """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> None: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> "RedBlackTree": """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> "RedBlackTree": """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> "RedBlackTree": """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" return self.parent and self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" return self.parent and self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other) -> bool: """Test if two trees are equal.""" if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
""" python/black : true flake8 : passed """ from typing import Iterator, Optional class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: Optional[int] = None, color: int = 0, parent: Optional["RedBlackTree"] = None, left: Optional["RedBlackTree"] = None, right: Optional["RedBlackTree"] = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> "RedBlackTree": """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> "RedBlackTree": """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() self.left._insert_repair() elif self.is_left(): self.grandparent.rotate_right() self.parent.color = 0 self.parent.right.color = 1 else: self.grandparent.rotate_left() self.parent.color = 0 self.parent.left.color = 1 else: self.parent.color = 0 uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> "RedBlackTree": """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> None: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> "RedBlackTree": """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> "RedBlackTree": """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> "RedBlackTree": """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" return self.parent and self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" return self.parent and self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other) -> bool: """Test if two trees are equal.""" if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms)
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ def isprime(d: int) -> int: """ returns whether the given digit is prime or not >>> isprime(1) 0 >>> isprime(17) 1 >>> isprime(10000) 0 """ if d == 1: return 0 i = 2 while i * i <= d: if d % i == 0: return 0 i = i + 1 return 1 def solution(ratio: float = 0.1) -> int: """ returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes = primes + isprime(i) j = j + 2 return j if __name__ == "__main__": import doctest doctest.testmod()
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ def isprime(d: int) -> int: """ returns whether the given digit is prime or not >>> isprime(1) 0 >>> isprime(17) 1 >>> isprime(10000) 0 """ if d == 1: return 0 i = 2 while i * i <= d: if d % i == 0: return 0 i = i + 1 return 1 def solution(ratio: float = 0.1) -> int: """ returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes = primes + isprime(i) j = j + 2 return j if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a, matrix_b): matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n): return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n): """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n): """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for i in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main(): for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": main()
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a, matrix_b): matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n): return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n): """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n): """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for i in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main(): for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Partition a set into two subsets such that the difference of subset sums is minimum """ def findMin(arr): n = len(arr) s = sum(arr) dp = [[False for x in range(s + 1)] for y in range(n + 1)] for i in range(1, n + 1): dp[i][0] = True for i in range(1, s + 1): dp[0][i] = False for i in range(1, n + 1): for j in range(1, s + 1): dp[i][j] = dp[i][j - 1] if arr[i - 1] <= j: dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2), -1, -1): if dp[n][j] is True: diff = s - 2 * j break return diff
""" Partition a set into two subsets such that the difference of subset sums is minimum """ def findMin(arr): n = len(arr) s = sum(arr) dp = [[False for x in range(s + 1)] for y in range(n + 1)] for i in range(1, n + 1): dp[i][0] = True for i in range(1, s + 1): dp[0][i] = False for i in range(1, n + 1): for j in range(1, s + 1): dp[i][j] = dp[i][j - 1] if arr[i - 1] <= j: dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2), -1, -1): if dp[n][j] is True: diff = s - 2 * j break return diff
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# NguyenU def find_max(nums): """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True """ max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num def main(): print(find_max([2, 4, 9, 7, 19, 94, 5])) # 94 if __name__ == "__main__": main()
# NguyenU def find_max(nums): """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True """ max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num def main(): print(find_max([2, 4, 9, 7, 19, 94, 5])) # 94 if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ def solution(limit=28123): """ Finds the sum of all the positive integers which cannot be written as the sum of two abundant numbers as described by the statement above. >>> solution() 4179871 """ sumDivs = [1] * (limit + 1) for i in range(2, int(limit ** 0.5) + 1): sumDivs[i * i] += i for k in range(i + 1, limit // i + 1): sumDivs[k * i] += k + i abundants = set() res = 0 for n in range(1, limit + 1): if sumDivs[n] > n: abundants.add(n) if not any((n - a in abundants) for a in abundants): res += n return res if __name__ == "__main__": print(solution())
""" A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ def solution(limit=28123): """ Finds the sum of all the positive integers which cannot be written as the sum of two abundant numbers as described by the statement above. >>> solution() 4179871 """ sumDivs = [1] * (limit + 1) for i in range(2, int(limit ** 0.5) + 1): sumDivs[i * i] += i for k in range(i + 1, limit // i + 1): sumDivs[k * i] += k + i abundants = set() res = 0 for n in range(1, limit + 1): if sumDivs[n] > n: abundants.add(n) if not any((n - a in abundants) for a in abundants): res += n return res if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import List def median_of_two_arrays(nums1: List[float], nums2: List[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
from typing import List def median_of_two_arrays(nums1: List[float], nums2: List[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Created on Fri Sep 28 15:22:29 2018 @author: Binish125 """ import copy import os import cv2 import numpy as np from matplotlib import pyplot as plt class contrastStretch: def __init__(self): self.img = "" self.original_image = "" self.last_list = [] self.rem = 0 self.L = 256 self.sk = 0 self.k = 0 self.number_of_rows = 0 self.number_of_cols = 0 def stretch(self, input_image): self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") self.k = np.sum(x) for i in range(len(x)): prk = x[i] / self.k self.sk += prk last = (self.L - 1) * self.sk if self.rem != 0: self.rem = int(last % last) last = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(last) self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) self.number_of_cols = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): num = self.img[j][i] if num != self.last_list[num]: self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img) def plotHistogram(self): plt.hist(self.img.ravel(), 256, [0, 256]) def showImage(self): cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) cv2.destroyAllWindows() if __name__ == "__main__": file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg") stretcher = contrastStretch() stretcher.stretch(file_path) stretcher.plotHistogram() stretcher.showImage()
""" Created on Fri Sep 28 15:22:29 2018 @author: Binish125 """ import copy import os import cv2 import numpy as np from matplotlib import pyplot as plt class contrastStretch: def __init__(self): self.img = "" self.original_image = "" self.last_list = [] self.rem = 0 self.L = 256 self.sk = 0 self.k = 0 self.number_of_rows = 0 self.number_of_cols = 0 def stretch(self, input_image): self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") self.k = np.sum(x) for i in range(len(x)): prk = x[i] / self.k self.sk += prk last = (self.L - 1) * self.sk if self.rem != 0: self.rem = int(last % last) last = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(last) self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) self.number_of_cols = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): num = self.img[j][i] if num != self.last_list[num]: self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img) def plotHistogram(self): plt.hist(self.img.ravel(), 256, [0, 256]) def showImage(self): cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) cv2.destroyAllWindows() if __name__ == "__main__": file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg") stretcher = contrastStretch() stretcher.stretch(file_path) stretcher.plotHistogram() stretcher.showImage()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is used to convert the currency using the Amdoren Currency API https://www.amdoren.com """ import os import requests URL_BASE = "https://www.amdoren.com/api/currency.php" TESTING = os.getenv("CI", False) API_KEY = os.getenv("AMDOREN_API_KEY", "") if not API_KEY and not TESTING: raise KeyError("Please put your API key in an environment variable.") # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Guilder AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia & Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc BMD Bermudian Dollar BND Brunei Dollar BOB Bolivian Boliviano BRL Brazilian Real BSD Bahamian Dollar BTN Bhutanese Ngultrum BWP Botswana Pula BYN Belarus Ruble BZD Belize Dollar CAD Canadian Dollar CDF Congolese Franc CHF Swiss Franc CLP Chilean Peso CNY Chinese Yuan COP Colombian Peso CRC Costa Rican Colon CUC Cuban Convertible Peso CVE Cape Verdean Escudo CZK Czech Republic Koruna DJF Djiboutian Franc DKK Danish Krone DOP Dominican Peso DZD Algerian Dinar EGP Egyptian Pound ERN Eritrean Nakfa ETB Ethiopian Birr EUR Euro FJD Fiji Dollar GBP British Pound Sterling GEL Georgian Lari GHS Ghanaian Cedi GIP Gibraltar Pound GMD Gambian Dalasi GNF Guinea Franc GTQ Guatemalan Quetzal GYD Guyanaese Dollar HKD Hong Kong Dollar HNL Honduran Lempira HRK Croatian Kuna HTG Haiti Gourde HUF Hungarian Forint IDR Indonesian Rupiah ILS Israeli Shekel INR Indian Rupee IQD Iraqi Dinar IRR Iranian Rial ISK Icelandic Krona JMD Jamaican Dollar JOD Jordanian Dinar JPY Japanese Yen KES Kenyan Shilling KGS Kyrgystani Som KHR Cambodian Riel KMF Comorian Franc KPW North Korean Won KRW South Korean Won KWD Kuwaiti Dinar KYD Cayman Islands Dollar KZT Kazakhstan Tenge LAK Laotian Kip LBP Lebanese Pound LKR Sri Lankan Rupee LRD Liberian Dollar LSL Lesotho Loti LYD Libyan Dinar MAD Moroccan Dirham MDL Moldovan Leu MGA Malagasy Ariary MKD Macedonian Denar MMK Myanma Kyat MNT Mongolian Tugrik MOP Macau Pataca MRO Mauritanian Ouguiya MUR Mauritian Rupee MVR Maldivian Rufiyaa MWK Malawi Kwacha MXN Mexican Peso MYR Malaysian Ringgit MZN Mozambican Metical NAD Namibian Dollar NGN Nigerian Naira NIO Nicaragua Cordoba NOK Norwegian Krone NPR Nepalese Rupee NZD New Zealand Dollar OMR Omani Rial PAB Panamanian Balboa PEN Peruvian Nuevo Sol PGK Papua New Guinean Kina PHP Philippine Peso PKR Pakistani Rupee PLN Polish Zloty PYG Paraguayan Guarani QAR Qatari Riyal RON Romanian Leu RSD Serbian Dinar RUB Russian Ruble RWF Rwanda Franc SAR Saudi Riyal SBD Solomon Islands Dollar SCR Seychellois Rupee SDG Sudanese Pound SEK Swedish Krona SGD Singapore Dollar SHP Saint Helena Pound SLL Sierra Leonean Leone SOS Somali Shilling SRD Surinamese Dollar SSP South Sudanese Pound STD Sao Tome and Principe Dobra SYP Syrian Pound SZL Swazi Lilangeni THB Thai Baht TJS Tajikistan Somoni TMT Turkmenistani Manat TND Tunisian Dinar TOP Tonga Paanga TRY Turkish Lira TTD Trinidad and Tobago Dollar TWD New Taiwan Dollar TZS Tanzanian Shilling UAH Ukrainian Hryvnia UGX Ugandan Shilling USD United States Dollar UYU Uruguayan Peso UZS Uzbekistan Som VEF Venezuelan Bolivar VND Vietnamese Dong VUV Vanuatu Vatu WST Samoan Tala XAF Central African CFA franc XCD East Caribbean Dollar XOF West African CFA franc XPF CFP Franc YER Yemeni Rial ZAR South African Rand ZMW Zambian Kwacha """ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = API_KEY ) -> str: """https://www.amdoren.com/currency-api/""" params = locals() params["from"] = params.pop("from_") res = requests.get(URL_BASE, params=params).json() return str(res["amount"]) if res["error"] == 0 else res["error_message"] if __name__ == "__main__": print( convert_currency( input("Enter from currency: ").strip(), input("Enter to currency: ").strip(), float(input("Enter the amount: ").strip()), ) )
""" This is used to convert the currency using the Amdoren Currency API https://www.amdoren.com """ import os import requests URL_BASE = "https://www.amdoren.com/api/currency.php" TESTING = os.getenv("CI", False) API_KEY = os.getenv("AMDOREN_API_KEY", "") if not API_KEY and not TESTING: raise KeyError("Please put your API key in an environment variable.") # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Guilder AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia & Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc BMD Bermudian Dollar BND Brunei Dollar BOB Bolivian Boliviano BRL Brazilian Real BSD Bahamian Dollar BTN Bhutanese Ngultrum BWP Botswana Pula BYN Belarus Ruble BZD Belize Dollar CAD Canadian Dollar CDF Congolese Franc CHF Swiss Franc CLP Chilean Peso CNY Chinese Yuan COP Colombian Peso CRC Costa Rican Colon CUC Cuban Convertible Peso CVE Cape Verdean Escudo CZK Czech Republic Koruna DJF Djiboutian Franc DKK Danish Krone DOP Dominican Peso DZD Algerian Dinar EGP Egyptian Pound ERN Eritrean Nakfa ETB Ethiopian Birr EUR Euro FJD Fiji Dollar GBP British Pound Sterling GEL Georgian Lari GHS Ghanaian Cedi GIP Gibraltar Pound GMD Gambian Dalasi GNF Guinea Franc GTQ Guatemalan Quetzal GYD Guyanaese Dollar HKD Hong Kong Dollar HNL Honduran Lempira HRK Croatian Kuna HTG Haiti Gourde HUF Hungarian Forint IDR Indonesian Rupiah ILS Israeli Shekel INR Indian Rupee IQD Iraqi Dinar IRR Iranian Rial ISK Icelandic Krona JMD Jamaican Dollar JOD Jordanian Dinar JPY Japanese Yen KES Kenyan Shilling KGS Kyrgystani Som KHR Cambodian Riel KMF Comorian Franc KPW North Korean Won KRW South Korean Won KWD Kuwaiti Dinar KYD Cayman Islands Dollar KZT Kazakhstan Tenge LAK Laotian Kip LBP Lebanese Pound LKR Sri Lankan Rupee LRD Liberian Dollar LSL Lesotho Loti LYD Libyan Dinar MAD Moroccan Dirham MDL Moldovan Leu MGA Malagasy Ariary MKD Macedonian Denar MMK Myanma Kyat MNT Mongolian Tugrik MOP Macau Pataca MRO Mauritanian Ouguiya MUR Mauritian Rupee MVR Maldivian Rufiyaa MWK Malawi Kwacha MXN Mexican Peso MYR Malaysian Ringgit MZN Mozambican Metical NAD Namibian Dollar NGN Nigerian Naira NIO Nicaragua Cordoba NOK Norwegian Krone NPR Nepalese Rupee NZD New Zealand Dollar OMR Omani Rial PAB Panamanian Balboa PEN Peruvian Nuevo Sol PGK Papua New Guinean Kina PHP Philippine Peso PKR Pakistani Rupee PLN Polish Zloty PYG Paraguayan Guarani QAR Qatari Riyal RON Romanian Leu RSD Serbian Dinar RUB Russian Ruble RWF Rwanda Franc SAR Saudi Riyal SBD Solomon Islands Dollar SCR Seychellois Rupee SDG Sudanese Pound SEK Swedish Krona SGD Singapore Dollar SHP Saint Helena Pound SLL Sierra Leonean Leone SOS Somali Shilling SRD Surinamese Dollar SSP South Sudanese Pound STD Sao Tome and Principe Dobra SYP Syrian Pound SZL Swazi Lilangeni THB Thai Baht TJS Tajikistan Somoni TMT Turkmenistani Manat TND Tunisian Dinar TOP Tonga Paanga TRY Turkish Lira TTD Trinidad and Tobago Dollar TWD New Taiwan Dollar TZS Tanzanian Shilling UAH Ukrainian Hryvnia UGX Ugandan Shilling USD United States Dollar UYU Uruguayan Peso UZS Uzbekistan Som VEF Venezuelan Bolivar VND Vietnamese Dong VUV Vanuatu Vatu WST Samoan Tala XAF Central African CFA franc XCD East Caribbean Dollar XOF West African CFA franc XPF CFP Franc YER Yemeni Rial ZAR South African Rand ZMW Zambian Kwacha """ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = API_KEY ) -> str: """https://www.amdoren.com/currency-api/""" params = locals() params["from"] = params.pop("from_") res = requests.get(URL_BASE, params=params).json() return str(res["amount"]) if res["error"] == 0 else res["error_message"] if __name__ == "__main__": print( convert_currency( input("Enter from currency: ").strip(), input("Enter to currency: ").strip(), float(input("Enter the amount: ").strip()), ) )
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is pure Python implementation of counting sort algorithm For doctests run following command: python -m doctest -v counting_sort.py or python3 -m doctest -v counting_sort.py For manual testing run: python counting_sort.py """ def counting_sort(collection): """Pure implementation of counting sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> counting_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> counting_sort([]) [] >>> counting_sort([-2, -5, -45]) [-45, -5, -2] """ # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection coll_len = len(collection) coll_max = max(collection) coll_min = min(collection) # create the counting array counting_arr_length = coll_max + 1 - coll_min counting_arr = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1, counting_arr_length): counting_arr[i] = counting_arr[i] + counting_arr[i - 1] # create the output collection ordered = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0, coll_len)): ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def counting_sort_string(string): """ >>> counting_sort_string("thisisthestring") 'eghhiiinrsssttt' """ return "".join([chr(i) for i in counting_sort([ord(c) for c in string])]) if __name__ == "__main__": # Test string sort assert "eghhiiinrsssttt" == counting_sort_string("thisisthestring") user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(counting_sort(unsorted))
""" This is pure Python implementation of counting sort algorithm For doctests run following command: python -m doctest -v counting_sort.py or python3 -m doctest -v counting_sort.py For manual testing run: python counting_sort.py """ def counting_sort(collection): """Pure implementation of counting sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> counting_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> counting_sort([]) [] >>> counting_sort([-2, -5, -45]) [-45, -5, -2] """ # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection coll_len = len(collection) coll_max = max(collection) coll_min = min(collection) # create the counting array counting_arr_length = coll_max + 1 - coll_min counting_arr = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1, counting_arr_length): counting_arr[i] = counting_arr[i] + counting_arr[i - 1] # create the output collection ordered = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0, coll_len)): ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def counting_sort_string(string): """ >>> counting_sort_string("thisisthestring") 'eghhiiinrsssttt' """ return "".join([chr(i) for i in counting_sort([ord(c) for c in string])]) if __name__ == "__main__": # Test string sort assert "eghhiiinrsssttt" == counting_sort_string("thisisthestring") user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(counting_sort(unsorted))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author : Syed Faizan ( 3rd Year IIIT Pune ) Github : faizan2700 Purpose : You have one function f(x) which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpsons in 1743 is one way to calculate integration. ( read article : https://cp-algorithms.com/num_methods/simpson-integration.html ) simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and returns the integration of function in given limit. """ # constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: """ Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integraion precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer >>> simpson_integration(lambda x : x*x,1,2,3) 2.333 >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) Traceback (most recent call last): ... AssertionError: a should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) Traceback (most recent call last): ... AssertionError: b should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : wrong_input >>> simpson_integration('wrong_input',2,3,4) Traceback (most recent call last): ... AssertionError: the function(object) passed should be callable your input : ... >>> simpson_integration(lambda x : x*x,3.45,3.2,1) -2.8 >>> simpson_integration(lambda x : x*x,3.45,3.2,0) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : 0 >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : -1 """ assert callable( function ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, float) or isinstance( a, int ), f"a should be float or integer your input : {a}" assert isinstance(function(a), float) or isinstance(function(a), int), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, float) or isinstance( b, int ), f"b should be float or integer your input : {b}" assert ( isinstance(precision, int) and precision > 0 ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integraion written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Syed Faizan ( 3rd Year IIIT Pune ) Github : faizan2700 Purpose : You have one function f(x) which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpsons in 1743 is one way to calculate integration. ( read article : https://cp-algorithms.com/num_methods/simpson-integration.html ) simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and returns the integration of function in given limit. """ # constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: """ Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integraion precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer >>> simpson_integration(lambda x : x*x,1,2,3) 2.333 >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) Traceback (most recent call last): ... AssertionError: a should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) Traceback (most recent call last): ... AssertionError: b should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : wrong_input >>> simpson_integration('wrong_input',2,3,4) Traceback (most recent call last): ... AssertionError: the function(object) passed should be callable your input : ... >>> simpson_integration(lambda x : x*x,3.45,3.2,1) -2.8 >>> simpson_integration(lambda x : x*x,3.45,3.2,0) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : 0 >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : -1 """ assert callable( function ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, float) or isinstance( a, int ), f"a should be float or integer your input : {a}" assert isinstance(function(a), float) or isinstance(function(a), int), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, float) or isinstance( b, int ), f"b should be float or integer your input : {b}" assert ( isinstance(precision, int) and precision > 0 ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integraion written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import deque from dataclasses import dataclass from typing import Iterator, List """ Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra. 0-1-graph is the weighted graph with the weights equal to 0 or 1. Link: https://codeforces.com/blog/entry/22276 """ @dataclass class Edge: """Weighted directed graph edge.""" destination_vertex: int weight: int class AdjacencyList: """Graph adjacency list.""" def __init__(self, size: int): self._graph: List[List[Edge]] = [[] for _ in range(size)] self._size = size def __getitem__(self, vertex: int) -> Iterator[Edge]: """Get all the vertices adjacent to the given one.""" return iter(self._graph[vertex]) @property def size(self): return self._size def add_edge(self, from_vertex: int, to_vertex: int, weight: int): """ >>> g = AdjacencyList(2) >>> g.add_edge(0, 1, 0) >>> g.add_edge(1, 0, 1) >>> list(g[0]) [Edge(destination_vertex=1, weight=0)] >>> list(g[1]) [Edge(destination_vertex=0, weight=1)] >>> g.add_edge(0, 1, 2) Traceback (most recent call last): ... ValueError: Edge weight must be either 0 or 1. >>> g.add_edge(0, 2, 1) Traceback (most recent call last): ... ValueError: Vertex indexes must be in [0; size). """ if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1.") if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size).") self._graph[from_vertex].append(Edge(to_vertex, weight)) def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int: """ Return the shortest distance from start_vertex to finish_vertex in 0-1-graph. 1 1 1 0--------->3 6--------7>------->8 | ^ ^ ^ |1 | | | |0 v 0| |0 1| 9-------->10 | | | ^ 1 v | | |0 1--------->2<-------4------->5 0 1 1 >>> g = AdjacencyList(11) >>> g.add_edge(0, 1, 0) >>> g.add_edge(0, 3, 1) >>> g.add_edge(1, 2, 0) >>> g.add_edge(2, 3, 0) >>> g.add_edge(4, 2, 1) >>> g.add_edge(4, 5, 1) >>> g.add_edge(4, 6, 1) >>> g.add_edge(5, 9, 0) >>> g.add_edge(6, 7, 1) >>> g.add_edge(7, 8, 1) >>> g.add_edge(8, 10, 1) >>> g.add_edge(9, 7, 0) >>> g.add_edge(9, 10, 1) >>> g.add_edge(1, 2, 2) Traceback (most recent call last): ... ValueError: Edge weight must be either 0 or 1. >>> g.get_shortest_path(0, 3) 0 >>> g.get_shortest_path(0, 4) Traceback (most recent call last): ... ValueError: No path from start_vertex to finish_vertex. >>> g.get_shortest_path(4, 10) 2 >>> g.get_shortest_path(4, 8) 2 >>> g.get_shortest_path(0, 1) 0 >>> g.get_shortest_path(1, 0) Traceback (most recent call last): ... ValueError: No path from start_vertex to finish_vertex. """ queue = deque([start_vertex]) distances = [None for i in range(self.size)] distances[start_vertex] = 0 while queue: current_vertex = queue.popleft() current_distance = distances[current_vertex] for edge in self[current_vertex]: new_distance = current_distance + edge.weight if ( distances[edge.destination_vertex] is not None and new_distance >= distances[edge.destination_vertex] ): continue distances[edge.destination_vertex] = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex) else: queue.append(edge.destination_vertex) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex.") return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
from collections import deque from dataclasses import dataclass from typing import Iterator, List """ Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra. 0-1-graph is the weighted graph with the weights equal to 0 or 1. Link: https://codeforces.com/blog/entry/22276 """ @dataclass class Edge: """Weighted directed graph edge.""" destination_vertex: int weight: int class AdjacencyList: """Graph adjacency list.""" def __init__(self, size: int): self._graph: List[List[Edge]] = [[] for _ in range(size)] self._size = size def __getitem__(self, vertex: int) -> Iterator[Edge]: """Get all the vertices adjacent to the given one.""" return iter(self._graph[vertex]) @property def size(self): return self._size def add_edge(self, from_vertex: int, to_vertex: int, weight: int): """ >>> g = AdjacencyList(2) >>> g.add_edge(0, 1, 0) >>> g.add_edge(1, 0, 1) >>> list(g[0]) [Edge(destination_vertex=1, weight=0)] >>> list(g[1]) [Edge(destination_vertex=0, weight=1)] >>> g.add_edge(0, 1, 2) Traceback (most recent call last): ... ValueError: Edge weight must be either 0 or 1. >>> g.add_edge(0, 2, 1) Traceback (most recent call last): ... ValueError: Vertex indexes must be in [0; size). """ if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1.") if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size).") self._graph[from_vertex].append(Edge(to_vertex, weight)) def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int: """ Return the shortest distance from start_vertex to finish_vertex in 0-1-graph. 1 1 1 0--------->3 6--------7>------->8 | ^ ^ ^ |1 | | | |0 v 0| |0 1| 9-------->10 | | | ^ 1 v | | |0 1--------->2<-------4------->5 0 1 1 >>> g = AdjacencyList(11) >>> g.add_edge(0, 1, 0) >>> g.add_edge(0, 3, 1) >>> g.add_edge(1, 2, 0) >>> g.add_edge(2, 3, 0) >>> g.add_edge(4, 2, 1) >>> g.add_edge(4, 5, 1) >>> g.add_edge(4, 6, 1) >>> g.add_edge(5, 9, 0) >>> g.add_edge(6, 7, 1) >>> g.add_edge(7, 8, 1) >>> g.add_edge(8, 10, 1) >>> g.add_edge(9, 7, 0) >>> g.add_edge(9, 10, 1) >>> g.add_edge(1, 2, 2) Traceback (most recent call last): ... ValueError: Edge weight must be either 0 or 1. >>> g.get_shortest_path(0, 3) 0 >>> g.get_shortest_path(0, 4) Traceback (most recent call last): ... ValueError: No path from start_vertex to finish_vertex. >>> g.get_shortest_path(4, 10) 2 >>> g.get_shortest_path(4, 8) 2 >>> g.get_shortest_path(0, 1) 0 >>> g.get_shortest_path(1, 0) Traceback (most recent call last): ... ValueError: No path from start_vertex to finish_vertex. """ queue = deque([start_vertex]) distances = [None for i in range(self.size)] distances[start_vertex] = 0 while queue: current_vertex = queue.popleft() current_distance = distances[current_vertex] for edge in self[current_vertex]: new_distance = current_distance + edge.weight if ( distances[edge.destination_vertex] is not None and new_distance >= distances[edge.destination_vertex] ): continue distances[edge.destination_vertex] = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex) else: queue.append(edge.destination_vertex) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex.") return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Tree_sort algorithm. Build a BST and in order traverse. """ class node: # BST data structure def __init__(self, val): self.val = val self.left = None self.right = None def insert(self, val): if self.val: if val < self.val: if self.left is None: self.left = node(val) else: self.left.insert(val) elif val > self.val: if self.right is None: self.right = node(val) else: self.right.insert(val) else: self.val = val def inorder(root, res): # Recursive traversal if root: inorder(root.left, res) res.append(root.val) inorder(root.right, res) def tree_sort(arr): # Build BST if len(arr) == 0: return arr root = node(arr[0]) for i in range(1, len(arr)): root.insert(arr[i]) # Traverse BST in order. res = [] inorder(root, res) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
""" Tree_sort algorithm. Build a BST and in order traverse. """ class node: # BST data structure def __init__(self, val): self.val = val self.left = None self.right = None def insert(self, val): if self.val: if val < self.val: if self.left is None: self.left = node(val) else: self.left.insert(val) elif val > self.val: if self.right is None: self.right = node(val) else: self.right.insert(val) else: self.val = val def inorder(root, res): # Recursive traversal if root: inorder(root.left, res) res.append(root.val) inorder(root.right, res) def tree_sort(arr): # Build BST if len(arr) == 0: return arr root = node(arr[0]) for i in range(1, len(arr)): root.insert(arr[i]) # Traverse BST in order. res = [] inorder(root, res) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Peak signal-to-noise ratio - PSNR https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python """ import math import os import cv2 import numpy as np def psnr(original, contrast): mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 PIXEL_MAX = 255.0 PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) return PSNR def main(): dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) # Value expected: 29.73dB print("-- First Test --") print(f"PSNR value is {psnr(original, contrast)} dB") # # Value expected: 31.53dB (Wikipedia Example) print("\n-- Second Test --") print(f"PSNR value is {psnr(original2, contrast2)} dB") if __name__ == "__main__": main()
""" Peak signal-to-noise ratio - PSNR https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python """ import math import os import cv2 import numpy as np def psnr(original, contrast): mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 PIXEL_MAX = 255.0 PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) return PSNR def main(): dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) # Value expected: 29.73dB print("-- First Test --") print(f"PSNR value is {psnr(original, contrast)} dB") # # Value expected: 31.53dB (Wikipedia Example) print("\n-- Second Test --") print(f"PSNR value is {psnr(original2, contrast2)} dB") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Normalization Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized value, x is the value, x_min is the minimum value within the column or list of data, and x_max is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization (particularly Gradient Descent). Standardization Wikipedia: https://en.wikipedia.org/wiki/Standardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as z-score normalization. The equation for standardization is x_std = (x - mu)/(sigma) where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization & Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian (normal) distributions work better with standardization 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: """ Returns a normalized list of values @params: data, a list of values to normalize @returns: a list of normalized values (rounded to ndigits decimal places) @examples: >>> normalization([2, 7, 10, 20, 30, 50]) [0.0, 0.104, 0.167, 0.375, 0.583, 1.0] >>> normalization([5, 10, 15, 20, 25]) [0.0, 0.25, 0.5, 0.75, 1.0] """ # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> list: """ Returns a standardized list of values @params: data, a list of values to standardize @returns: a list of standardized values (rounded to ndigits decimal places) @examples: >>> standardization([2, 7, 10, 20, 30, 50]) [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69] >>> standardization([5, 10, 15, 20, 25]) [-1.265, -0.632, 0.0, 0.632, 1.265] """ # variables for calculation mu = mean(data) sigma = stdev(data) # standardize data return [round((x - mu) / (sigma), ndigits) for x in data]
""" Normalization Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized value, x is the value, x_min is the minimum value within the column or list of data, and x_max is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization (particularly Gradient Descent). Standardization Wikipedia: https://en.wikipedia.org/wiki/Standardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as z-score normalization. The equation for standardization is x_std = (x - mu)/(sigma) where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization & Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian (normal) distributions work better with standardization 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: """ Returns a normalized list of values @params: data, a list of values to normalize @returns: a list of normalized values (rounded to ndigits decimal places) @examples: >>> normalization([2, 7, 10, 20, 30, 50]) [0.0, 0.104, 0.167, 0.375, 0.583, 1.0] >>> normalization([5, 10, 15, 20, 25]) [0.0, 0.25, 0.5, 0.75, 1.0] """ # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> list: """ Returns a standardized list of values @params: data, a list of values to standardize @returns: a list of standardized values (rounded to ndigits decimal places) @examples: >>> standardization([2, 7, 10, 20, 30, 50]) [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69] >>> standardization([5, 10, 15, 20, 25]) [-1.265, -0.632, 0.0, 0.632, 1.265] """ # variables for calculation mu = mean(data) sigma = stdev(data) # standardize data return [round((x - mu) / (sigma), ndigits) for x in data]
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: """ finds where function becomes 0 in [a,b] using bolzano >>> bisection(lambda x: x ** 3 - 1, -5, 5) 1.0000000149011612 >>> bisection(lambda x: x ** 3 - 1, 2, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. >>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 1.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 3.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. """ start: float = a end: float = b if function(a) == 0: # one of the a or b is a root for the function return a elif function(b) == 0: return b elif ( function(a) * function(b) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval.") else: mid: float = start + (end - start) / 2.0 while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7 if function(mid) == 0: return mid elif function(mid) * function(start) < 0: end = mid else: start = mid mid = start + (end - start) / 2.0 return mid def f(x: float) -> float: return x ** 3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
from typing import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: """ finds where function becomes 0 in [a,b] using bolzano >>> bisection(lambda x: x ** 3 - 1, -5, 5) 1.0000000149011612 >>> bisection(lambda x: x ** 3 - 1, 2, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. >>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 1.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 3.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. """ start: float = a end: float = b if function(a) == 0: # one of the a or b is a root for the function return a elif function(b) == 0: return b elif ( function(a) * function(b) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval.") else: mid: float = start + (end - start) / 2.0 while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7 if function(mid) == 0: return mid elif function(mid) * function(start) < 0: end = mid else: start = mid mid = start + (end - start) / 2.0 return mid def f(x: float) -> float: return x ** 3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def points_to_polynomial(coordinates: list[list[int]]) -> str: """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> print(points_to_polynomial([])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[]])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) f(x)=x^2*0.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) f(x)=x^2*0.0+x^1*-0.0+x^0*1.0 >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) f(x)=x^2*0.0+x^1*-0.0+x^0*3.0 >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) f(x)=x^2*0.0+x^1*1.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) f(x)=x^2*1.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) f(x)=x^2*1.0+x^1*-0.0+x^0*2.0 >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0 >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]])) f(x)=x^2*5.0+x^1*-18.0+x^0*18.0 """ try: check = 1 more_check = 0 d = coordinates[0][0] for j in range(len(coordinates)): if j == 0: continue if d == coordinates[j][0]: more_check += 1 solved = "x=" + str(coordinates[j][0]) if more_check == len(coordinates) - 1: check = 2 break elif more_check > 0 and more_check != len(coordinates) - 1: check = 3 else: check = 1 if len(coordinates) == 1 and coordinates[0][0] == 0: check = 2 solved = "x=0" except Exception: check = 3 x = len(coordinates) if check == 1: count_of_line = 0 matrix: list[list[float]] = [] # put the x and x to the power values in a matrix while count_of_line < x: count_in_line = 0 a = coordinates[count_of_line][0] count_line: list[float] = [] while count_in_line < x: count_line.append(a ** (x - (count_in_line + 1))) count_in_line += 1 matrix.append(count_line) count_of_line += 1 count_of_line = 0 # put the y values into a vector vector: list[float] = [] while count_of_line < x: vector.append(coordinates[count_of_line][1]) count_of_line += 1 count = 0 while count < x: zahlen = 0 while zahlen < x: if count == zahlen: zahlen += 1 if zahlen == x: break bruch = matrix[zahlen][count] / matrix[count][count] for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[zahlen][counting_columns] -= item * bruch # manipulating the values in the vector vector[zahlen] -= vector[count] * bruch zahlen += 1 count += 1 count = 0 # make solutions solution: list[str] = [] while count < x: solution.append(str(vector[count] / matrix[count][count])) count += 1 count = 0 solved = "f(x)=" while count < x: remove_e: list[str] = solution[count].split("E") if len(remove_e) > 1: solution[count] = remove_e[0] + "*10^" + remove_e[1] solved += "x^" + str(x - (count + 1)) + "*" + str(solution[count]) if count + 1 != x: solved += "+" count += 1 return solved elif check == 2: return solved else: return "The program cannot work out a fitting polynomial." if __name__ == "__main__": print(points_to_polynomial([])) print(points_to_polynomial([[]])) print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
def points_to_polynomial(coordinates: list[list[int]]) -> str: """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> print(points_to_polynomial([])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[]])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) f(x)=x^2*0.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) f(x)=x^2*0.0+x^1*-0.0+x^0*1.0 >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) f(x)=x^2*0.0+x^1*-0.0+x^0*3.0 >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) f(x)=x^2*0.0+x^1*1.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) f(x)=x^2*1.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) f(x)=x^2*1.0+x^1*-0.0+x^0*2.0 >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0 >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]])) f(x)=x^2*5.0+x^1*-18.0+x^0*18.0 """ try: check = 1 more_check = 0 d = coordinates[0][0] for j in range(len(coordinates)): if j == 0: continue if d == coordinates[j][0]: more_check += 1 solved = "x=" + str(coordinates[j][0]) if more_check == len(coordinates) - 1: check = 2 break elif more_check > 0 and more_check != len(coordinates) - 1: check = 3 else: check = 1 if len(coordinates) == 1 and coordinates[0][0] == 0: check = 2 solved = "x=0" except Exception: check = 3 x = len(coordinates) if check == 1: count_of_line = 0 matrix: list[list[float]] = [] # put the x and x to the power values in a matrix while count_of_line < x: count_in_line = 0 a = coordinates[count_of_line][0] count_line: list[float] = [] while count_in_line < x: count_line.append(a ** (x - (count_in_line + 1))) count_in_line += 1 matrix.append(count_line) count_of_line += 1 count_of_line = 0 # put the y values into a vector vector: list[float] = [] while count_of_line < x: vector.append(coordinates[count_of_line][1]) count_of_line += 1 count = 0 while count < x: zahlen = 0 while zahlen < x: if count == zahlen: zahlen += 1 if zahlen == x: break bruch = matrix[zahlen][count] / matrix[count][count] for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[zahlen][counting_columns] -= item * bruch # manipulating the values in the vector vector[zahlen] -= vector[count] * bruch zahlen += 1 count += 1 count = 0 # make solutions solution: list[str] = [] while count < x: solution.append(str(vector[count] / matrix[count][count])) count += 1 count = 0 solved = "f(x)=" while count < x: remove_e: list[str] = solution[count].split("E") if len(remove_e) > 1: solution[count] = remove_e[0] + "*10^" + remove_e[1] solved += "x^" + str(x - (count + 1)) + "*" + str(solution[count]) if count + 1 != x: solved += "+" count += 1 return solved elif check == 2: return solved else: return "The program cannot work out a fitting polynomial." if __name__ == "__main__": print(points_to_polynomial([])) print(points_to_polynomial([[]])) print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ import numpy as np class Decision_Tree: def __init__(self, depth=5, min_leaf_size=5): self.depth = depth self.decision_boundary = 0 self.left = None self.right = None self.min_leaf_size = min_leaf_size self.prediction = None def mean_squared_error(self, labels, prediction): """ mean_squared_error: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: mean_squared_error calculates the error if prediction is used to estimate the labels >>> tester = Decision_Tree() >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) >>> test_prediction = np.float(6) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True >>> test_labels = np.array([1,2,3]) >>> test_prediction = np.float(2) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True """ if labels.ndim != 1: print("Error: Input labels must be one dimensional") return np.mean((labels - prediction) ** 2) def train(self, X, y): """ train: @param X: a one dimensional numpy array @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value """ """ this section is to check that the inputs conform to our dimensionality constraints """ if X.ndim != 1: print("Error: Input data set must be one dimensional") return if len(X) != len(y): print("Error: X and y have different lengths") return if y.ndim != 1: print("Error: Data set labels must be one dimensional") return if len(X) < 2 * self.min_leaf_size: self.prediction = np.mean(y) return if self.depth == 1: self.prediction = np.mean(y) return best_split = 0 min_error = self.mean_squared_error(X, np.mean(y)) * 2 """ loop over all possible splits for the decision tree. find the best split. if no split exists that is less than 2 * error for the entire array then the data set is not split and the average for the entire array is used as the predictor """ for i in range(len(X)): if len(X[:i]) < self.min_leaf_size: continue elif len(X[i:]) < self.min_leaf_size: continue else: error_left = self.mean_squared_error(X[:i], np.mean(y[:i])) error_right = self.mean_squared_error(X[i:], np.mean(y[i:])) error = error_left + error_right if error < min_error: best_split = i min_error = error if best_split != 0: left_X = X[:best_split] left_y = y[:best_split] right_X = X[best_split:] right_y = y[best_split:] self.decision_boundary = X[best_split] self.left = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.right = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.left.train(left_X, left_y) self.right.train(right_X, right_y) else: self.prediction = np.mean(y) return def predict(self, x): """ predict: @param x: a floating point value to predict the label of the prediction function works by recursively calling the predict function of the appropriate subtrees based on the tree's decision boundary """ if self.prediction is not None: return self.prediction elif self.left or self.right is not None: if x >= self.decision_boundary: return self.right.predict(x) else: return self.left.predict(x) else: print("Error: Decision tree not yet trained") return None class Test_Decision_Tree: """Decision Tres test class""" @staticmethod def helper_mean_squared_error_test(labels, prediction): """ helper_mean_squared_error_test: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: helper_mean_squared_error_test calculates the mean squared error """ squared_error_sum = np.float(0) for label in labels: squared_error_sum += (label - prediction) ** 2 return np.float(squared_error_sum / labels.size) def main(): """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed. """ X = np.arange(-1.0, 1.0, 0.005) y = np.sin(X) tree = Decision_Tree(depth=10, min_leaf_size=10) tree.train(X, y) test_cases = (np.random.rand(10) * 2) - 1 predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) print("Test values: " + str(test_cases)) print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error)) if __name__ == "__main__": main() import doctest doctest.testmod(name="mean_squarred_error", verbose=True)
""" Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ import numpy as np class Decision_Tree: def __init__(self, depth=5, min_leaf_size=5): self.depth = depth self.decision_boundary = 0 self.left = None self.right = None self.min_leaf_size = min_leaf_size self.prediction = None def mean_squared_error(self, labels, prediction): """ mean_squared_error: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: mean_squared_error calculates the error if prediction is used to estimate the labels >>> tester = Decision_Tree() >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) >>> test_prediction = np.float(6) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True >>> test_labels = np.array([1,2,3]) >>> test_prediction = np.float(2) >>> tester.mean_squared_error(test_labels, test_prediction) == ( ... Test_Decision_Tree.helper_mean_squared_error_test(test_labels, ... test_prediction)) True """ if labels.ndim != 1: print("Error: Input labels must be one dimensional") return np.mean((labels - prediction) ** 2) def train(self, X, y): """ train: @param X: a one dimensional numpy array @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value """ """ this section is to check that the inputs conform to our dimensionality constraints """ if X.ndim != 1: print("Error: Input data set must be one dimensional") return if len(X) != len(y): print("Error: X and y have different lengths") return if y.ndim != 1: print("Error: Data set labels must be one dimensional") return if len(X) < 2 * self.min_leaf_size: self.prediction = np.mean(y) return if self.depth == 1: self.prediction = np.mean(y) return best_split = 0 min_error = self.mean_squared_error(X, np.mean(y)) * 2 """ loop over all possible splits for the decision tree. find the best split. if no split exists that is less than 2 * error for the entire array then the data set is not split and the average for the entire array is used as the predictor """ for i in range(len(X)): if len(X[:i]) < self.min_leaf_size: continue elif len(X[i:]) < self.min_leaf_size: continue else: error_left = self.mean_squared_error(X[:i], np.mean(y[:i])) error_right = self.mean_squared_error(X[i:], np.mean(y[i:])) error = error_left + error_right if error < min_error: best_split = i min_error = error if best_split != 0: left_X = X[:best_split] left_y = y[:best_split] right_X = X[best_split:] right_y = y[best_split:] self.decision_boundary = X[best_split] self.left = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.right = Decision_Tree( depth=self.depth - 1, min_leaf_size=self.min_leaf_size ) self.left.train(left_X, left_y) self.right.train(right_X, right_y) else: self.prediction = np.mean(y) return def predict(self, x): """ predict: @param x: a floating point value to predict the label of the prediction function works by recursively calling the predict function of the appropriate subtrees based on the tree's decision boundary """ if self.prediction is not None: return self.prediction elif self.left or self.right is not None: if x >= self.decision_boundary: return self.right.predict(x) else: return self.left.predict(x) else: print("Error: Decision tree not yet trained") return None class Test_Decision_Tree: """Decision Tres test class""" @staticmethod def helper_mean_squared_error_test(labels, prediction): """ helper_mean_squared_error_test: @param labels: a one dimensional numpy array @param prediction: a floating point value return value: helper_mean_squared_error_test calculates the mean squared error """ squared_error_sum = np.float(0) for label in labels: squared_error_sum += (label - prediction) ** 2 return np.float(squared_error_sum / labels.size) def main(): """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed. """ X = np.arange(-1.0, 1.0, 0.005) y = np.sin(X) tree = Decision_Tree(depth=10, min_leaf_size=10) tree.train(X, y) test_cases = (np.random.rand(10) * 2) - 1 predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) print("Test values: " + str(test_cases)) print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error)) if __name__ == "__main__": main() import doctest doctest.testmod(name="mean_squarred_error", verbose=True)
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function """ from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 >>> gaussian(1, 4, 2) 0.06475879783294587 >>> gaussian(1, 5, 3) 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma ** 2) * exp(-((x - mu) ** 2) / (2 * sigma ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function """ from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 >>> gaussian(1, 4, 2) 0.06475879783294587 >>> gaussian(1, 5, 3) 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma ** 2) * exp(-((x - mu) ** 2) / (2 * sigma ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
JFIFC     C  "  L !1AQ"aq2 #BR$3bCr4DS %&5cs<!1AQ"aq2#B3R$br4 ?N49 Ԑz?{!yV4J&9gPZs)o9D`'>vO.~l-yl6؃&vg*Z;R>UTD|~dZB> sը);Iȍb˭%4I`~ֶMvNxNNa6Cָ!K4K;rkg=VtIB4ʂ]5&<Zŕ.ց9ԓ=3Í/u Bܙ4-, \&T^#SNϣҐ<CRb>lKt2B,"B΅C9؂-ʅI$ӕ5Dh ay 2j2Nץ5Zʛ%2|@7NRu K'Q(ZBBBwsnm_mP :Nn$,AܒOϺ4*93"<WXo9]В%|^zDGwB  &4jm%OPV6vAXUQH)IJs-KH$e^sKvZ%H$@ bu$D|c :PiH 78g!ФƇk@>Gcu4TAK O+CAKpĥ<B,D sk~eD:T{Cϗם{/ n%!˩Iנ AHXBe–͐i_,)Ƴ8S6q+rT-*Y1[~zR$"H}U YOC?K}RPgM<!6NKmLP 'Y*7I2O!d>L\@1oƲ 饦麁s^PA9_+Xb>?'JJJ\ԡ IuuSJLV|[n9\yhԲx\/!ne^CMm+w*RtN6J#0L>KV]{ Au *IHRڢ{K{M* ꖣ07rYP KnF4X)XKn&EЍto-\e%CCoJSa.xAyoΊ^">iisEC hHMLkt^R oiF Ioa $,x`'Cî)GA s?{$2][*[fS*Iͩ)T2J |:ya^ (j(n g]'elғ*x<d:(jL ":u}2t ̥﯐?bsR1ܢӀӤ)9Zu 6Kf ˖m- }9|pD:ہ@ A>ZͻV}BIDh:mjg+kD{I/ u0|ڋ,HdO[g܆XK2mmp8R`9ءS.%Nwrp01VIJ@3ݑw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kh4@BҠ9xkZ ۭT/D:R|C}m*ʡG* WVL
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Return an image of 16 generations of one-dimensional cellular automata based on a given ruleset number https://mathworld.wolfram.com/ElementaryCellularAutomaton.html """ from __future__ import annotations from PIL import Image # Define the first generation of cells # fmt: off CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # fmt: on def format_ruleset(ruleset: int) -> list[int]: """ >>> format_ruleset(11100) [0, 0, 0, 1, 1, 1, 0, 0] >>> format_ruleset(0) [0, 0, 0, 0, 0, 0, 0, 0] >>> format_ruleset(11111111) [1, 1, 1, 1, 1, 1, 1, 1] """ return [int(c) for c in f"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: """ Convert the cells into a greyscale PIL.Image.Image and return it to the caller. >>> from random import random >>> cells = [[random() for w in range(31)] for h in range(16)] >>> img = generate_image(cells) >>> isinstance(img, Image.Image) True >>> img.width, img.height (31, 16) """ # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") img.show()
""" Return an image of 16 generations of one-dimensional cellular automata based on a given ruleset number https://mathworld.wolfram.com/ElementaryCellularAutomaton.html """ from __future__ import annotations from PIL import Image # Define the first generation of cells # fmt: off CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # fmt: on def format_ruleset(ruleset: int) -> list[int]: """ >>> format_ruleset(11100) [0, 0, 0, 1, 1, 1, 0, 0] >>> format_ruleset(0) [0, 0, 0, 0, 0, 0, 0, 0] >>> format_ruleset(11111111) [1, 1, 1, 1, 1, 1, 1, 1] """ return [int(c) for c in f"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: """ Convert the cells into a greyscale PIL.Image.Image and return it to the caller. >>> from random import random >>> cells = [[random() for w in range(31)] for h in range(16)] >>> img = generate_image(cells) >>> isinstance(img, Image.Image) True >>> img.width, img.height (31, 16) """ # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") img.show()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for i in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for i in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/Tree_traversal from dataclasses import dataclass from typing import Optional @dataclass class Node: data: int left: Optional["Node"] = None right: Optional["Node"] = None def make_tree() -> Node: return Node(1, Node(2, Node(4), Node(5)), Node(3)) def preorder(root: Node): """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node): """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node): """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node): """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order_1(root: Node): """ Print whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ if not root: return temp = root que = [temp] while len(que) > 0: print(que[0].data, end=" ") temp = que.pop(0) if temp.left: que.append(temp.left) if temp.right: que.append(temp.right) return que def level_order_2(root: Node, level: int): """ Level-wise traversal: Print all nodes present at the given level of the binary tree """ if not root: return root if level == 1: print(root.data, end=" ") elif level > 1: level_order_2(root.left, level - 1) level_order_2(root.right, level - 1) def print_left_to_right(root: Node, level: int): """ Print elements on particular level from left to right direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_left_to_right(root.left, level - 1) print_left_to_right(root.right, level - 1) def print_right_to_left(root: Node, level: int): """ Print elements on particular level from right to left direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_right_to_left(root.right, level - 1) print_right_to_left(root.left, level - 1) def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: print_right_to_left(root, h) flag = 0 def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversal is {postorder(root)}") print(f"Height of Tree is {height(root)}") print("Complete Level Order Traversal is : ") level_order_1(root) print("\nLevel-wise order Traversal is : ") for h in range(1, height(root) + 1): level_order_2(root, h) print("\nZigZag order Traversal is : ") zigzag(root) print() if __name__ == "__main__": import doctest doctest.testmod() main()
# https://en.wikipedia.org/wiki/Tree_traversal from dataclasses import dataclass from typing import Optional @dataclass class Node: data: int left: Optional["Node"] = None right: Optional["Node"] = None def make_tree() -> Node: return Node(1, Node(2, Node(4), Node(5)), Node(3)) def preorder(root: Node): """ Pre-order traversal visits root node, left subtree, right subtree. >>> preorder(make_tree()) [1, 2, 4, 5, 3] """ return [root.data] + preorder(root.left) + preorder(root.right) if root else [] def postorder(root: Node): """ Post-order traversal visits left subtree, right subtree, root node. >>> postorder(make_tree()) [4, 5, 2, 3, 1] """ return postorder(root.left) + postorder(root.right) + [root.data] if root else [] def inorder(root: Node): """ In-order traversal visits left subtree, root node, right subtree. >>> inorder(make_tree()) [4, 2, 5, 1, 3] """ return inorder(root.left) + [root.data] + inorder(root.right) if root else [] def height(root: Node): """ Recursive function for calculating the height of the binary tree. >>> height(None) 0 >>> height(make_tree()) 3 """ return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order_1(root: Node): """ Print whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. """ if not root: return temp = root que = [temp] while len(que) > 0: print(que[0].data, end=" ") temp = que.pop(0) if temp.left: que.append(temp.left) if temp.right: que.append(temp.right) return que def level_order_2(root: Node, level: int): """ Level-wise traversal: Print all nodes present at the given level of the binary tree """ if not root: return root if level == 1: print(root.data, end=" ") elif level > 1: level_order_2(root.left, level - 1) level_order_2(root.right, level - 1) def print_left_to_right(root: Node, level: int): """ Print elements on particular level from left to right direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_left_to_right(root.left, level - 1) print_left_to_right(root.right, level - 1) def print_right_to_left(root: Node, level: int): """ Print elements on particular level from right to left direction of the binary tree. """ if not root: return if level == 1: print(root.data, end=" ") elif level > 1: print_right_to_left(root.right, level - 1) print_right_to_left(root.left, level - 1) def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: print_right_to_left(root, h) flag = 0 def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversal is {postorder(root)}") print(f"Height of Tree is {height(root)}") print("Complete Level Order Traversal is : ") level_order_1(root) print("\nLevel-wise order Traversal is : ") for h in range(1, height(root) + 1): level_order_2(root, h) print("\nZigZag order Traversal is : ") zigzag(root) print() if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
4,359
fix(ci): Update pre-commit hooks and apply new black
Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2021-04-26T04:41:57Z"
"2021-04-26T05:46:50Z"
69457357e8c6a3530034aca9707e22ce769da067
6f21f76696ff6657bff6fc2239315a1650924190
fix(ci): Update pre-commit hooks and apply new black. Ref: - https://github.com/psf/black/pull/1740 (New formatting) - https://github.com/psf/black/releases/tag/21.4b0 ### **Describe your change:** * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 77: https://projecteuler.net/problem=77 It is possible to write ten as the sum of primes in exactly five different ways: 7 + 3 5 + 5 5 + 3 + 2 3 + 3 + 2 + 2 2 + 2 + 2 + 2 + 2 What is the first value which can be written as the sum of primes in over five thousand different ways? """ from functools import lru_cache from math import ceil from typing import Optional, Set NUM_PRIMES = 100 primes = set(range(3, NUM_PRIMES, 2)) primes.add(2) prime: int for prime in range(3, ceil(NUM_PRIMES ** 0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100) def partition(number_to_partition: int) -> Set[int]: """ Return a set of integers corresponding to unique prime partitions of n. The unique prime partitions can be represented as unique prime decompositions, e.g. (7+3) <-> 7*3 = 12, (3+3+2+2) = 3*3*2*2 = 36 >>> partition(10) {32, 36, 21, 25, 30} >>> partition(15) {192, 160, 105, 44, 112, 243, 180, 150, 216, 26, 125, 126} >>> len(partition(20)) 26 """ if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} ret: Set[int] = set() prime: int sub: int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime): ret.add(sub * prime) return ret def solution(number_unique_partitions: int = 5000) -> Optional[int]: """ Return the smallest integer that can be written as the sum of primes in over m unique ways. >>> solution(4) 10 >>> solution(500) 45 >>> solution(1000) 53 """ for number_to_partition in range(1, NUM_PRIMES): if len(partition(number_to_partition)) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 77: https://projecteuler.net/problem=77 It is possible to write ten as the sum of primes in exactly five different ways: 7 + 3 5 + 5 5 + 3 + 2 3 + 3 + 2 + 2 2 + 2 + 2 + 2 + 2 What is the first value which can be written as the sum of primes in over five thousand different ways? """ from functools import lru_cache from math import ceil from typing import Optional, Set NUM_PRIMES = 100 primes = set(range(3, NUM_PRIMES, 2)) primes.add(2) prime: int for prime in range(3, ceil(NUM_PRIMES ** 0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100) def partition(number_to_partition: int) -> Set[int]: """ Return a set of integers corresponding to unique prime partitions of n. The unique prime partitions can be represented as unique prime decompositions, e.g. (7+3) <-> 7*3 = 12, (3+3+2+2) = 3*3*2*2 = 36 >>> partition(10) {32, 36, 21, 25, 30} >>> partition(15) {192, 160, 105, 44, 112, 243, 180, 150, 216, 26, 125, 126} >>> len(partition(20)) 26 """ if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} ret: Set[int] = set() prime: int sub: int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime): ret.add(sub * prime) return ret def solution(number_unique_partitions: int = 5000) -> Optional[int]: """ Return the smallest integer that can be written as the sum of primes in over m unique ways. >>> solution(4) 10 >>> solution(500) 45 >>> solution(1000) 53 """ for number_to_partition in range(1, NUM_PRIMES): if len(partition(number_to_partition)) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"{solution() = }")
-1