DFS Algorithm in Python
DFS Algorithm in Python
print()
Fibonacci recursive
def fibonacciSeries(i):
if i <= 1:
return i
else:
return (fibonacciSeries(i - 1) + fibonacciSeries(i - 2))
num=10
if num <=0:
print("Please enter a Positive Number")
else:
print("Fibonacci Series:", end=" ")
for i in range(num):
print(fibonacciSeries(i), end=" ")
Sorting time
start_time = time.time() sorted_bubble =
bubble_sort(array_to_sort.copy()) # Copy to avoid sorting already sorted
array end_time = time.time() bubble_time = end_time - start_time #
Measure time for Quick Sort start_time = time.time() sorted_quick =
quick_sort(array_to_sort.copy()) end_time = time.time() quick_time =
end_time - start_time
# DFS algorithm
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
dfs(graph, '0')
# BFS algorithm in Python
import collections
# BFS algorithm
def bfs(graph, root):
while queue:
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal: ")
bfs(graph, 0)
# Dijkstra's Algorithm in Python
import sys
num_of_vertices = len(vertices[0])
visited_and_distance[to_visit][0] = 1
i=0
while queue:
# Find the node with the smallest distance in the queue
min_distance = float('inf')
min_index = -1
for i, (distance, node, path) in enumerate(queue):
if distance < min_distance:
min_distance = distance
min_index = i
while queue:
# Get the first path from the queue
path = queue.popleft()
# Get the last node in the path
node = path[-1]
return None
# Input from the user
start = input("Enter the starting county: ")
end = input("Enter the destination county: ")
# Explore neighbors
for neighbor in graph.get(start, []):
if neighbor not in visited:
result = dfs(graph, neighbor, end, path, visited)
if result: # If a path is found, return it
return result
--------------------------------------
---------
# Bubble sort in Python
def bubbleSort(array):
bubbleSort(data)
factorial = 1
recursive
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1 or x == 0:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))
# change the value for a different result
num = 7