Trying to implement Tower of Hanoi recursive algorithm with arrays

Despite the fact that there are many questions about this problem, none of them helped me figure it out. I understand what recursion is, and I can easily solve Towers of Hanoi on my own in 2 ^ n-1 moves, but it's hard for me to write an algorithm for it in Python. The base script works, but I can’t find a way to translate “move n-1 disks to the auxiliary binding, and then the largest disk to the target binding” in the array operation, and I don’t understand why the last element is not extracted from the array when I exit its into a recursive call.

This program:

peg_a = [1,0]
peg_b = []
peg_c = []

def hanoi(start,aux,target):
    print(start,aux,target)
    if len(start) == 1:
        target.append(start.pop())
        print(start,aux,target)
    else:
        hanoi(start[1:],target,aux)
        target.append(start.pop())
        print(start,aux,target)

hanoi(peg_a, peg_b, peg_c)

And here is what is printed:

[1, 0] [] []
[0] [] []
[] [] [0]
[1] [0] [0]

Any help?

+4
2

, , . , , . , , , start[1:], , "" .

, , , .

:

def hanoi(pegs, start, target, n):
    assert len(pegs[start]) >= n, 'not enough disks on peg'
    if n == 1:
        pegs[target].append(pegs[start].pop())
        print '%i -> %i: %s' % (start, target, pegs)
    else:
        aux = 3 - start - target  # start + target + aux = 3
        hanoi(pegs, start, aux, n-1)
        hanoi(pegs, start, target, 1)
        hanoi(pegs, aux, target, n-1)

3 , , , . pegs, . start target - , . , . :

pegs = [[4, 3, 2, 1], [], []]
hanoi(pegs, 0, 1, 4)    

0 -> 2: [[4, 3, 2], [], [1]]
0 -> 1: [[4, 3], [2], [1]]
2 -> 1: [[4, 3], [2, 1], []]
0 -> 2: [[4], [2, 1], [3]]
1 -> 0: [[4, 1], [2], [3]]
1 -> 2: [[4, 1], [], [3, 2]]
0 -> 2: [[4], [], [3, 2, 1]]
0 -> 1: [[], [4], [3, 2, 1]]
2 -> 1: [[], [4, 1], [3, 2]]
2 -> 0: [[2], [4, 1], [3]]
1 -> 0: [[2, 1], [4], [3]]
2 -> 1: [[2, 1], [4, 3], []]
0 -> 2: [[2], [4, 3], [1]]
0 -> 1: [[], [4, 3, 2], [1]]
2 -> 1: [[], [4, 3, 2, 1], []]
+3

:

  • , start[1:] , , , (. "" ).
  • else, aux target.

, , , start target:

def hanoi(n, start, aux, target):
    if n == 1:
        target.append(start.pop())
    else:
        hanoi(n - 1, start, target, aux)
        target.append(start.pop())
        hanoi(n - 1, aux, start, target)

:

def hanoi(n, start, aux, target):
    if n > 0:
        hanoi(n - 1, start, target, aux)
        target.append(start.pop())
        hanoi(n - 1, aux, start, target)
+1

Source: https://habr.com/ru/post/1568456/


All Articles