def test_instantiation(self): """ Testing the instantiation of a Stack """ # Test that the object is of type Stack. stack = Stack() assert isinstance(stack, Stack)
from stack import Stack print("\nLet's play Towers of Hanoi!!") #Create the Stacks left_stack = Stack("Left") middle_stack = Stack("Middle") right_stack = Stack("Right") stacks = [] stacks.append(left_stack) stacks.append(middle_stack) stacks.append(right_stack) #Set up the Game num_disks = int(input("\nHow many disks do you want to play with?\n")) while(num_disks < 3): num_disks = int(input("\nEnter a number greater than or equal to 3\n")) disks = [] for i in range(num_disks,0,-1): disks.append(i) left_stack.push(i) num_optimal_moves = 2 ** num_disks -1 print("\nThe fastest you can solve this game is in {0} moves".format(num_optimal_moves)) #Get User Input def get_input(): choices = [] for stack in stacks: name = stack.get_name()
def __init__(self, string): self.string = string self.stack = Stack()
def test_new_stack_with_head_has_head(): """Check new stack with head kwarg has head.""" from stack import Stack this_stack = Stack(5) assert this_stack._linkedlist.head.value == 5
def test_pop_with_values(): """Check that pop removes the top value from the stack.""" from stack import Stack this_stack = Stack(data=[1, 2, 3]) assert this_stack.pop() == 3
def __init__(self): self.primary_stack = Stack() self.auxiliary_stack = Stack()
def main(): print(Stack().template.to_json())
def merge_alternating(stack1: Stack, stack2: Stack) -> Stack: """Return a stack by merging two stacks in alternating order. Precondition: <stack1> and <stack2> have the same size. The new stack's top element is the top element of <stack1>, followed by the top element of <stack2>, followed by the next element of <stack1>, then <stack2>, etc. If <stack1> and <stack2> are both empty, the new stack should also be empty. <stack1> and <stack2> should be unchanged when the function ends. >>> s1 = Stack() >>> s2 = Stack() >>> s1.push('a') >>> s1.push('b') >>> s1.push('c') >>> s2.push(1) >>> s2.push(2) >>> s2.push(3) >>> merged = merge_alternating(s1, s2) >>> merged.pop() 'c' >>> merged.pop() 3 >>> merged.pop() 'b' >>> merged.pop() 2 >>> merged.pop() 'a' >>> merged.pop() 1 >>> merged.is_empty() True >>> s1.is_empty() False >>> s2.is_empty() False """ # TODO: implement this function. def copy_and_reverse_stack(stack): """ copy a stack """ if stack is None: return None copy1 = Stack() copy2 = Stack() while not stack.is_empty(): value = stack.pop() copy1.push(value) copy2.push(value) while not copy2.is_empty(): stack.push(copy2.pop()) return copy1 result = Stack() if stack1.is_empty() and stack2.is_empty(): return result temp1 = copy_and_reverse_stack(stack1) temp2 = copy_and_reverse_stack(stack2) while not temp2.is_empty(): result.push(temp2.pop()) result.push(temp1.pop()) return result
#!.env/bin/python from aws_cdk import core from stack import Stack ENV = core.Environment(account="473883619336", region="us-east-1") app = core.App() Stack(app, "blog-backend-stack", env=ENV) app.synth()
def test_reverse_empty(): """Test stack reverse on an empty stack.""" stack = Stack() reverse(stack) assert stack.is_empty()
def setUp(self): self.stack = Stack()
from stack import Stack def reverse_string(stack, input_str): for i in range(len(input_str)): stack.push(input_str[i]) rev_str = "" while not stack.is_empty(): rev_str += stack.pop() return rev_str stack = Stack() input_str = "!evitacudE ot emocleW" print(reverse_string(stack, input_str))
def __init__(self): self.s1 = Stack() self.s2 = Stack()
[6, 9], [7], [12, 13], [9], [6], [11], [7], [13, 14], [], [13] ] v0 = 0 u0 = 14 order = Stack() discovered = [False] * vertexes paths = [0] * vertexes def DFS(v): for u in edges[v]: if (not discovered[u]): discovered[u] = True DFS(u) order.push(u) DFS(v0) order.push(v0) paths[v0] = 1 while (not order.empty):
def test_init_with_list(self): s = Stack(['A', 'B', 'C']) assert s.peek() == 'C' assert s.length() == 3 assert s.is_empty() is False
from stack import Stack garage = Stack() option = 0 while option != 4: print("Operations: ") print("1. Add vehicle") print("2. Remove a vehicle") print("3. Parked vehicles") print("4. Close the program") option = int(input("Option: ")) if option == 1: plate_number = input("plate number: ") garage.push(plate_number) print("Vehicle " + plate_number + " parked") elif option == 2: vehicle_plate = input("plate number: ") street = Stack() removed = False while not garage.is_empty(): parked_plate = garage.pop() if parked_plate == vehicle_plate: print("Vehicle " + vehicle_plate + " removed") removed = True else: street.push(parked_plate) while not street.is_empty():
def test_init(self): s = Stack() assert s.peek() is None assert s.length() == 0 assert s.is_empty() is True
def match(exprs, line, fn): stack = Stack() is_expr = False expr = [] for c in exprs: if c == '#': if not is_expr: is_expr = True else: is_expr = False v = fn(line, ''.join(expr)) expr = [] if stack.top is None: stack.push(v) continue s = stack.pop() if s == '!': v = not v if stack.top is None: stack.push(v) continue s = stack.pop() if s == '&': if isinstance(stack.top.value, bool): v = stack.pop() and v stack.push(v) else: raise Exception('wrong expr') elif s == '|': if isinstance(stack.top.value, bool): v = stack.pop() or v stack.push(v) else: raise Exception('wrong expr') elif s == '(': stack.push(s) stack.push(v) else: raise Exception('wrong expr') else: if is_expr: expr.append(c) else: if c in '(&!|': stack.push(c) elif c.strip() == '': pass elif c == ')': v = stack.pop() if not isinstance(v, bool): raise Exception('wrong expr') s = stack.pop() if s == '!': v = not v s = stack.pop() if s == '(': stack.push(v) else: raise Exception('wrong expr') else: raise Exception('wrong expr') while stack.top: v = stack.pop() if not isinstance(v, bool): raise Exception('wrong expr') s = stack.pop() if s == '!': v = not v s = stack.pop() if s == '&': v2 = stack.pop() if not isinstance(v2, bool): raise Exception('wrong expr') v = v and v2 elif s == '|': v2 = stack.pop() if not isinstance(v2, bool): raise Exception('wrong expr') v = v or v2 else: raise Exception('wrong expr') if stack.top is None: return v else: stack.push(v)
from stack import Stack s = Stack() s.push(10) s.push('aaaaaa') s.push('kajsnjbahdf') print(s.peek()) print(s.size()) s.pop() s.pop() print(s.peek())
from stack import Stack from queue import Queue N = 6 my_stack = Stack(N) my_stack.push("Australia") my_stack.push("India") my_stack.push("Costa Rica") my_stack.push("Peru") my_stack.push("Ghana") my_stack.push("Indonesia") my_queue = Queue(N) my_queue.enqueue("Australia") my_queue.enqueue("India") my_queue.enqueue("Costa Rica") my_queue.enqueue("Peru") my_queue.enqueue("Ghana") my_queue.enqueue("Indonesia") #Print the first values in the stack and queue print("The top value in my stack is: {0}".format(my_stack.peek())) print("The front value of my queue is: {0}".format(my_queue.peek())) #Get First Value added to Queue first_value_added_to_queue = my_queue.peek() #Checkpoint 2 print("\nThe first value enqueued to the queue was {0}".format( first_value_added_to_queue)) queue_runtime = "1" #Checkpoint 3 print("The runtime of getting the front of the queue is O({0})".format(
def test_new_stack_is_empty(): """Check that a new stack is empty.""" from stack import Stack this_stack = Stack() assert this_stack._linkedlist.length == 0
##Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. ##The following are the only functions that should be used to write this program: push | pop | peek | isEmpty. # from python interactive repo from stack import Stack def sortStack(st): """sort a stack in ascending order""" tempSt = [] while not st.isEmpty(): element = st.pop() while tempSt != [] and element < tempSt[-1]: st.push(tempSt.pop()) tempSt.append(element) return tempSt if __name__ == '__main__': st = Stack() for i in range(10, -1, -1): st.push(i) sortList = sortStack(st) print(sortList)
def new_stack(): """Create a new stack with some data as a fixture.""" from stack import Stack this_stack = Stack(data=[1, 2, 3]) return this_stack
def main(): stk = Stack([1, 2, 3, 4]) print size(stk)
def test_pop_without_values(): """Check that pop raises IndexError when called on empty stack.""" from stack import Stack this_stack = Stack() with pytest.raises(IndexError): this_stack.pop()
def __init__(self): super().__init__() self.stack = Stack()
def __init__(self, top=None): super(StackMin, self).__init__(top) self.stack_of_mins = Stack()
from stack import Stack print("\nLet's play Towers of Hanoi!!") #Create the Stacks stacks = [] left_stack = Stack('Left') stacks.append(left_stack) middle_stack = Stack('Middle') stacks.append(middle_stack) right_stack = Stack('Right') stacks.append(right_stack) #Set up the Game num_disks = int(input("\nHow many disks do you want to play with?\n")) while num_disks < 3: num_disks = int(input("Enter a number greater than or equal to 3\n")) for i in range(num_disks, 0, -1): left_stack.push(i) num_optimal_moves = (2**num_disks) - 1 print("\nThe fastest you can solve this game is in {0} moves".format( num_optimal_moves)) #Get User Input def get_input(): choices = [stack.get_name()[0] for stack in stacks] while True: for i in range(len(stacks)): name = stacks[i].get_name() letter = choices[i] print("Enter {0} for {1}".format(letter, name))
def data(): return Stack()
def __init__(self, path, pattern='', n_thumb=5, fig=None, grid=None, buffer_size=7, **kwargs): """ Parameters ---------- path: str Path to the stack of images pattern: str Pattern to use to select the files (e.g. extension) If nothing is given, the most common extension in the directory is used Default: '' n_thumb: int Number of thumbnails to show in the navigation bar buffer_size: int Number of images in the buffer, which are preloaded for faster viewing Default: 7 """ self._path = path folder = basename(path) self._buffer_size = buffer_size self._c_ix = 0 # If not pattern given, use the most common extension in the given folder if pattern == '': lst_files = os.listdir(path) ext = Counter([os.path.splitext(fn)[1] for fn in lst_files]) most_common = ext.most_common(1)[0][0] pattern = '*' + most_common # Stack initialization self._stack = Stack(path, pattern) n_im = len(self.stack) self.n_thumb = min(n_im, n_thumb) self.title = kwargs.get('title', 'Frame {} / ' + '{}'.format(n_im)) # Buffer initialization self._buffer = ImBuffer(buffer_size, self.stack) self.buffer.filling = True self.buffer.fill() # Load the first image self._c_im = self.buffer[self.c_ix] # Figure initialization self._thumb_ix = range(0, n_im, max(1, int(n_im / self.n_thumb))) if fig is None: self.fig = plt.figure(num=folder, figsize=(8, 8)) else: self.fig = fig if grid is None: gs = gridspec.GridSpec(4, self.n_thumb) else: gs = gridspec.GridSpecFromSubplotSpec(4, self.n_thumb, subplot_spec=grid) self.gs = gs self.ax_im = plt.subplot(gs[:3, :]) # Thumbnails self.ax_min = [plt.subplot(gs[3, i]) for i in range(self.n_thumb)] _ = [ax.set_axis_off() for ax in self.ax_min] _ = [ ax.imshow(self.stack[i], interpolation='none', **kwargs) for i, ax in zip(self._thumb_ix, self.ax_min) ] # Add a marker to the thumbnails axes xlim, ylim = self.ax_min[0].get_xlim(), self.ax_min[0].get_ylim() self._rects = [ Rectangle((0, 0), max(xlim), max(ylim), facecolor='none', edgecolor='orange', linewidth=5, visible=False) for _ in self.ax_min ] _ = [ax.add_patch(r) for ax, r in zip(self.ax_min, self._rects)] self._c_rect = self._rects[0] self._pic = self.ax_im.imshow(self.c_im, aspect=1, interpolation='none', **kwargs) self._cid_press = None self._cid_mouse = None self._cid_scroll = None self._cids = [self._cid_press, self._cid_mouse, self._cid_scroll] # Connect the callbacks for figure events self.connect() self.update_pic() plt.ion() self.fig.subplots_adjust(wspace=0) self.fig.show()