Towers of Hanoi: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: A variant which separates computation from display)
m (→‎Python recursive: (separating composition of the solution from its display))
Line 3,377: Line 3,377:


<lang python># hanoi :: Int -> String -> String -> String -> [(String, String)]
<lang python># hanoi :: Int -> String -> String -> String -> [(String, String)]
def hanoi(n, a, b, c):
def hanoi(n):
def go(n, a, b, c):
def go(n, a, b, c):
p = n - 1
p = n - 1
Line 3,383: Line 3,383:
go(p, a, c, b) + [(a, b)] + go(p, c, b, a)
go(p, a, c, b) + [(a, b)] + go(p, c, b, a)
) if 0 < n else []
) if 0 < n else []
return go(n, a, b, c)
return lambda a: lambda b: lambda c: go(n, a, b, c)




Line 3,395: Line 3,395:




print(
for step in map(
'\n'.join(
lambda xy: justifyRight(5)(' ')(xy[0]) + ' -> ' + xy[1],
map(
hanoi(4, 'left', 'right', 'mid')
lambda xy: justifyRight(5)
):
(' ')(xy[0]) + ' -> ' + xy[1],
print(step)
hanoi(4)('left')('right')('mid')
</lang>
)
)
)</lang>
{{Out}}
{{Out}}
<pre> left -> mid
<pre> left -> mid
Line 3,417: Line 3,420:
left -> right
left -> right
mid -> right</pre>
mid -> right</pre>



==={{libheader|VPython}}===
==={{libheader|VPython}}===