Python Forum

Full Version: cannot reset list in for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to write a short program to solve a measurement puzzle with three jiggers of water. I want it to loop through a list of tuples, each one of which describes a pouring jigger and a receiving jigger by its size and its content. After running through the for loop once in which a function modifies the jigger contents, I want to be able to reset the jigger to its original contents and run through the for loop a second time. I do not seem to be able to reset the contents of the jigger to its original state for the second run through the for loop.
# oneLiterPourSolver_test.py
# figures out a classic 3 jigger pour puzzle

jigger3 = [3,2] 
jigger5 = [5,3] 
jigger8 = [8,5] 
pour_1 = [(jigger3,jigger5),(jigger3, jigger8)] 


def resetJiggers():
    global jigger3, jigger5, jigger8, pour_1
    jigger3 = [3,2] 
    jigger5 = [5,3] 
    jigger8 = [8,5]
    #         [(pour from 3 into 5),(pour from 3 into 8)]
    pour_1 = [(jigger3,jigger5),(jigger3, jigger8)] 
    
def firstPour(fromJigger, toJigger):
        toJigger[1] = toJigger[1] + fromJigger[1]
        fromJigger[1] = 0
        
    
for (x,y) in pour_1:
    firstPour(x,y)
    resetJiggers()
I know I'm missing something very simple. I've tried using globals (everywhere!) AND moving the call to resetJiggers() to different position, all to no avail. My debugger (in IDLE) indicates that, once called, the for loop uses the changed values of jigger3 and jigger5 (instead of the reset values) no matter what...
Scope.
Rule 1: Never use globals
Rule 2: Never use globals
Rule 3: you get the idea

# oneLiterPourSolver_test.py
# figures out a classic 3 jigger pour puzzle
 
jigger3 = [3,2] 
jigger5 = [5,3] 
jigger8 = [8,5] 
pour_1 = [(jigger3,jigger5),(jigger3, jigger8)] 
 
def resetJiggers():

    j3 = [3,2] 
    j5 = [5,3] 
    j8 = [8,5]
    #         [(pour from 3 into 5),(pour from 3 into 8)]
    p1 = [(j3,j5),(j3, j8)] 
    return j3, j5, j8, p1
     
def firstPour(fromJigger, toJigger):
        toJigger[1] = toJigger[1] + fromJigger[1]
        fromJigger[1] = 0
         
     
for (x,y) in pour_1:
    firstPour(x,y)
    jigger3, jigger5, jigger8, pour_1 = resetJiggers()

print(jigger3, jigger5, jigger8, pour_1)
Output:
[3, 2] [5, 3] [8, 5] [([3, 2], [5, 3]), ([3, 2], [8, 5])]
Thanks, Minister Jeff... I've recast the problem, with your help, and I'll post the solution when I've uncovered it. Do you know of a good discussion on scope in functions? I need to go back and relearn...