mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-03-11 17:19:48 +00:00
Compare commits
4 Commits
9544b7f5e3
...
41cb59a4bf
Author | SHA1 | Date | |
---|---|---|---|
|
41cb59a4bf | ||
|
338cbafe0d | ||
|
7a2ee6eba2 | ||
|
e3c6e81716 |
@ -1,4 +1,4 @@
|
||||
def actual_power(a: int, b: int):
|
||||
def actual_power(a: int, b: int) -> int:
|
||||
"""
|
||||
Function using divide and conquer to calculate a^b.
|
||||
It only works for integer a,b.
|
||||
@ -19,10 +19,12 @@ def actual_power(a: int, b: int):
|
||||
"""
|
||||
if b == 0:
|
||||
return 1
|
||||
half = actual_power(a, b // 2)
|
||||
|
||||
if (b % 2) == 0:
|
||||
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
|
||||
return half * half
|
||||
else:
|
||||
return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
|
||||
return a * half * half
|
||||
|
||||
|
||||
def power(a: int, b: int) -> float:
|
||||
@ -43,9 +45,9 @@ def power(a: int, b: int) -> float:
|
||||
-0.125
|
||||
"""
|
||||
if b < 0:
|
||||
return 1 / actual_power(a, b)
|
||||
return 1 / actual_power(a, -b)
|
||||
return actual_power(a, b)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(power(-2, -3))
|
||||
print(power(-2, -3)) # output -0.125
|
||||
|
@ -15,27 +15,27 @@ edges: dict[str, list[str]] = {
|
||||
vertices: list[str] = ["a", "b", "c", "d", "e"]
|
||||
|
||||
|
||||
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
|
||||
"""Perform topological sort on a directed acyclic graph."""
|
||||
current = start
|
||||
# add current to visited
|
||||
visited.append(current)
|
||||
neighbors = edges[current]
|
||||
for neighbor in neighbors:
|
||||
# if neighbor not in visited, visit
|
||||
if neighbor not in visited:
|
||||
sort = topological_sort(neighbor, visited, sort)
|
||||
# if all neighbors visited add current to sort
|
||||
sort.append(current)
|
||||
# if all vertices haven't been visited select a new one to visit
|
||||
if len(visited) != len(vertices):
|
||||
for vertice in vertices:
|
||||
if vertice not in visited:
|
||||
sort = topological_sort(vertice, visited, sort)
|
||||
# return sort
|
||||
return sort
|
||||
class Topo:
|
||||
def topo_sort(self):
|
||||
visited = set()
|
||||
stack = []
|
||||
|
||||
def dfs(node):
|
||||
visited.add(node)
|
||||
|
||||
for neighbor in edges[node]:
|
||||
if neighbor not in visited:
|
||||
dfs(neighbor)
|
||||
|
||||
stack.append(node)
|
||||
|
||||
return stack
|
||||
|
||||
result = dfs("a")
|
||||
return result[::-1]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sort = topological_sort("a", [], [])
|
||||
topo = Topo()
|
||||
sort = topo.topo_sort()
|
||||
print(sort)
|
||||
|
Loading…
x
Reference in New Issue
Block a user