Became Hot Network Question
Towers od hanoi Tower of Hanoi without recursion
Towers od hanoi without recursion
Hi I am pretty new to programming and I would like you to give me some feedback about my code, how does it look, what could be better. Thank you.
A = []
B = []
C = []
PegDict = {'A': A,'B': B,'C': C} #Would it be better to use a two dimensional array?
discs = int(input("Podaj ilość dysków: "))
for i in range(discs, 0, -1):
A.append(i)
movesNeeded = pow(2, discs) - 1
StartingPeg = A.copy()
def move(fromm, to):
to.append(fromm[-1])
fromm.pop()
Moves the smallest disc one peg to the left. This part could be done better i think.
def moveLeft():
if A and A[-1] == 1:
move(A, C)
return
if B and B[-1] == 1:
move(B, A)
return
if C and C[-1] == 1:
move(C, B)
return
Moves the smallest disc one peg to the right
def moveRight():
if A and A[-1] == 1:
move(A, B)
return
if B and B[-1] == 1:
move(B, C)
return
if C and C[-1] == 1:
move(C, A)
return
Returns key of a peg that is the only valid move target for a cartain peg
def PossibleMove(Peg):
if Peg:
if Peg[-1] != 1:
for i in PegDict:
x = PegDict[i]
if not x:
return i
elif Peg[-1] < x[-1]:
return i
Main part
moves = 0
while not C == StartingPeg:
if discs%2 == 0:
moveRight()
moves += 1
else:
moveLeft()
moves += 1
print(A)
print(B)
print(C)
print()
for key in PegDict:
if PossibleMove(PegDict[key]) != None:
fromPeg = PegDict[key]
onePossibleMove = PossibleMove(PegDict[key])
if fromPeg:
moves += 1
move(fromPeg, PegDict[onePossibleMove])
print(A)
print(B)
print(C)
print()
print()
print('Moves: '+ str(moves))
print('Minimal number of moves: '+ str(movesNeeded))
lang-py