Menu
- 6.Write a Program to Implement Travelling Salesman Problem using Python.
- 7.Write a Program to Implement Tower of Hanoi using Python
- 8.Write a Program to Implement Monkey Banana Problem using Python.
- 9.Write a Program to Implement Alpha-Beta Pruning using Python.
- 10.Write a Program to Implement 8-Queens Problem using Python.
Aim: Write a Program to Implement Water-Jug problem using Python
Program:
# This function is used to initialize the
# dictionary elements with a default value.
from collections import defaultdict
# jug1 and jug2 contain the value
jug1, jug2, aim = 4, 3, 2
# Initialize dictionary with default value as false.
visited = defaultdict(lambda: False)
def waterJugSolver(amt1, amt2):
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
visited[(amt1, amt2)] = True
return (waterJugSolver(0, amt2) or
waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
waterJugSolver(amt1 + min(amt2, (jug1-amt1)),
amt2 - min(amt2, (jug1-amt1))) or
waterJugSolver(amt1 - min(amt1, (jug2-amt2)),
amt2 + min(amt1, (jug2-amt2))))
else:
return False
print("Steps: ")
waterJugSolver(0, 0)
Output:
Steps:
0 0
4 0
4 3
0 3
3 0
3 3
4 2
0 2