def calculate(self): oprd_stack = Stack() for ch in self.get_postfix_exp(): if ch.isdigit(): oprd_stack.push(int(ch)) else: oprd2 = oprd_stack.pop() oprd1 = oprd_stack.pop() oprd_stack.push(self.calc_two_oprd(oprd1, oprd2, ch)) self.result = oprd_stack.pop()
def convert_to_postfix(self): exp_list = [] oprt_stack = Stack() for ch in self.get_org_exp(): if ch.isdigit(): exp_list.append(ch) else: if oprt_stack.empty() or ch == '(': oprt_stack.push(ch) elif ch == ')': op = oprt_stack.pop() while op != '(': exp_list.append(op) op = oprt_stack.pop() elif self.get_weight(ch) > \ self.get_weight(oprt_stack.peek()): oprt_stack.push(ch) else: while not oprt_stack.empty() and self.get_weight(ch) <=\ self.get_weight(oprt_stack.peek()): exp_list.append(oprt_stack.pop()) oprt_stack.push(ch) while not oprt_stack.empty(): exp_list.append(oprt_stack.pop()) self.postfix_exp = ''.join(exp_list)
class TestStack(unittest.TestCase): def setUp(self): self.client = Redis() self.client.flushdb() self.stack = Stack(self.client, "test-stack") def test_push(self): self.assertEqual( self.stack.push(1), 1 ) self.assertEqual( self.stack.push(2), 2 ) def test_pop_return_none_when_stack_empty(self): self.assertIsNone( self.stack.pop() ) def test_pop(self): self.stack.push(1) self.stack.push(2) self.assertEqual( self.stack.pop(), "2" ) self.assertEqual( self.stack.pop(), "1" ) def test_count(self): self.assertEqual( self.stack.count(), 0 ) self.stack.push(1) self.assertEqual( self.stack.count(), 1 )
def push(self, object): Stack.push(self, object) # do real push StackLog.pushes += 1 # overall stats self.maxlen = max(self.maxlen, len(self)) # per-instance stats
def push(self, object): Stack.push(self, object) # do real push StackLog.pushes = StackLog.pushes + 1 # overall stats self.maxlen = max(self.maxlen, len(self)) # per-instance stats
def push(self, object): Stack.push(self, object) StackLog.pushes += 1 self.maxlen = max(self.maxlen, len(self))
if __name__ == '__main__': from stack2 import Stack x = Stack() x.push('spam') x.push(123) print(x) y = Stack() y.push(3.1415) y.push(x.pop()) print(x) print(y) z = Stack() for c in 'spam': z.push(c) while z: print(z.pop(), end=' ') print() z = x + y print(z) for item in z: print(item, end=' ') print()