1
I wrote this recursive code from Anoi’s tower and was trying to implement a section that told me the minimum number of moves needed and what move we were playing ( add a move whenever it changed).
For example if there were 3 disks:
Primeira jogada: Tower 1 --> Tower 2
etc...
Número minimo de jogadas: 7
How could I implement this? Recursively? With iteration and cycles? I tried recursively but lost myself in my reasoning and could not solve the problem without reformulating everything.
def hanoi():
def mova(n, origem, destino, aux):
def mova_disco(de, para):
print("Tower", de, "-->", "Tower", para, "\n\n")
if n == 1:
mova_disco(origem, destino)
else:
mova(n - 1, origem, aux, destino)
mova_disco(origem, destino)
mova(n - 1, aux, destino, origem)
n = eval(input("Quantos discos deseja considerar? \n -->"))
print("Solução do puzzle: \n")
mova(n, "1", "3", "2")
#Running the code
hanoi()
In Portuguese, por favor, já que estamos no [pt.so]
– Woss
And by translating, you could explain why you used the
eval
on user input?– Woss
@Woss already translated. I used evalei as I would use "int(input)", just for habit and because they use in the book I’m reading. But they work the same way I think.
– Guilherme Almeida
eval
is not the same thing asint
. The difference is thatint
converts to number and gives error if you have anything that is not a number, whileeval
accepts any valid command, and may even be dangerous, see here an example - if the book says to useeval
and does not alert to these problems, I would already look with suspicion...– hkotsubo
Okay, I get it. Thank you. I will take this into account next time before using Eval :) ?
– Guilherme Almeida