0% found this document useful (0 votes)
11 views

DFS Algorithm in Python

Uploaded by

huseyn.test01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

DFS Algorithm in Python

Uploaded by

huseyn.test01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Fibonacci interative

# Write a program to print fibonacci series upto n terms in python


num = 10
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")

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 in Python

# DFS algorithm
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)

print(start)

for next in graph[start] - visited:


dfs(graph, next, visited)
return visited

graph = {'0': set(['1', '2']),


'1': set(['0', '3', '4']),
'2': set(['0']),
'3': set(['1']),
'4': set(['2', '3'])}

dfs(graph, '0')
# BFS algorithm in Python

import collections

# BFS algorithm
def bfs(graph, root):

visited, queue = set(), collections.deque([root])


visited.add(root)

while queue:

# Dequeue a vertex from queue


vertex = queue.popleft()
print(str(vertex) + " ", end="")

# If not visited, mark it as visited, and


# enqueue it
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)

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

# Providing the graph


vertices = [[0, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0]]

edges = [[0, 0, 1, 2, 0, 0, 0],


[0, 0, 2, 0, 0, 3, 0],
[1, 2, 0, 1, 3, 0, 0],
[2, 0, 1, 0, 0, 0, 1],
[0, 0, 3, 0, 0, 2, 0],
[0, 3, 0, 0, 2, 0, 1],
[0, 0, 0, 1, 0, 1, 0]]

# Find which vertex is to be visited next


def to_be_visited():
global visited_and_distance
v = -10
for index in range(num_of_vertices):
if visited_and_distance[index][0] == 0 \
and (v < 0 or visited_and_distance[index][1] <=
visited_and_distance[v][1]):
v = index
return v

num_of_vertices = len(vertices[0])

visited_and_distance = [[0, 0]]


for i in range(num_of_vertices-1):
visited_and_distance.append([0, sys.maxsize])

for vertex in range(num_of_vertices):

# Find next vertex to be visited


to_visit = to_be_visited()
for neighbor_index in range(num_of_vertices):

# Updating new distances


if vertices[to_visit][neighbor_index] == 1 and \
visited_and_distance[neighbor_index][0] == 0:
new_distance = visited_and_distance[to_visit][1] \
+ edges[to_visit][neighbor_index]
if visited_and_distance[neighbor_index][1] > new_distance:
visited_and_distance[neighbor_index][1] = new_distance

visited_and_distance[to_visit][0] = 1

i=0

# Printing the distance


for distance in visited_and_distance:
print("Distance of ", chr(ord('a') + i),
" from source vertex: ", distance[1])
i=i+1

Map with Djkstria

# Define the map of Azerbaijan as a graph (dictionary of neighboring rayons)


# Each edge has a weight of 1 to represent uniform distance between
neighboring regions.
azerbaijan_map = {
'Baku': {'Absheron': 1},
'Absheron': {'Baku': 1, 'Khizi': 1},
'Khizi': {'Absheron': 1, 'Guba': 1, 'Shamakhi': 1},
'Guba': {'Khizi': 1, 'Gusar': 1, 'Shabran': 1},
'Shabran': {'Guba': 1, 'Siyazan': 1},
'Siyazan': {'Shabran': 1, 'Gobustan': 1},
'Gobustan': {'Siyazan': 1, 'Shamakhi': 1},
'Shamakhi': {'Gobustan': 1, 'Khizi': 1, 'Ismayilli': 1},
'Ismayilli': {'Shamakhi': 1, 'Gabala': 1},
'Gabala': {'Ismayilli': 1, 'Oghuz': 1},
'Oghuz': {'Gabala': 1, 'Sheki': 1},
'Sheki': {'Oghuz': 1, 'Zagatala': 1},
'Gusar': {'Guba': 1},
'Zagatala': {'Sheki': 1, 'Balakan': 1},
'Balakan': {'Zagatala': 1},
# Add other regions and their neighbors similarly
}

# Dijkstra's algorithm for finding the shortest path without heapq


def dijkstra(graph, start, end):
# Priority queue as a list of (distance, node, path)
queue = [(0, start, [])]
visited = set()

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

# Pop the node with the smallest distance


distance, node, path = queue.pop(min_index)

# If we've reached the destination, return the path and distance


if node == end:
return (distance, path + [node])

# Skip if the node is already visited


if node in visited:
continue

# Mark the node as visited


visited.add(node)

# Add neighbors to the queue


for neighbor, weight in graph.get(node, {}).items():
if neighbor not in visited:
queue.append((distance + weight, neighbor, path + [node]))

return None # If no path is found


# Input from the user
start = input("Enter the starting region: ")
end = input("Enter the destination region: ")

# Find the shortest path


result = dijkstra(azerbaijan_map, start, end)

# Output the result


if result:
distance, path = result
print("Shortest path from", start, "to", end, "is:", " -> ".join(path), "with
distance", distance)
else:
print("No path found from", start, "to", end)

Map with BFS


from collections import deque

# Define the map of Estonia as a graph (dictionary of neighbors)


estonia_map = {
'Harju': ['Lääne-Viru', 'Rapla', 'Järva'],
'Lääne-Viru': ['Harju', 'Ida-Viru', 'Järva'],
'Ida-Viru': ['Lääne-Viru', 'Jõgeva'],
'Jõgeva': ['Ida-Viru', 'Lääne-Viru', 'Tartu', 'Järva'],
'Järva': ['Harju', 'Lääne-Viru', 'Jõgeva', 'Viljandi'],
'Tartu': ['Jõgeva', 'Põlva', 'Viljandi', 'Valga'],
'Rapla': ['Harju', 'Lääne', 'Pärnu', 'Järva'],
'Pärnu': ['Rapla', 'Lääne', 'Viljandi', 'Saare'],
'Viljandi': ['Pärnu', 'Järva', 'Tartu', 'Valga'],
'Valga': ['Viljandi', 'Tartu', 'Põlva', 'Võru'],
'Põlva': ['Tartu', 'Valga', 'Võru'],
'Võru': ['Põlva', 'Valga'],
'Saare': ['Pärnu'],
'Lääne': ['Rapla', 'Pärnu'],
}

# Function to perform BFS and find the shortest path


def bfs_shortest_path(graph, start, end):
# Initialize a queue with the starting point and a path list
queue = deque([[start]])
visited = set()

while queue:
# Get the first path from the queue
path = queue.popleft()
# Get the last node in the path
node = path[-1]

# Return the path if we reached the destination


if node == end:
return path

# If the node hasn't been visited, visit it


elif node not in visited:
for neighbor in graph.get(node, []):
new_path = list(path)
new_path.append(neighbor)
queue.append(new_path)

# Mark the node as visited


visited.add(node)

return None
# Input from the user
start = input("Enter the starting county: ")
end = input("Enter the destination county: ")

# Find the shortest path


path = bfs_shortest_path(estonia_map, start, end)

# Output the result


if path:
print("Shortest path from", start, "to", end, "is:", " -> ".join(path))
else:
print("No path found from", start, "to", end)

Map with DFS


# Define the map of Azerbaijan as a graph (dictionary of neighboring
regions)
azerbaijan_map = {
'Baku': {'Absheron'},
'Absheron': {'Baku', 'Khizi'},
'Khizi': {'Absheron', 'Guba', 'Shamakhi'},
'Guba': {'Khizi', 'Gusar', 'Shabran'},
'Shabran': {'Guba', 'Siyazan'},
'Siyazan': {'Shabran', 'Gobustan'},
'Gobustan': {'Siyazan', 'Shamakhi'},
'Shamakhi': {'Gobustan', 'Khizi', 'Ismayilli'},
'Ismayilli': {'Shamakhi', 'Gabala'},
'Gabala': {'Ismayilli', 'Oghuz'},
'Oghuz': {'Gabala', 'Sheki'},
'Sheki': {'Oghuz', 'Zagatala'},
'Gusar': {'Guba'},
'Zagatala': {'Sheki', 'Balakan'},
'Balakan': {'Zagatala'},
# Add other regions and their neighbors as needed
}

# DFS algorithm to find a path from start to end


def dfs(graph, start, end, path=None, visited=None):
# Initialize path and visited set if they are not provided
if path is None:
path = []
if visited is None:
visited = set()

# Add the current node to the path and mark it as visited


path.append(start)
visited.add(start)

# If we've reached the destination, return the current path


if start == end:
return path

# 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

# Backtrack if no path found


path.pop()
return None

# Input from the user


start = input("Enter the starting region: ")
end = input("Enter the destination region: ")

# Find a path using DFS


result = dfs(azerbaijan_map, start, end)

# Output the result


if result:
print("Path from", start, "to", end, "is:", " -> ".join(result))
else:
print("No path found from", start, "to", end)

--------------------------------------
---------
# Bubble sort in Python

def bubbleSort(array):

# loop to access each array element


for i in range(len(array)):

# loop to compare array elements


for j in range(0, len(array) - i - 1):
# compare two adjacent elements
# change > to < to sort in descending order
if array[j] > array[j + 1]:

# swapping elements if elements


# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

data = [-2, 45, 0, 11, -9]


data = [int(num.strip()) for num in user_input.split(",")]

bubbleSort(data)

print('Sorted Array in Ascending Order:')


print(data)

factorial using iterative

# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

recursive

# Python program to find the factorial of a number provided by the user


# using recursion

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

# to take input from the user


# num = int(input("Enter a number: "))

# call the factorial function


result = factorial(num)
print("The factorial of", num, "is", result)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy