Skip to content

Instantly share code, notes, and snippets.

@nasifimtiazohi
Last active August 24, 2019 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasifimtiazohi/84c064ca571acb1f39aef0ffed8e825b to your computer and use it in GitHub Desktop.
Save nasifimtiazohi/84c064ca571acb1f39aef0ffed8e825b to your computer and use it in GitHub Desktop.
class tower:
def __init__(self, position, n):
#initial position as 0,1, or 2
self.position=position
# sanity check
if position > 2:
raise ValueError('tower position not valid. must be between 0 and 2')
if n < 1:
raise ValueError('disk number not valid. must be between 0 and 2')
#initialize an empty stack to hold the disks
self.disks=[]
#if original tower, fill up with disks
if position==0:
for x in range(n,0,-1):
self.disks.append(x)
def addDisk(self,x):
#check if x is smaller than top disks
if len(self.disks) !=0 and x > self.disks[-1]:
raise ValueError('new disk bigger than the top')
self.disks.append(x)
def removeDisk(self):
return self.disks.pop(-1)
def printStars(x):
for i in range(0,x):
print('*',end='')
def shiftDisk(original, destination, intermediate, n):
if n==1:
transferDisk=original.removeDisk()
destination.addDisk(transferDisk)
#print state after each transfer
drawTowers(original,destination,intermediate)
else:
shiftDisk(original, intermediate,destination, n-1)
shiftDisk(original,destination,intermediate,1)
shiftDisk(intermediate,destination,original,n-1)
def drawTowers(a,b,c):
#figure out the original positions of the tower
temp=[a,b,c]
for t in temp:
if t.position==0:
original=t
elif t.position==1:
destination=t
elif t.position==2:
intermediate=t
maxLen=max(len(original.disks),len(destination.disks),len(intermediate.disks))
for i in range(0,maxLen,1):
if i < len(original.disks):
printStars(original.disks[i])
print('\t',end='')
if i < len(destination.disks):
printStars(destination.disks[i])
print('\t',end='')
if i < len(intermediate.disks):
printStars(intermediate.disks[i])
print('\n')
print('--------------------------')
if __name__ == "__main__":
print("enter the number of disks: ")
n=int(input())
original=tower(0,n)
destination=tower(1,n)
intermediate=tower(2,n)
drawTowers(original,destination,intermediate)
shiftDisk(original,destination,intermediate,n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment