def test_pushMultiple_ComeOutFILO(self): stack = Stack() stack.push(2) stack.push(1) out1 = stack.pop() out2 = stack.pop() self.assertEqual(1, out1) self.assertEqual(2, out2)
class MyQueue: def __init__(self): self.s1 = Stack() # Use for dequeues self.s2 = Stack() # Use for reverse ordering def enqueue(self, item): #while not self.s1.is_empty(): while self.s1.peek() is not None: self.s2.push(self.s1.pop()) self.s2.push(item) #while not self.s2.is_empty(): while self.s2.peek() is not None: self.s1.push(self.s2.pop()) def dequeue(self): return self.s1.pop() def __str__(self): return "s1: {}\ns2: {}".format(self.s1.__str__(), self.s2.__str__())
class MyQueue: """ For Question 5. """ def __init__(self): self.s1 = Stack() self.s2 = Stack() def enqueue(self, item): """ Add to end. """ self.s1.push(item) def dequeue(self): """ Remove from front. """ if self.s1.is_empty(): return None while (not self.s1.is_empty()): self.s2.push( self.s1.pop() ) result = self.s2.pop() while (not self.s2.is_empty()): self.s1.push( self.s2.pop() ) return result
class QueueViaStack(object): ''' Time : Space: Note : ''' def __init__(self): self.input = Stack() self.output = Stack() def push(self, data): self.input.push(data) def pop(self): if self.input.empty() and self.output.empty(): return None curr = self.input.pop() while curr != None: self.output.push(curr.data) curr = self.input.pop() return self.output.pop()
def sort_stack(s): assert not s.is_empty() ss = Stack() # This will be the auxiliary stack num_elements = 0 while not s.is_empty(): ss.push(s.pop()) num_elements += 1 num_sorted = 0 while num_sorted < num_elements: # `num_sorted` is how much `s` is filled. # `ss` has the `num_elements-num_sorted` elements. min_item = np.float('inf') # Search through all non-sorted items to find minimum. for _ in range(num_elements - num_sorted): item = ss.pop() if item < min_item: min_item = item s.push(item) # Put all unsorted items other than the one with min back # into ss, if we get the min hold it out and put it in s. got_min = False # Handle duplicates for _ in range(num_elements - num_sorted): item = s.pop() if item == min_item and not got_min: got_min = True else: ss.push(item) s.push(min_item) num_sorted += 1 return s
def test_canPushAndPop(self): stack = Stack() stack.push(1) out = stack.pop() self.assertEqual(1, out)