+ 1

Python runtime error

why isn't mcnt a global variable??? ......................................... Below is the recursive algorithm to preform the towers of hanoi. For n rings move n-1 rings to the temperary peg, then move the nth ring form source peg to the final peg. Now move n-1 rings from the temperary peg to the to the final peg ''' #global mcnt mcnt = 0 def hanoi(n, a, b, c): #mcnt += 1 if n <= 0: return hanoi(n-1, a, c, b) report(n, a, b) hanoi(n-1, c, b, a) def report(n, a, b): pna=['a', 'b', 'c'] x, y = pna[a], pna[b] #mcnt = 1 mcnt += 1 printf("Move# %d ring %d from peg %c to peg %c\n", mcnt,n, x, y ); …………………………………………………………. File "./Playground/file0.py", line 40, in report mcnt += 1 UnboundLocalError: local variable 'mcnt' referenced before assignment ……………………………………………………………… in report mcnt += 1 UnboundLocalError: local variable 'mcnt'

23rd Jul 2020, 8:21 PM
Rick Shiffman
Rick Shiffman - avatar
2 Respostas
+ 4
If you want to mutate/change the value of a global variable, you need to bring it in with "global" keyword like this: mcnt = 0 def hanoi(n, a, b, c): #mcnt += 1 if n <= 0: return hanoi(n-1, a, c, b) report(n, a, b) hanoi(n-1, c, b, a) def report(n, a, b): global mcnt # indicate that report may change the value of global variable mcnt pna=['a', 'b', 'c'] x, y = pna[a], pna[b] #mcnt = 1 mcnt += 1 print("Move# %d ring %d from peg %c to peg %c\n" % (mcnt,n, x, y) ) Also I think you want print instead of printf.
23rd Jul 2020, 8:32 PM
Josh Greig
Josh Greig - avatar
+ 1
thanks Josh
23rd Jul 2020, 8:40 PM
Rick Shiffman
Rick Shiffman - avatar