mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-10-05 21:29:29 +00:00
Compare commits
7 Commits
dad5ee5a5a
...
7fa47ea6e5
Author | SHA1 | Date | |
---|---|---|---|
|
7fa47ea6e5 | ||
|
fcf82a1eda | ||
|
ad6395d340 | ||
|
50aca04c67 | ||
|
5a8655d306 | ||
|
c84aca23a8 | ||
|
3cd92013ab |
|
@ -96,7 +96,7 @@ We want your work to be readable by others; therefore, we encourage you to note
|
|||
|
||||
```bash
|
||||
python3 -m pip install ruff # only required the first time
|
||||
ruff .
|
||||
ruff check
|
||||
```
|
||||
|
||||
- Original code submission require docstrings or comments to describe your work.
|
||||
|
|
38
data_structures/stacks/lexicographical_numbers.py
Normal file
38
data_structures/stacks/lexicographical_numbers.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
from collections.abc import Iterator
|
||||
|
||||
|
||||
def lexical_order(max_number: int) -> Iterator[int]:
|
||||
"""
|
||||
Generate numbers in lexical order from 1 to max_number.
|
||||
|
||||
>>> " ".join(map(str, lexical_order(13)))
|
||||
'1 10 11 12 13 2 3 4 5 6 7 8 9'
|
||||
>>> list(lexical_order(1))
|
||||
[1]
|
||||
>>> " ".join(map(str, lexical_order(20)))
|
||||
'1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
|
||||
>>> " ".join(map(str, lexical_order(25)))
|
||||
'1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 3 4 5 6 7 8 9'
|
||||
>>> list(lexical_order(12))
|
||||
[1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
"""
|
||||
|
||||
stack = [1]
|
||||
|
||||
while stack:
|
||||
num = stack.pop()
|
||||
if num > max_number:
|
||||
continue
|
||||
|
||||
yield num
|
||||
if (num % 10) != 9:
|
||||
stack.append(num + 1)
|
||||
|
||||
stack.append(num * 10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from doctest import testmod
|
||||
|
||||
testmod()
|
||||
print(f"Numbers from 1 to 25 in lexical order: {list(lexical_order(26))}")
|
|
@ -28,6 +28,24 @@ def longest_common_subsequence(x: str, y: str):
|
|||
(2, 'ph')
|
||||
>>> longest_common_subsequence("computer", "food")
|
||||
(1, 'o')
|
||||
>>> longest_common_subsequence("", "abc") # One string is empty
|
||||
(0, '')
|
||||
>>> longest_common_subsequence("abc", "") # Other string is empty
|
||||
(0, '')
|
||||
>>> longest_common_subsequence("", "") # Both strings are empty
|
||||
(0, '')
|
||||
>>> longest_common_subsequence("abc", "def") # No common subsequence
|
||||
(0, '')
|
||||
>>> longest_common_subsequence("abc", "abc") # Identical strings
|
||||
(3, 'abc')
|
||||
>>> longest_common_subsequence("a", "a") # Single character match
|
||||
(1, 'a')
|
||||
>>> longest_common_subsequence("a", "b") # Single character no match
|
||||
(0, '')
|
||||
>>> longest_common_subsequence("abcdef", "ace") # Interleaved subsequence
|
||||
(3, 'ace')
|
||||
>>> longest_common_subsequence("ABCD", "ACBD") # No repeated characters
|
||||
(3, 'ABD')
|
||||
"""
|
||||
# find the length of strings
|
||||
|
||||
|
|
|
@ -14,6 +14,18 @@ class DirectedGraph:
|
|||
# adding the weight is optional
|
||||
# handles repetition
|
||||
def add_pair(self, u, v, w=1):
|
||||
"""
|
||||
Adds a directed edge u->v with weight w.
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.add_pair(-1,2)
|
||||
>>> dg.add_pair(1,3,5)
|
||||
>>> dg.add_pair(1,3,5)
|
||||
>>> dg.add_pair(1,3,6)
|
||||
>>> dg.all_nodes()
|
||||
[-1, 2, 1, 3]
|
||||
>>> dg.graph[1]
|
||||
[[5, 3], [6, 3]]
|
||||
"""
|
||||
if self.graph.get(u):
|
||||
if self.graph[u].count([w, v]) == 0:
|
||||
self.graph[u].append([w, v])
|
||||
|
@ -23,10 +35,36 @@ class DirectedGraph:
|
|||
self.graph[v] = []
|
||||
|
||||
def all_nodes(self):
|
||||
"""
|
||||
Returns list of all nodes in the graph.
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.all_nodes()
|
||||
[]
|
||||
>>> dg.add_pair(1,1)
|
||||
>>> dg.all_nodes()
|
||||
[1]
|
||||
>>> dg.add_pair(2,3,3)
|
||||
>>> dg.all_nodes()
|
||||
[1, 2, 3]
|
||||
"""
|
||||
return list(self.graph)
|
||||
|
||||
# handles if the input does not exist
|
||||
def remove_pair(self, u, v):
|
||||
"""
|
||||
Removes all edges u->v if it exists.
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.remove_pair(1,2) # silently exits
|
||||
>>> dg.add_pair(0,5,2)
|
||||
>>> dg.graph[0]
|
||||
[[2, 5]]
|
||||
>>> dg.remove_pair(5,0)
|
||||
>>> dg.graph[0]
|
||||
[[2, 5]]
|
||||
>>> dg.remove_pair(0,5)
|
||||
>>> dg.graph[0]
|
||||
[]
|
||||
"""
|
||||
if self.graph.get(u):
|
||||
for _ in self.graph[u]:
|
||||
if _[1] == v:
|
||||
|
@ -34,42 +72,57 @@ class DirectedGraph:
|
|||
|
||||
# if no destination is meant the default value is -1
|
||||
def dfs(self, s=-2, d=-1):
|
||||
if s == d:
|
||||
return []
|
||||
"""
|
||||
Performs depth first search from s to find d.
|
||||
Returns the path s->d as a list.
|
||||
Returns dfs from s if d is not found
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.dfs()
|
||||
[]
|
||||
>>> dg.add_pair(1,1)
|
||||
>>> dg.dfs(1,1)
|
||||
[1]
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.add_pair(0,1)
|
||||
>>> dg.add_pair(0,2)
|
||||
>>> dg.add_pair(1,3)
|
||||
>>> dg.add_pair(1,4)
|
||||
>>> dg.add_pair(1,5)
|
||||
>>> dg.add_pair(2,5)
|
||||
>>> dg.add_pair(5,6)
|
||||
>>> dg.dfs(0,6)
|
||||
[0, 2, 5, 6]
|
||||
>>> dg.dfs(1,6)
|
||||
[1, 5, 6]
|
||||
>>> dg.dfs()
|
||||
[0, 2, 5, 6, 1, 4, 3]
|
||||
>>> dg.dfs(1,0)
|
||||
[1, 5, 6, 4, 3]
|
||||
"""
|
||||
stack = []
|
||||
visited = []
|
||||
if s == -2:
|
||||
s = next(iter(self.graph))
|
||||
stack.append(s)
|
||||
visited.append(s)
|
||||
ss = s
|
||||
|
||||
while True:
|
||||
# check if there is any non isolated nodes
|
||||
if len(self.graph[s]) != 0:
|
||||
ss = s
|
||||
for node in self.graph[s]:
|
||||
if visited.count(node[1]) < 1:
|
||||
if node[1] == d:
|
||||
visited.append(d)
|
||||
return visited
|
||||
else:
|
||||
stack.append(node[1])
|
||||
visited.append(node[1])
|
||||
ss = node[1]
|
||||
break
|
||||
|
||||
# check if all the children are visited
|
||||
if s == ss:
|
||||
stack.pop()
|
||||
if len(stack) != 0:
|
||||
s = stack[len(stack) - 1]
|
||||
if self.graph.get(s, None):
|
||||
pass # -2 is a node
|
||||
elif len(self.graph) > 0:
|
||||
s = next(iter(self.graph))
|
||||
else:
|
||||
s = ss
|
||||
return [] # Graph empty
|
||||
stack.append(s)
|
||||
|
||||
# check if se have reached the starting point
|
||||
if len(stack) == 0:
|
||||
return visited
|
||||
# Run dfs
|
||||
while len(stack) > 0:
|
||||
s = stack.pop()
|
||||
visited.append(s)
|
||||
# If reached d, return
|
||||
if s == d:
|
||||
break
|
||||
|
||||
# add not visited child nodes to stack
|
||||
for _, ss in self.graph[s]:
|
||||
if visited.count(ss) < 1:
|
||||
stack.append(ss)
|
||||
return visited
|
||||
|
||||
# c is the count of nodes you want and if you leave it or pass -1 to the function
|
||||
# the count will be random from 10 to 10000
|
||||
|
@ -84,12 +137,42 @@ class DirectedGraph:
|
|||
self.add_pair(i, n, 1)
|
||||
|
||||
def bfs(self, s=-2):
|
||||
"""
|
||||
Performs breadth first search from s
|
||||
Returns list.
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.bfs()
|
||||
[]
|
||||
>>> dg.add_pair(1,1)
|
||||
>>> dg.bfs(1)
|
||||
[1]
|
||||
>>> dg = DirectedGraph()
|
||||
>>> dg.add_pair(0,1)
|
||||
>>> dg.add_pair(0,2)
|
||||
>>> dg.add_pair(1,3)
|
||||
>>> dg.add_pair(1,4)
|
||||
>>> dg.add_pair(1,5)
|
||||
>>> dg.add_pair(2,5)
|
||||
>>> dg.add_pair(5,6)
|
||||
>>> dg.bfs(0)
|
||||
[0, 1, 2, 3, 4, 5, 6]
|
||||
>>> dg.bfs(1)
|
||||
[1, 3, 4, 5, 6]
|
||||
>>> dg.bfs()
|
||||
[0, 1, 2, 3, 4, 5, 6]
|
||||
"""
|
||||
d = deque()
|
||||
visited = []
|
||||
if s == -2:
|
||||
s = next(iter(self.graph))
|
||||
if self.graph.get(s, None):
|
||||
pass # -2 is a node
|
||||
elif len(self.graph) > 0:
|
||||
s = next(iter(self.graph))
|
||||
else:
|
||||
return [] # Graph empty
|
||||
d.append(s)
|
||||
visited.append(s)
|
||||
# Run bfs
|
||||
while d:
|
||||
s = d.popleft()
|
||||
if len(self.graph[s]) != 0:
|
||||
|
@ -300,42 +383,60 @@ class Graph:
|
|||
|
||||
# if no destination is meant the default value is -1
|
||||
def dfs(self, s=-2, d=-1):
|
||||
if s == d:
|
||||
return []
|
||||
"""
|
||||
Performs depth first search from s to find d.
|
||||
Returns the path s->d as a list.
|
||||
Returns dfs from s if d is not found
|
||||
>>> ug = Graph()
|
||||
>>> ug.dfs()
|
||||
[]
|
||||
>>> ug.add_pair(1,1)
|
||||
>>> ug.dfs(1,1)
|
||||
[1]
|
||||
>>> ug = Graph()
|
||||
>>> ug.add_pair(0,1)
|
||||
>>> ug.add_pair(0,2)
|
||||
>>> ug.add_pair(1,3)
|
||||
>>> ug.add_pair(1,4)
|
||||
>>> ug.add_pair(1,5)
|
||||
>>> ug.add_pair(2,5)
|
||||
>>> ug.add_pair(5,6)
|
||||
>>> ug.dfs(0,6)
|
||||
[0, 2, 5, 6]
|
||||
>>> ug.dfs(1,6)
|
||||
[1, 5, 6]
|
||||
>>> ug.dfs()
|
||||
[0, 2, 5, 6, 1, 4, 3]
|
||||
>>> ug.dfs(1,0)
|
||||
[1, 5, 6, 2, 0]
|
||||
"""
|
||||
stack = []
|
||||
visited = []
|
||||
if s == -2:
|
||||
s = next(iter(self.graph))
|
||||
stack.append(s)
|
||||
visited.append(s)
|
||||
ss = s
|
||||
|
||||
while True:
|
||||
# check if there is any non isolated nodes
|
||||
if len(self.graph[s]) != 0:
|
||||
ss = s
|
||||
for node in self.graph[s]:
|
||||
if visited.count(node[1]) < 1:
|
||||
if node[1] == d:
|
||||
visited.append(d)
|
||||
return visited
|
||||
else:
|
||||
stack.append(node[1])
|
||||
visited.append(node[1])
|
||||
ss = node[1]
|
||||
break
|
||||
|
||||
# check if all the children are visited
|
||||
if s == ss:
|
||||
stack.pop()
|
||||
if len(stack) != 0:
|
||||
s = stack[len(stack) - 1]
|
||||
if self.graph.get(s, None):
|
||||
pass # -2 is a node
|
||||
elif len(self.graph) > 0:
|
||||
s = next(iter(self.graph))
|
||||
else:
|
||||
s = ss
|
||||
return [] # Graph empty
|
||||
stack.append(s)
|
||||
|
||||
# check if se have reached the starting point
|
||||
if len(stack) == 0:
|
||||
return visited
|
||||
# Run dfs
|
||||
while len(stack) > 0:
|
||||
s = stack.pop()
|
||||
if visited.count(s) == 1:
|
||||
continue
|
||||
else:
|
||||
visited.append(s)
|
||||
# If reached d, return
|
||||
if s == d:
|
||||
break
|
||||
|
||||
# add not visited child nodes to stack
|
||||
for _, ss in self.graph[s]:
|
||||
if visited.count(ss) < 1:
|
||||
stack.append(ss)
|
||||
return visited
|
||||
|
||||
# c is the count of nodes you want and if you leave it or pass -1 to the function
|
||||
# the count will be random from 10 to 10000
|
||||
|
@ -350,10 +451,39 @@ class Graph:
|
|||
self.add_pair(i, n, 1)
|
||||
|
||||
def bfs(self, s=-2):
|
||||
"""
|
||||
Performs breadth first search from s
|
||||
Returns list.
|
||||
>>> ug = Graph()
|
||||
>>> ug.bfs()
|
||||
[]
|
||||
>>> ug.add_pair(1,1)
|
||||
>>> ug.bfs(1)
|
||||
[1]
|
||||
>>> ug = Graph()
|
||||
>>> ug.add_pair(0,1)
|
||||
>>> ug.add_pair(0,2)
|
||||
>>> ug.add_pair(1,3)
|
||||
>>> ug.add_pair(1,4)
|
||||
>>> ug.add_pair(1,5)
|
||||
>>> ug.add_pair(2,5)
|
||||
>>> ug.add_pair(5,6)
|
||||
>>> ug.bfs(0)
|
||||
[0, 1, 2, 3, 4, 5, 6]
|
||||
>>> ug.bfs(1)
|
||||
[1, 0, 3, 4, 5, 2, 6]
|
||||
>>> ug.bfs()
|
||||
[0, 1, 2, 3, 4, 5, 6]
|
||||
"""
|
||||
d = deque()
|
||||
visited = []
|
||||
if s == -2:
|
||||
s = next(iter(self.graph))
|
||||
if self.graph.get(s, None):
|
||||
pass # -2 is a node
|
||||
elif len(self.graph) > 0:
|
||||
s = next(iter(self.graph))
|
||||
else:
|
||||
return [] # Graph empty
|
||||
d.append(s)
|
||||
visited.append(s)
|
||||
while d:
|
||||
|
|
113
searches/exponential_search.py
Normal file
113
searches/exponential_search.py
Normal file
|
@ -0,0 +1,113 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Pure Python implementation of exponential search algorithm
|
||||
|
||||
For more information, see the Wikipedia page:
|
||||
https://en.wikipedia.org/wiki/Exponential_search
|
||||
|
||||
For doctests run the following command:
|
||||
python3 -m doctest -v exponential_search.py
|
||||
|
||||
For manual testing run:
|
||||
python3 exponential_search.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def binary_search_by_recursion(
|
||||
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
|
||||
) -> int:
|
||||
"""Pure implementation of binary search algorithm in Python using recursion
|
||||
|
||||
Be careful: the collection must be ascending sorted otherwise, the result will be
|
||||
unpredictable.
|
||||
|
||||
:param sorted_collection: some ascending sorted collection with comparable items
|
||||
:param item: item value to search
|
||||
:param left: starting index for the search
|
||||
:param right: ending index for the search
|
||||
:return: index of the found item or -1 if the item is not found
|
||||
|
||||
Examples:
|
||||
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4)
|
||||
0
|
||||
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4)
|
||||
4
|
||||
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4)
|
||||
1
|
||||
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
|
||||
-1
|
||||
"""
|
||||
if right < 0:
|
||||
right = len(sorted_collection) - 1
|
||||
if list(sorted_collection) != sorted(sorted_collection):
|
||||
raise ValueError("sorted_collection must be sorted in ascending order")
|
||||
if right < left:
|
||||
return -1
|
||||
|
||||
midpoint = left + (right - left) // 2
|
||||
|
||||
if sorted_collection[midpoint] == item:
|
||||
return midpoint
|
||||
elif sorted_collection[midpoint] > item:
|
||||
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
|
||||
else:
|
||||
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
|
||||
|
||||
|
||||
def exponential_search(sorted_collection: list[int], item: int) -> int:
|
||||
"""
|
||||
Pure implementation of an exponential search algorithm in Python.
|
||||
For more information, refer to:
|
||||
https://en.wikipedia.org/wiki/Exponential_search
|
||||
|
||||
Be careful: the collection must be ascending sorted, otherwise the result will be
|
||||
unpredictable.
|
||||
|
||||
:param sorted_collection: some ascending sorted collection with comparable items
|
||||
:param item: item value to search
|
||||
:return: index of the found item or -1 if the item is not found
|
||||
|
||||
The time complexity of this algorithm is O(log i) where i is the index of the item.
|
||||
|
||||
Examples:
|
||||
>>> exponential_search([0, 5, 7, 10, 15], 0)
|
||||
0
|
||||
>>> exponential_search([0, 5, 7, 10, 15], 15)
|
||||
4
|
||||
>>> exponential_search([0, 5, 7, 10, 15], 5)
|
||||
1
|
||||
>>> exponential_search([0, 5, 7, 10, 15], 6)
|
||||
-1
|
||||
"""
|
||||
if list(sorted_collection) != sorted(sorted_collection):
|
||||
raise ValueError("sorted_collection must be sorted in ascending order")
|
||||
|
||||
if sorted_collection[0] == item:
|
||||
return 0
|
||||
|
||||
bound = 1
|
||||
while bound < len(sorted_collection) and sorted_collection[bound] < item:
|
||||
bound *= 2
|
||||
|
||||
left = bound // 2
|
||||
right = min(bound, len(sorted_collection) - 1)
|
||||
return binary_search_by_recursion(sorted_collection, item, left, right)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
||||
# Manual testing
|
||||
user_input = input("Enter numbers separated by commas: ").strip()
|
||||
collection = sorted(int(item) for item in user_input.split(","))
|
||||
target = int(input("Enter a number to search for: "))
|
||||
result = exponential_search(sorted_collection=collection, item=target)
|
||||
if result == -1:
|
||||
print(f"{target} was not found in {collection}.")
|
||||
else:
|
||||
print(f"{target} was found at index {result} in {collection}.")
|
Loading…
Reference in New Issue
Block a user