Towers of Hanoi: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
No edit summary
Line 1: Line 1:
oh... no way! This is empty, too?! --[[User:D2|d2]] 16:45, 24 January 2007 (EST)
{{task}}
{{task}}

{{stub}}
In this task, the goal is to solve the Towers of Hanoi problem with recursivity.

==[[Python]]==
[[Category:Python]]

<pre>
def hanoi(ndisks, startPeg=1, endPeg=3):
if ndisks:
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(ndisks=4)
</pre>

Revision as of 15:28, 25 January 2007

Task
Towers of Hanoi
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to solve the Towers of Hanoi problem with recursivity.

Python

def hanoi(ndisks, startPeg=1, endPeg=3):
  if ndisks:
    hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
    print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
    hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(ndisks=4)