def hanoi(disks, source, Destination, auxiliary):
if disks == 1:
print('move disk 1 from tower {} to tower {}.'.format(source, auxiliary))
return
hanoi(disks - 1, source, auxiliary, Destination)
print('move disk {} from tower {} to tower {}.'.format(disk, source, auxiliary))
hanoi(disks - 1, Destination, source, auxiliary)
disk = int(input('Input Disk: '))
hanoi(disk, 'A', 'B', 'C')
n = disk
d =(2**n)-1
print("\nTotal Moves " str(d))
I need to add number 1-10000 as in the image depend on how many moves execute. Can anyone give me a hint?
CodePudding user response:
You could store the current move number as a global variable.
def hanoi(disks, source, Destination, auxiliary):
global current_move_number
current_move_number = 1
if disks == 1:
print(f'{current_move_number}. move disk 1 from tower {source} to tower {auxiliary}.')
return
hanoi(disks - 1, source, auxiliary, Destination)
print(f'{current_move_number}. move disk {disk} from tower {source} to tower {auxiliary}.')
hanoi(disks - 1, Destination, source, auxiliary)
disk = int(input('Input Disk: '))
current_move_number = 0
hanoi(disk, 'A', 'B', 'C')
n = disk
d =(2**n)-1
print("\nTotal Moves " str(d))
CodePudding user response:
This can be done with an additional argument, a counter:
def hanoi(disks, source, Destination, auxiliary, cnt=1): # initial counter = 1
if disks == 1:
print('{}. move disk 1 from tower {} to tower {}.'.format(cnt, source, auxiliary))
return cnt 1 # increment counter after move and return
cnt = hanoi(disks - 1, source, auxiliary, Destination, cnt)
print('{}. move disk {} from tower {} to tower {}.'.format(cnt, disk, source, auxiliary))
return hanoi(disks - 1, Destination, source, auxiliary, cnt 1) # increment counter after move and return the result of the next hanoi call
disk = int(input('Input Disk: '))
total = hanoi(disk, 'A', 'B', 'C') # you can take the total number of move as return from hanoi
n = disk
d = (2 ** n) - 1
print("\nTotal Moves " str(d))
print(f"Total Moves (returned total from `hanoi`) {total-1}") # another way to print the total number of moves
Output:
Input Disk: 3
1. move disk 1 from tower A to tower C.
2. move disk 3 from tower A to tower B.
3. move disk 1 from tower C to tower B.
4. move disk 3 from tower A to tower C.
5. move disk 1 from tower B to tower A.
6. move disk 3 from tower B to tower C.
7. move disk 1 from tower A to tower C.
Total Moves 7
Total Moves (returned total from `hanoi`) 7