class Hannoi(): def __init__(self, N): self.solutionSize = N self.first = Stack() self.second = Stack() self.third = Stack() for i in range(N, 0, -1): self.first.push(i) def solveTowers(self): self.moveDisk(self.solutionSize, self.first, self.second, self.third) def moveDisk(self, size, fr, helper, dest): if size == 1: data = fr.pop() dest.push(data) else: self.moveDisk(size - 1, fr, dest, helper) self.moveDisk(1, fr, helper, dest) self.moveDisk(size - 1, helper, fr, dest) def verifySolution(self): while not self.third.isEmpty(): print self.third.pop()
def __init__(self, N): self.solutionSize = N self.first = Stack() self.second = Stack() self.third = Stack() for i in range(N, 0, -1): self.first.push(i)
def sortStack(stack): if stack.isEmpty(): return 'Stack is empty' less = Stack() middle = Stack() greater = Stack() return sortStackHelper(stack, less, middle, greater)
def push(self, data): lengthOfSet = len(self.stacks) indexOfUnfilledStack = None for i in range(0, lengthOfSet): if self.stacks[i].stackSize() < self.capacity: indexOfUnfilledStack = i break if indexOfUnfilledStack != None: self.stacks[indexOfUnfilledStack].push(data) else: self.stacks.append(Stack()) self.stacks[lengthOfSet].push(data)
class MyQueue(): def __init__(self): self.stack = Stack() self.helpderStack = Stack() def enqueue(self, data): self.stack.push(data) def dequeue(self): if self.stack.isEmpty(): return 'Queue is currently empty' self.createQueue() data = self.helperStack.pop() while not self.helperStack.isEmpty(): self.stack.push(self.helpderStack.pop()) def createQueue(self): while not self.stack.isEmpty(): self.helperStack.push(self.stack.pop())
def sortStackHelper(stack, less, middle, greater): if stack.isEmpty(): return Stack() middle.push(stack.pop()) if stack.isEmpty(): return middle while not stack.isEmpty(): data = stack.pop() if data >= middle.peek(): greater.push(data) else: less.push(data) leftHand = sortStackHelper(less, Stack(), Stack(), Stack()) rightHand = sortStackHelper(greater, Stack(), Stack(), Stack()) leftHand.push(middle.pop()) while not rightHand.isEmpty(): middle.push(rightHand.pop()) while not middle.isEmpty(): leftHand.push(middle.pop()) return leftHand
def __init__(self): self.stack = Stack() self.helpderStack = Stack()