How to make a list of recursive iterations - Python

Asked

Viewed 97 times

3

I am implementing a python Hanoi tower and I need a log of all moves. It could be a list of the states of the 3 stacks. But when I try to use the append function for this list/log, the result is the last state of the game repeated by the number of iterations. What am I doing wrong?

pino1 = [3, 2, 1]
pino2 = []
pino3 = []
pinos = []

def moveTorre(altura, origem, destino, aux):
    if (altura > 0):
        moveTorre(altura-1, origem, aux, destino)
        moveDisk(origem, destino, altura)
        moveTorre(altura-1, aux, destino, origem)


def moveDisk(origem, destino, altura):
    global pino1
    global pino2
    global pino3
    global pinos
    destino.append(altura)
    origem.pop()
    pinos.append(pino1)
    pinos.append(pino2)
    pinos.append(pino3)
    print(pino1)
    print(pino2)
    print(pino3)
    print(pinos)


while (pino1 or pino2):
    moveTorre(3, pino1, pino3, pino2)
  • What is the argument aux?

  • 1

    It is the auxiliary pin of the tower of Hanoi. The first is the origin - pino1, the third is the destiny - pino3, and the middle called auxiliary - pino2. I implemented them as lists.

  • try to print, then just subistuir by log code

  • The print works right, but using the append it replaces the previous entries with the current one. It does this in all iterations.

1 answer

3


you do not want to repeat the numbers but show all the interactions at the end?

it changes the values of the other list by account that are referenced, to end this problem just use the slice operator [:] for example below pinos.append(pino1[:])

pino1 = [3, 2, 1]
pino2 = []
pino3 = []
pinos = []


def moveTorre(altura, origem, destino, aux):
    if altura > 0:
        moveTorre(altura-1, origem, aux, destino)
        moveDisk(origem, destino, altura)
        moveTorre(altura-1, aux, destino, origem)


def moveDisk(origem, destino, altura):
    global pino1
    global pino2
    global pino3
    global pinos
    destino.append(altura)
    origem.pop()
    pinos.append(pino1[:])
    pinos.append(pino2[:])
    pinos.append(pino3[:])
    print(pino1)
    print(pino2)
    print(pino3)
    print(pinos)


while pino1 or pino2:
    moveTorre(3, pino1, pino3, pino2)
  • It was the second case. It worked. Thank you very much!

  • nothing, and do not forget to mark all the answers that were useful and relevant S2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.