Python の宿題ここで答えます Part 2
■ このスレッドは過去ログ倉庫に格納されています
0173デフォルトの名無しさん
2011/01/11(火) 06:54:24class Hanoi(object):
def __init__(self, height):
self.bars = [range(height, 0, -1), [], []]
self.step = 0
def __repr__(self):
return 'step -> %d\nBAR1: %s\nBAR2: %s\nBAR3: %s' % (
self.step, self.bars[0], self.bars[1], self.bars[2])
def move(self, n, src, dst, work):
''' move n discs from src to dst using work '''
if n == 1: # move sigle disc directly
self.bars[dst].append(self.bars[src].pop())
self.step += 1
print self
else: # move above (n - 1) discs to work, and move n th disc to dst
self.move(n - 1, src, work, dst)
self.move(1, src, dst, work)
self.move(n - 1, work, dst, src)
if __name__ == '__main__':
import sys
try:
height = int(sys.argv[1])
except (IndexError, TypeError, ValueError), e:
height = 3
hanoi = Hanoi(height)
print hanoi
hanoi.move(height, 0, 1, 2)
■ このスレッドは過去ログ倉庫に格納されています