def test_6(self): a = Stack() a.push(6) a.push(2) a.push(5) a.push(3) b = stack_sort(a) self.assertEquals(b.pop(), 6)
def remove_from_all(self, animal): temp_kennel = Stack() oldest = self.all.dq() while type(oldest) != type(animal): temp_kennel.push(oldest) oldest = self.all.dq() while temp_kennel.size > 0: self.all.add_to_front(temp_kennel.pop())
def generate_towers(n): """ Instantiate three stacks. The first stack has n values. """ start, middle, end = Stack(), Stack(), Stack() for val in range(1, n + 1): start.push(val) return start, middle, end
def __set_half_stack(self): self.stack = Stack() slow_node = self.ll.head fast_node = self.ll.head while not self.__reach_end(fast_node): self.stack.push(self.__remove_haed()) slow_node = self.ll.head fast_node = fast_node.next.next if self.__is_even_length(fast_node): self.stack.push(slow_node) self.__remove_haed()
def three_stacks_simple(array): """ Implement three stacks using a single array, iteratively. """ stack0, stack1, stack2 = Stack(), Stack(), Stack() for i, val in enumerate(array): stack = i % 3 if stack == 0: stack0.push(value) elif stack == 1: stack1.push(value) else: stack2.push(value) return stack0, stack1, stack2
def play_game(): # Create and shuffle the Draw deck deck = Deck() deck.shuffle() # Create the play stacks stack1 = Stack("ascending") stack2 = Stack("ascending") stack3 = Stack("descending") stack4 = Stack("descending") stacks = [stack1, stack2, stack3, stack4] # Create the starting hands hand1 = Hand() hand1.draw(deck) # While there are still cards in the deck and hand... while deck.cards or hand1.cards: # Get a list of stack states with directions print("The stacks are:") states = [] for stack in stacks: print(str(stack.state) + " " + stack.direction) # Determine how many cards MUST be played if deck.cards: requirement = 2 else: requirement = 1 plays = hand1.play(stacks, requirement) print(f"I was able to play {plays} cards") if plays < requirement: break hand1.draw(deck) print("I have the following cards in hand: " + ", ".join(hand1.cards_as_str())) # The game is over (didn't have enough plays) print("Done") cards_remaining = deck.size() + hand1.size() print(f"The Game ended with {cards_remaining} cards remaining.") if cards_remaining == 0: print("You have won The Game!!") elif cards_remaining < 11: print("You didn't win, but you did really good!") else: print("Sorry, you lost The Game. Better luck next time.") return cards_remaining
def setUp(self): self.stack = Stack() self.sample = range(1, 10) self.stackBigger = Stack() self.sampleBigger = range(11, 20) for (i, value) in enumerate(self.sample): print(self.sampleBigger[i]) self.stack.add_item(value) self.stackBigger.add_item(self.sampleBigger[i]) self.add = self.stackBigger + self.stack self.radd = self.stack + 5
def create_stack(size): """ This function create a stack object with the size specified as its input Args: size: int value representing the size of a stack Returns: Stack: Stack object with the length == size """ # Initialize a stack stack = Stack() for _ in range(size): # Push an element with random value into the stack stack.push(Node(np.random.randint(0, 1000))) # Now return the stack return stack
def setUp(self): """ Setup method for unit-testing. This method will be called for each test case in this file Returns: """ # Create dummy nodes for testing the stack class self.first_node = Node(1) self.second_node = Node(2) self.third_node = Node(3) # Push all nodes into a stack self.stack = Stack() self.stack.push(self.first_node) self.stack.push(self.second_node) self.stack.push(self.third_node)
class MyQueue(object): """ Implements a queue using two stacks. Lazily reverses items from the back_stack to the front_stack when needed. """ def __init__(self): self.front_stack = Stack() self.back_stack = Stack() def eq(self, data): self.back_stack.push(data) def dq(self): if self.front_stack.size == 0: self.rebuild() return self.front_stack.pop() def peek_front(self): if self.front_stack.size == 0: self.rebuild() return self.front_stack.peek() def rebuild(self): """ Lazily rebuilds the front stack when a value is needed by pop/peek. When the front_stack empties, rebuild it by reversing the values in the back_stack. """ while self.back_stack.size > 0: self.front_stack.push(self.back_stack.pop())
def stack_sort(stack): """ Uses a helper stack and a temporary value to insert values into a stack in ascending order. Time complexity: O(n^2) Space complexity: O(n) """ helper = Stack() helper.push(stack.pop()) while stack.size != 0: if stack.peek() > helper.peek(): helper.push(stack.pop()) else: value = stack.pop() while helper.size > 0 and value <= helper.peek(): stack.push(helper.pop()) helper.push(value) return helper
class StackTestCase(unittest.TestCase): """ docstring """ def setUp(self): self.stack = Stack() self.sample = range(1, 10) self.stackBigger = Stack() self.sampleBigger = range(11, 20) for (i, value) in enumerate(self.sample): print(self.sampleBigger[i]) self.stack.add_item(value) self.stackBigger.add_item(self.sampleBigger[i]) self.add = self.stackBigger + self.stack self.radd = self.stack + 5 def test_length(self): self.assertEqual(self.stack.get_count(), len(self.sample)) def test_tot(self): self.assertEqual(self.stack.get_tot(), sum(self.sample)) def test_lower_bigger(self): self.assertLess(self.stack, self.stackBigger) self.assertGreaterEqual(self.stackBigger, self.stack) def test_add(self): self.assertEqual(self.add, 180) def test_radd(self): self.assertEqual(self.radd, 50)
def ToBinary(n): BinStack=Stack() L=[] while n!=0: x=n%2 BinStack.push(x) n=n//2 while not BinStack.isEmpty(): L.append(str(BinStack.peek())) BinStack.pop() NewBinLst=''.join(L) print(NewBinLst)
class KaibunChecker(object): def __init__(self, ll): self.ll = ll def is_kaibun(self): self.__set_half_stack() return self.__stack_are_equal_to_list() def __set_half_stack(self): self.stack = Stack() slow_node = self.ll.head fast_node = self.ll.head while not self.__reach_end(fast_node): self.stack.push(self.__remove_haed()) slow_node = self.ll.head fast_node = fast_node.next.next if self.__is_even_length(fast_node): self.stack.push(slow_node) self.__remove_haed() def __stack_are_equal_to_list(self): while not self.stack.isEmpty(): node1 = self.stack.pop() node2 = self.__remove_haed() if node1.val != node2.val: return False if self.ll.head != None: raise Exception("Different length of stack and list!") return True def __remove_haed(self): node = self.ll.head self.ll.head = node.next return node def __reach_end(self, fast_node): if fast_node.next == None: return True elif fast_node.next.next == None: return True else: return False def __is_even_length(self, fast_node): if not self.__reach_end(fast_node): raise Exception("Don't use unless it reached end.") return fast_node.next != None
def stacksort(cs): final = Stack() temp = Stack() temp.push( 1) #I have to do this so it will go into the while loop underneath while not cs.is_empty() and not temp.is_empty( ): #This while loop stops when I have nothing left in either loop, this happens when all the elements are in the 'final' stack a = cs.pop() #Pop the first value of cs into a temp = Stack() #Clear this stack while not cs.is_empty( ): #this will take 2 values and compare them to each other and look for the smallest number b = cs.pop() #Pop another value from cs into b if a < b or a == b: #look for the smaller value temp.push( b ) #if a is smaller, continue on to compare a to all the other remaining values else: temp.push( a ) #otherwise push a into the temp stack and set the value of a to b a = b final.push( a ) #after it finds the smallest value, push that into the final stack while not temp.is_empty(): #push all the values from temp into cs cs.push(temp.pop()) temp.push( 1) #I have to do this so it will go into the while loop once again the_final = Stack() while not final.is_empty(): the_final.push(final.pop()) return the_final
def stacksort(cs): ss = Stack() #Small Stack bs = Stack() #Big Stack while not cs.is_empty(): #if the current stack is not empty new = cs.pop() placed = False while(not placed): #placed represents whether or not the new variable has been placed into a stack if ss.is_empty(): #if small stack is empty if bs.is_empty(): #and big stack is empty ss.push(new) #push new into small stack placed = True #end the while loop and start with the next value in the cs else: #ss is empty but bs is not big = bs.pop() if(new>big): #if the value from cs is bigger than bs ss.push(big) #put the bs value at the top of ss else: bs.push(big) #otherwise push it back into bs bs.push(new) #and then push new on top of it placed = True #end while loops else: #if ss is not empty small = ss.pop() if(new<small): #if cs value is less than ss value bs.push(small) #put ss value into bs and then restart the loop else: ss.push(small) #otherwise put small back into ss if bs.is_empty(): bs.push(new) #and if bs is empty put new into bs placed=True #end loop else: big = bs.pop() #if bs isn't empty if(new>big): #and if cs value is bigger than bs value ss.push(big) #put bs value into ss else: bs.push(big) #if cs value is smaller than bs value push big then new in that order bs.push(new) placed =True #end loop while not bs.is_empty(): a = bs.pop() ss.push(a) while not ss.is_empty(): a = ss.pop() cs.push(a) return cs
from classes import Stack from bs import strings from func import find_opposite_bracket from data import url if __name__ == '__main__': for string in strings: my_stack = Stack() for i in string: if my_stack.isEmpty(): my_stack.push(i) elif find_opposite_bracket(i) == my_stack.peek(): my_stack.pop() else: my_stack.push(i) if my_stack.isEmpty(): print(f'Строка со скобками "{string}" сбалансированна') else: print(f'Строка со скобками "{string}" не сбалансированна')
line = line.split() print(line) #build a cask object for each cask in the input file, store in a dictonary if key == "C": temp_cask = Cask(line[0], int(line[1]), float(line[2])) casks[temp_cask.c_id] = temp_cask #build a stack object for each stack in the input file #Check if stack contains a cask, if so put cask in stack #Build a node with the stack name, and store the stack in the node #Give all nodes a uniqe number ID for use in adjacancy matrix #store all nodes in a dictonary, using the number_id as key #Store name connected to number in two different dictonaries for references elif key == "S": temp_stack = Stack(line.pop(0), int(line.pop(0)), []) for cask in line: temp_stack.addCaskToStack(casks.get(cask)) stacks[temp_stack.s_id] = temp_stack node_name = temp_stack.s_id nodes[node_name] = Node(node_name, num_nodes, True) node_name_to_num[node_name] = num_nodes node_num_to_name[num_nodes] = node_name num_nodes += 1 #Create an edge object for each edge, store it in a list. If new nodes are #discovered, create a node object for them, and store in the node dictonary elif key == "E":
def iterative_minimax(game: 'Game') -> Any: """ Returns the best score available for a certain game using an iterative approach. @param game 'Game': the Game object that represents the game being played @rtype: Any """ tree_list = [] tree_list.append(Tree((game.current_state, [], None, None))) s = Stack() s.add(tree_list[0]) a_lst = [] while not s.is_empty(): p = s.remove() if (p.children == []) and p.value.get_possible_moves() != []: moves = [p] for value in p.value.get_possible_moves(): q = Tree((p.value.make_move(value), [], None, value)) p.children.append(q) tree_list.append(q) moves.append(q) a_lst.append(moves) for node in tree_list: s.add(node) elif (p.children == []) and p.value.get_possible_moves() == []: old_state = game.current_state game.current_state = p.value if not game.is_winner('p1') and not game.is_winner('p2'): p.score = 0 game.current_state = old_state else: p.score = -1 game.current_state = old_state else: lst_scores = [] for node in p.children: lst_scores.append(node.score * -1) p.score = max(lst_scores) for outer_list in a_lst: if game.current_state.__repr__() == outer_list[0].value.__repr__() \ and outer_list[0].children != []: lst = [] for node in outer_list[0].children: if node.value.get_possible_moves() == []: lst.append(node.move_made) if len(lst) == 1: return lst[0] elif len(lst) >= 1: return random.choice(lst) m = [(node.move_made, node.score) for node in outer_list[1:]] lst = [] for item in m: if item[1] == outer_list[0].score * -1: lst.append(item[0]) return random.choice(lst) return -1
class TestStack(TestCase): """ TestStack object implementation """ def setUp(self): """ Setup method for unit-testing. This method will be called for each test case in this file Returns: """ # Create dummy nodes for testing the stack class self.first_node = Node(1) self.second_node = Node(2) self.third_node = Node(3) # Push all nodes into a stack self.stack = Stack() self.stack.push(self.first_node) self.stack.push(self.second_node) self.stack.push(self.third_node) def test_push(self): """ Unit-test for stack.push method Returns: """ # Add new element by pushing into the stack, then check the value new_element = Node(4) self.stack.push(new_element) self.assertEqual(new_element.value, self.stack.peek()) # Add another element with push operation to make sure ;) new_element = Node(5) self.stack.push(new_element) self.assertEqual(new_element.value, self.stack.peek()) def test_pop(self): """ Unit-test for stack.pop method Returns: """ # Pop an element one by one, then check the node self.assertEqual(self.stack.pop(), self.third_node) self.assertEqual(self.stack.pop(), self.second_node) self.assertEqual(self.stack.pop(), self.first_node) def test_peek(self): """ Unit-test for stack.peek method Returns: """ # Check if the nodes are properly stored into the stack self.assertEqual(self.third_node.value, self.stack.peek()) new_element = Node(4) self.stack.push(new_element) self.assertEqual(new_element.value, self.stack.peek()) def tearDown(self): """
def __init__(self): self.front_stack = Stack() self.back_stack = Stack()
def stack_sort(stack): """ Uses a helper stack and a temporary value to insert values into a stack in ascending order. Time complexity: O(n^2) Space complexity: O(n) """ helper = Stack() helper.push(stack.pop()) while stack.size != 0: if stack.peek() > helper.peek(): helper.push(stack.pop()) else: value = stack.pop() while helper.size > 0 and value <= helper.peek(): stack.push(helper.pop()) helper.push(value) return helper if __name__ == "__main__": a = Stack() a.push(6) a.push(2) a.push(5) a.push(3) print a print stack_sort(a)