def test_print_empty_stack(capsys): stack = Stack() stack.print() expected = "[]\n" output = capsys.readouterr().out assert output == expected
def test_peek_stack_with_elements(): stack = Stack([1, 2, "Dog"]) expected = "Dog" output = stack.peek() assert output == expected assert stack.stack[-1] == expected
def test_stack(): """Fixture for testing.""" from src.stack import Stack empty = Stack() one = Stack(5) multi = Stack([1, 2, 'three', 4, 5]) return empty, one, multi
def initialize_stack(num_disks): global stacks global left global middle global right global moves global inv_f global min_moves global final_answer global game_completion_f stacks = [] left_stack = Stack("Left") middle_stack = Stack("Middle") right_stack = Stack("Right") stacks.append(left_stack) stacks.append(middle_stack) stacks.append(right_stack) for i in range(num_disks, 0, -1): stacks[0].push(i) left = stacks[0].get_items() middle = stacks[1].get_items() right = stacks[2].get_items() moves = 0 inv_f = 0 min_moves = 2**num_disks - 1 game_completion_f = 0 final_answer = left
def test_print_stack_with_elements(capsys): stack = Stack([1, 2, 3, 4, 5]) stack.print() expected = "[1, 2, 3, 4, 5]\n" output = capsys.readouterr().out assert output == expected
def test_size(self): # test if the size is being enforced stack = Stack(size=10) for num in range(1000): stack.push(num) assert stack.size() == 10 assert stack.stack == [_ for _ in range(10)]
def test_pop_with_full_stack(): stack = Stack([2, 4, 1, 4020]) expected = 4020 output = stack.pop() assert output == expected assert stack.stack[-1] == 1
def dummyFunc(opcode: Opcode, bytecode: bc.Bytecode, stack: st.Stack): if opcode.consume > 0: stack.pop(opcode.consume, type_hint_constants.ANY) if opcode.produce > 0: import time stack.push(str(int(time.time())))
def test_push_empty_stack(): stack = Stack() element = 230 stack.push(element) expected = [230] output = stack.stack assert output == expected
def test_push(self): s = Stack() s.push(1) self.assertEqual(s.top['value'], 1, 'should have inserted 1') self.assertIsNone(s.top['prev'], 'should have nothing before') s.push(2) self.assertEqual(s.top['value'], 2, 'should have 2 as top') self.assertEqual(s.top['prev']['value'], 1, 'should have 1 before') self.assertIsNone(s.top['prev']['prev'], '1 is the last value')
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def tearDown(self): self.stack = None def test_push(self): self.stack.push("foo") self.assertTrue(self.stack.stack.head.data == "foo") self.assertTrue(self.stack.stack.head.next is None) self.stack.push("bar") self.assertTrue(self.stack.stack.head.data == "bar") self.assertTrue(self.stack.stack.head.next.data == "foo") def test_pop(self): self.stack.push("foo") self.stack.push("bar") self.assertTrue(self.stack.stack.head.data == "bar") self.assertTrue(self.stack.stack.head.next.data == "foo") self.stack.pop() self.assertTrue(self.stack.stack.head.data == "foo") self.assertTrue(self.stack.stack.head.next is None)
def expr_to_stack(self, expr): stack = Stack() buf = '' idx = len(expr) - 1 while idx >= 0: char = expr[idx] idx -= 1 # If 0-9 then add to buffer (for multi-digit numbers) if char.isdigit(): buf = char + buf continue # Convert value from buffer to integer and move to stack if buf != '': stack.push(int(buf)) buf = '' # Add operators to stack if not char.isdigit() and char in self.allowed_operators.keys(): stack.push(char) # Finally flush buffer into stack if buf != '': stack.push(int(buf)) return stack
def test_openvpn_security_group(): output = (Stack().template_to_json()) properties = output["Resources"]["OpenVPNSecurityGroup"]["Properties"] expect(properties["GroupName"]).to.eq('OpenVPN') expect(properties["GroupDescription"]).to.eq( 'This is a security group for OpenVPN') expect(properties["SecurityGroupIngress"]).to.eq([{ "CidrIp": "0.0.0.0/0", "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22 }, { "CidrIp": "0.0.0.0/0", "IpProtocol": "udp", "FromPort": 1194, "ToPort": 1194 }]) expect(properties["SecurityGroupEgress"]).to.eq([{ 'CidrIp': '0.0.0.0/0', 'FromPort': -1, 'IpProtocol': -1, 'ToPort': -1 }]) expect(properties["VpcId"]).to.eq(vpc_id)
def test_openvpn_ec2_instance(): output = (Stack().template_to_json()) properties = output["Resources"]["EC2OpenVPN"]["Properties"] expect(properties["ImageId"]).to.eq('ami-0b69ea66ff7391e80') expect(properties["InstanceType"]).to.eq('t2.micro') expect(properties["KeyName"]).to.eq('rwalker')
def test_push_with_multiple_elements(): stack = Stack() stack.push([1, 2, 3]) stack.push("Horse") stack.push(9.321) expected = [[1, 2, 3], "Horse", 9.321] output = stack.stack assert output == expected
def test_exceptions(self): with self.assertRaises(StackUnderflowException): s = Stack(1) s.pop() with self.assertRaises(StackOverflowException): s = Stack(1) s.push(10) s.push(20)
def sort_stack(stack): buffer_stack = Stack() while(not stack.is_empty()): value = stack.pop() if(buffer_stack.is_empty): buffer_stack.push(value) else: if(not buffer_stack.is_empty()): while(buffer_stack.peek() > value): temp = buffer_stack.pop() stack.push(temp) else: buffer_stack.push(value) return buffer_stack
def test_stack_exceptions(self): with self.assertRaises(ValueError): s = Stack("A") with self.assertRaises(ValueError): s = Stack(10) s.size = "A" with self.assertRaises(ValueError): s = Stack(10) s.top = "A"
def __init__(self, text: str): # Data stack (main stack for operations). self.__ds = Stack() # Return stack (supports procedures work). self.__rs = Stack() # Instruction pointer. self.__iptr = 0 # Input text parsed into list of values and instructions. self.__code_list = list(self.parse(text)) # Storage for variables. Mapping names of vars to their values. self.__heap = dict() # Storage for procedures. self.__procedures = dict() # Mapping operations in our language to functions that perform the necessary business logic. self.__valid_operations = { '+': self.sum, '-': self.sub, '*': self.mult, '/': self.div, '%': self.mod, '!': self.fact, '==': self.equal, '>': self.greater, '<': self.less, 'and': self.operator_and, 'or': self.operator_or, 'cast_int': self.cast_int, 'cast_str': self.cast_str, 'drop': self.drop, 'over': self.over, 'dup': self.dup, 'if': self.operator_if, 'jmp': self.jump, 'stack': self.output_stack, 'swap': self.swap, 'print': self.print, 'println': self.println, 'read': self.read, 'call': self.call, 'return': self.ret, 'exit': self.exit, 'store': self.store, 'load': self.load, }
def test_push(): """Test push.""" s = Stack() s.push(3) s.push(5) s.push(7) assert len(s.data) == 3 assert not s.is_empty()
def test_pop(self): s = Stack() value = s.pop() self.assertIsNone(value, 'should return None from empty stack') s.push(1) value = s.pop() self.assertEqual(value, 1, 'should return the stack value') self.assertEqual(s.pop(), None, 'should remain an empty stack')
def test_pop(self): s = Stack(10) s.push(20) s.push(10) value = s.pop() assert value == 10 assert s.top.value == 20 assert s.top.next == None s.pop() assert s.top == None
def test_size(self): s = Stack(10) s.push(10) s.push(20) assert s.size == 2 s.pop() s.pop() assert s.size == 0
def test_push(self): s = Stack(10) s.push(10) assert s.top.value == 10 assert s.top.next == None s.push(20) assert s.top.value == 20 assert s.top.next.value == 10
def validate_brackets(sentence): brackets = Stack() for char in sentence: if char == '(': brackets.push(True) elif char == ')': if brackets.pop() is not True: return False return brackets.size() == 0
def generate(self, z, sample, max_length): """Generate a valid expression from z using the decoder""" logits_all = self.decoder(z, max_length=max_length).squeeze() rules_all = [] for logits in logits_all: t = 0 stack = Stack(grammar=GCFG, start_symbol=START) rules = [] while stack.nonempty: alpha = stack.pop() print(alpha) mask = get_mask(alpha, stack.grammar, as_variable=True) probs = mask * logits[t].exp() probs = probs / probs.sum() if sample: m = Categorical(probs) i = m.sample() else: _, i = probs.max(-1) # argmax # convert PyTorch Variable to regular integer i = i.item() # select rule i rule = stack.grammar.productions()[i] rules.append(rule) # add rhs nonterminals to stack in reversed order for symbol in reversed(rule.rhs()): if isinstance(symbol, Nonterminal): stack.push(symbol) t += 1 if t == max_length: break rules_all.append(rules) # if len(rules) < 15: # pad = [stack.grammar.productions()[-1]] return rules_all
def calculate_span(stock_price: list): if len(stock_price) == 0: raise ValueError("The list cannot be an empty list") if not isinstance(stock_price, list): raise ValueError("The `stocks_prices` must be a list") if not all([isinstance(i, int) for i in stock_price]): raise ValueError("All values must be integers") s = Stack(len(stock_price) + 1) s.push(0) span = [0] * len(stock_price) for idx, i in enumerate(stock_price): while not s.empty() and stock_price[s.top.value] <= i: v = s.pop() if (s.empty()): span[idx] = idx + 1 else: span[idx] = idx - s.top.value s.push(idx) return span
def calculate(self, expr): result = Stack() elements = self.expr_to_stack(expr) while elements.size() > 0: element = elements.pop() # If passed operator "=", then we return value from result buffer if element == '=': return result.pop() # If passed number, then add it to result buffer if isinstance(element, int): result.push(element) # If passed another operator, then calculate if element in self.allowed_operators: # If size >= 2 y = result.pop() x = result.pop() value = self.allowed_operators[element]( x, y) # Pass params in reverted direction result.push(value) return result.pop()
def main(): template = json.dumps(Stack().template_to_json()) params = {'StackName': stack_name, 'TemplateBody': template} try: cf.validate_template(TemplateBody=template) if _stack_exists(stack_name): print('Updating {}'.format(stack_name)) cf.update_stack(**params) waiter = cf.get_waiter('stack_update_complete') else: print('Creating {}'.format(stack_name)) cf.create_stack(**params) waiter = cf.get_waiter('stack_create_complete') print("...waiting for stack to be ready...") waiter.wait(StackName=stack_name) except botocore.exceptions.ClientError as ex: error_message = ex.response['Error']['Message'] if error_message == 'No updates are to be performed.': print("No changes") else: raise
def proper_parens(str): """Return 0 if string of parens is balanced, 1 if open and -1 if broken.""" stack = Stack() for i in str: if i is '(': stack.push(i) print('data', stack._container.head.data) elif i is ')': try: stack.pop() except IndexError: return -1 if stack._container.head: return 1 return 0
def filter_tokens(self): """ Requests tokens from the lexer and adds INDENT and DEDENT to the stream where relevant. :return: filtered token :raise: VykingIndentationError """ # Vyking has 3 indentation states. # - no colon hence no need to indent # - COLON was read, next rule must be a single line statement # or a block statement # - NEWLINE was read after a colon, user must indent BOF = 0 # Beginnig of file NO_INDENT = 1 MAY_INDENT = 2 # COLON was read MUST_INDENT = 3 # COLON and NEWLINE were read # Stack storing indentation levels met levels = Stack() levels.push(0) state = BOF # helper function def need_DEDENT(token): """Returns True if DEDENT is needed""" if token.value > levels.read(): raise VykingIndentationError( token.lineno, "indentation level is too high.\n" " \tHint: check for missing colon or mismatch in indentation level.", ) else: return token.value < levels.read() for token in self.lexer: # ignore NEWLINEs at beginning of input if state == BOF: if token.type == "NEWLINE": continue else: state = NO_INDENT if state == NO_INDENT: if token.type == "COLON": state = MAY_INDENT yield token elif token.type == "WS": while need_DEDENT(token): levels.pop() yield self._DEDENT(token.lineno - 1) else: yield token elif state == MAY_INDENT: if token.type == "NEWLINE": state = MUST_INDENT else: state = NO_INDENT yield token else: # MUST_INDENT if token.type == "WS" and token.value > levels.read(): # Store new indentation level levels.push(token.value) state = NO_INDENT yield self._INDENT(token.lineno) else: raise VykingIndentationError(token.lineno, "Expected indentation") # Yield DEDENTs at end of input while levels.pop() != 0: yield self._DEDENT(self.get_lineno()) yield self._new_token("ENDMARKER", self.get_lineno()) yield None
def test_len(self): s = Stack() self.assertEqual(len(s), 0, 'no elements yet') s.push(1) self.assertEqual(len(s), 1, 'one element') s.push(2) self.assertEqual(len(s), 2, 'two elements') s.pop() self.assertEqual(len(s), 1, 'one element left') s.pop() self.assertEqual(len(s), 0, 'no elements left') s.pop() self.assertEqual(len(s), 0, 'still no elements left')
def __validateStack(self, stack: st.Stack): stackLen = len(stack.getStack()) if stackLen < self.consume: raise ExceptionalHalt("Stackunderflow: %d != %d" % (stackLen, self.consume))
def pushFunc(opcode: Opcode, bytecode: bc.Bytecode, stack: st.Stack): toPush = bytecode.read(opcode.getShift()) if len(toPush) == 0: raise ExceptionalHalt("No values to push in bytecode sequence") stack.push(toPush)