8/2/24, 1:50 PM WATER JUG,DFS,BFS - Jupyter Notebook
In [7]: def waterjug(j1c,j2c,tm):
j1=0
j2=j2c
while j1 != tm:
print(f'jug 1={j1}/{j1c}jug2={j2}/{j2c}')
pm=min(j2,j1c-j1)
j1+=pm
j2-=pm
print(f'jug 1={j1}/{j1c}jug2={j2}/{j2c}')
if j1==tm:
break
if j1==j1c:
j1=0
if j2==0:
j2=j2c
print(f'final state:jug 1={j1}/{j1c}jug2={j2}/{j2c}')
In [8]: j1c = int(input("Enter capacity of Jug 1: "))
j2c = int(input("Enter capacity of Jug 2: "))
tm = int(input("Enter target amount: "))
waterjug(j1c, j2c, tm)
Enter capacity of Jug 1: 4
Enter capacity of Jug 2: 3
Enter target amount: 2
jug 1=0/4jug2=3/3
jug 1=3/4jug2=0/3
jug 1=3/4jug2=3/3
jug 1=4/4jug2=2/3
jug 1=0/4jug2=2/3
jug 1=2/4jug2=0/3
final state:jug 1=2/4jug2=0/3
In [9]: #dfs
localhost:8889/notebooks/WATER JUG%2CDFS%2CBFS.ipynb# 1/3
8/2/24, 1:50 PM WATER JUG,DFS,BFS - Jupyter Notebook
In [14]: def dfs(graph, start):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
print(node, end=' ')
visited.add(node)
stack.extend(graph[node][::-1])
def accept_graph():
graph = {}
edges = int(input("Enter number of edges: "))
for _ in range(edges):
edge = input("Enter an edge (Format: node1 node2): ").split()
node1, node2 = edge[0], edge[1]
if node1 not in graph:
graph[node1] = []
if node2 not in graph:
graph[node2] = []
graph[node1].append(node2)
graph[node2].append(node1)
return graph
graph = accept_graph()
start = input("Enter start node: ")
print("DFS Traversal:")
dfs(graph, start)
Enter number of edges: 5
Enter an edge (Format: node1 node2): A B
Enter an edge (Format: node1 node2): A C
Enter an edge (Format: node1 node2): B D
Enter an edge (Format: node1 node2): B E
Enter an edge (Format: node1 node2): C F
Enter start node: A
DFS Traversal:
A B D E C F
In [ ]: #BFS
localhost:8889/notebooks/WATER JUG%2CDFS%2CBFS.ipynb# 2/3
8/2/24, 1:50 PM WATER JUG,DFS,BFS - Jupyter Notebook
In [12]: from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
print(node, end=' ')
visited.add(node)
queue.extend(graph[node])
def accept_graph():
graph = {}
edges = int(input("Enter number of edges: "))
for _ in range(edges):
edge = input("Enter an edge (Format: node1 node2): ").split()
node1, node2 = edge[0], edge[1]
if node1 not in graph:
graph[node1] = []
if node2 not in graph:
graph[node2] = []
graph[node1].append(node2)
graph[node2].append(node1)
return graph
graph = accept_graph()
start = input("Enter start node: ")
print("BFS Traversal:")
bfs(graph, start)
Enter number of edges: 5
Enter an edge (Format: node1 node2): A B
Enter an edge (Format: node1 node2): A C
Enter an edge (Format: node1 node2): B D
Enter an edge (Format: node1 node2): B E
Enter an edge (Format: node1 node2): C F
Enter start node: A
BFS Traversal:
A B C D E F
In [ ]:
localhost:8889/notebooks/WATER JUG%2CDFS%2CBFS.ipynb# 3/3