0% found this document useful (0 votes)
14 views1 page

Python Solution for Water Jug Problem

The document presents a Python solution to the Water Jug Problem, where two jugs with capacities of 4 and 3 units are used to measure a target amount of 2 units. It utilizes a recursive function to explore all possible states of the jugs and prints the steps taken to reach the solution. The implementation employs a defaultdict to track visited states and avoid redundant calculations.

Uploaded by

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

Python Solution for Water Jug Problem

The document presents a Python solution to the Water Jug Problem, where two jugs with capacities of 4 and 3 units are used to measure a target amount of 2 units. It utilizes a recursive function to explore all possible states of the jugs and prints the steps taken to reach the solution. The implementation employs a defaultdict to track visited states and avoid redundant calculations.

Uploaded by

Mahnoor Rafique
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Water Jug Problem Solution in Python

---------------------------------------------------
from collections import defaultdict
jug1, jug2, aim = 4, 3, 2
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)

You might also like