0

I'm trying to create a function that actually moves the items from one stack to another, however I have a lot of duplication. Can anyone help me refine it? (there is some bits that need to be added yet as well)

def guess2(frompeg, topeg):
    temp = -1
    if frompeg == 'a':
        if a != []:
            temp = a.pop()
        else:
            print('Error Popping a')
            return ()
    if frompeg == 'b':
        if b != []:
            temp = b.pop()
        else:
            print('Error Popping b')
            return ()
    if frompeg == 'c':
        if c != []:
            temp = c.pop()
        else:
            print('Error Popping c')
            return ()

    if topeg == 'a':
        if a == []:
            a.append(temp)
        elif temp < a[-1]:
            a.append(temp)
        else:

            print('Error')
    if topeg == 'b':
        if b == []:
            b.append(temp)
        elif temp < b[-1]:
            b.append(temp)
        else:
            print('Error')
    if topeg == 'c':
        if c == []:
            c.append(temp)
        elif temp < c[-1]:
            c.append(temp)

        else:
            print('Error')


print(a,b,c)
guess2('a','b')
print(a,b,c)
Brigzy97
  • 17
  • 1
  • 1
  • 7
  • You may find this recursive solution useful: http://stackoverflow.com/questions/1223305/tower-of-hanoi-recursive-algorithm – Rob Murray Dec 16 '15 at 14:03

1 Answers1

1

one thing you could do is an object map:

a = [7,6,5,4,3,2,1]
b = []
c = []

dd = {'a':a, 'b':b, 'c':c}

def guess2(frompeg, topeg):
    if dd[frompeg] != []:
       temp = dd[frompeg].pop()       
    else:
        print('Error Popping', frompeg)
        return  

    if dd[topeg] == []:
        dd[topeg].append(temp)
    elif temp < dd[topeg][-1]:
        dd[topeg].append(temp)
    else:
        dd[frompeg].append(temp) # put it back
        print('Error')
gkusner
  • 1,244
  • 1
  • 11
  • 14