def main():
    my_stack = Stack() 
    for _ in range(10):
        my_stack.push(randint(0, 9))
    sort_stack(my_stack)
    for _ in range(10):
        print my_stack.pop()
class StackWithMin(object):
    def __init__(self, top = None):
        self.top = top 

        #store the min values
        self._min = Stack(top) 

    def min(self):
        retval = self._min.peek()
        if retval is None:
            retval = sys.maxsize
        return retval



    def push(self,data):
        new_node = Node(data, self.top)
        self.top = new_node

        if data <= self.min(): 
            self._min.push(data)


    def pop(self):
        if self.top:
            retval = Node(self.top.data)
            self.top = self.top.next

            if retval.data == self.min():
                self._min.pop()
            return retval

    def peek(self):
        if self.top:
            return self.top.data
Example #3
0
	def solution(self):
		stck = Stack()
		node = self.goal
		while not node is None:
			stck.push(node.board)
			node = node.prev
		return stck
Example #4
0
def test_push():
    """Test stack push method."""
    from stack import Stack
    from stack import Node
    stack = Stack()
    stack.push(data[0])
    assert isinstance(stack.head, Node)
Example #5
0
def test_pop_2():
    our_list = ["first", "second", "third", "fourth"]
    our_stack = Stack(our_list)
    assert our_stack.pop() == "fourth"
    assert our_stack.pop() == "third"
    assert our_stack.pop() == "second"
    assert our_stack.pop() == "first"
Example #6
0
	def __init__(self):
		'''
		Initialize Queue

		'''
		self.stack1 = Stack()
		self.stack2 = Stack()
Example #7
0
def test_count(COUNT_LIST, count):
    """Test to see if stack count is correct."""
    from stack import Stack
    s = Stack()
    for i in COUNT_LIST:
        s.push(i)
    assert s.size() == count
def test_push():
    my_stack = Stack([1, 2, 3])
    my_stack.push(4)
    # assert my_stack.container.display() == (4, 3, 2, 1)
    assert my_stack.pop() == 4
    # check to make sure new stack wasn't initialized
    assert my_stack.pop() == 3
def test_empty():
    """Test case where an empty list is pushed to stack."""
    from stack import Stack
    stacky = Stack()
    stacky.push([])
    with pytest.raises(IndexError):
        stacky.pop().get_data()
class VisitOrder:
  
    stack = None 
    level = 0

    node_list = []

    def __init__( self ):
        self.stack = Stack()

    def make_stack( self ):
        while self.stack.length() > 0:
            print "self.stack.length() ==> " + str( self.stack.length() )
            print "Pop the stack ---> " + str( self.stack.pop().value )

    def get_node( self, node_id ):
        for n in self.node_list:
            #print 'get_node ' + str( n.id )
            if n.id == node_id:
                return n
        return None

    def build_tree( self, node ):
         self.level = self.level + 1
         print "in build_tree level : " + str( self.level )
         while len( node.value ) > 0:
             node.left = self.stack.pop() 
             build_tree( node.left )
         
         while len( node.value ) > 0:
             node.right = self.stack.pop()
             build_tree( node.right )
Example #11
0
class StackAllTestCase(unittest.TestCase):
    """Comprehensive tests of (non-empty) Stack."""

    def setUp(self):
        """Set up an empty stack."""
        self.stack = Stack()

    def tearDown(self):
        """Clean up."""
        self.stack = None

    def testAll(self):
        """Test adding and removeping multiple elements."""

        for item in range(20):
            self.stack.add(item)
            assert not self.stack.is_empty(), \
                'is_empty() returned True on a non-empty Stack!'

        expect = 19
        while not self.stack.is_empty():
            assert self.stack.remove() == expect, \
                ('Something wrong on top of the Stack! Expected ' +
                 str(expect) + '.')
            expect -= 1
Example #12
0
 def __init__(self):
     ''' 
     Initialize the queue with two stacks -- an incoming
     and outgoing stack.
     '''
     self.incoming_stack = Stack()
     self.outgoing_stack = Stack()
def test_push_pop(input_list):
    from stack import Stack
    new_stack = Stack()
    for item in input_list:
        new_stack.push(item)
    for item in reversed(input_list):
        assert new_stack.pop() == item
Example #14
0
def stack_sort(s):
    def find_max(s):
        t = Stack()
        m = None
        while s.size > 0:
            v = s.pop()
            t.push(v)
            if not m or v > m:
                m = v
        while t.size > 0:
            v = t.pop()
            if v != m:
                s.push(v)
        return m

    sort = Stack()

    while s.size > 0:
        m = find_max(s)
        sort.push(m)

    while sort.size > 0:
        s.push(sort.pop())

    return s
Example #15
0
def heightStack(height, nameStr):
    h = Stack(nameStr)
    while height != 0:
        h.push(height)
        height -= 1

    return h
Example #16
0
def converter(exp, fix="post"):
    """takes simple infix expression and converts to prefix or postfix"""
    tokens = list(exp)
    open_paren, close_paren = "(", ")"

    if fix not in ["pre", "post"]:
        raise ValueError("Must specify conversion as either 'pre' or 'post'")

    if fix == "pre":
        tokens.reverse()
        open_paren, close_paren = ")", "("

    s = Stack()
    result = ''

    for t in tokens:
        if t == open_paren:
            pass
        elif t in ["*", "+", "-", "/"]:
            s.push(t)
        elif t == close_paren and not s.is_empty():
            result += s.pop()
        else:
            result += t

    if fix == "pre":
        return result[::-1]
    return result
class Transactor:

    def __init__(self):
        self.stack = Stack()
        self.transaction_queue = []

    def start_transaction(self):
        """ (Transactor) -> NoneType
        Starts an "undo"-able set of events.
        """
        self.transaction_queue = []

    def end_transaction(self):
        """ (Transactor) -> NoneType
        Ends the current set of events.
        """
        self.stack.push(self.transaction_queue)
        self.transaction_queue = []

    def add_action(self, action):
        """ (Transactor, function) -> NoneType
        Adds an action onto the list of transactions.
        """
        self.transaction_queue.append(action)

    def undo(self):
        """ (Transactor) -> NoneType
        Undoes the last set of transactions. Returns true on success, or
        false on failure (indicating there were no more transactions to undo).
        Can throw a stack.EmptyStackError, which should be handled!
        """
        for cmd in reversed(self.stack.pop()):
            cmd()
Example #18
0
def revString(string):
	s = Stack()
	for c in string:
		s.push(c)
	
	while not s.isEmpty():
		print(s.pop(), end = '')
Example #19
0
class MyQueue:
    def __init__(self):
        self.stack_in  = Stack()
        self.stack_out = Stack()

    def enqueue(self, item):
        if not self.stack_in.is_empty():
            self.empty_stack(self.stack_in, self.stack_out)
        self.stack_in.push(item)

    def dequeue(self):
        if not self.stack_out.is_empty():
            self.empty_stack(self.stack_out, self.stack_in)
        return self.stack_in.pop()

    def empty_stack(self, stack1, stack2):
        '''
        Empty stack1 into stack2
        '''
        while not stack1.is_empty():
            stack2.push(stack1.pop())

    def print_mq(self):
        self.empty_stack(self.stack_in, self.stack_out)
        print self.stack_out
Example #20
0
def test_push():
    stack= Stack()
    
    stack.push(0)
    assert stack._lst.head.datum==0

    stack.push('dookie')
    assert stack._lst.head.datum=='dookie'
def test_start():
    """Test that empty stack has no head."""
    from stack import Stack
    stacky = Stack()
    try:
        stacky.pop().get_data()
    except IndexError:
        assert True
    def test_size(self):
        test_stack = Stack()

        test_stack.push("Woooooo")
        test_stack.push("Boooooo")
        test_stack.push("UNITTTTESSSSTS")

        self.assertEquals(3, test_stack.size)
Example #23
0
def dec2bin(num):
	s = Stack()
	while num > 0:
		s.push(num % 2)
		num = num //2
	
	while not s.isEmpty():
		print(s.pop(), end = '')
Example #24
0
 def test_simple_reverse(self):
     stack = Stack()
     stack.push(1)
     stack.push(2)
     reverse(stack)
     self.assertEqual(stack.pop(), 1)
     self.assertEqual(stack.pop(), 2)
     self.assertTrue(stack.is_empty())
Example #25
0
def rev_string(string):
	s = Stack()
	rev_s = ' '
	for char in string :
		s.push(char)
	while  not s.isEmpty():
		rev_s = rev_s + s.pop()
	return rev_s
Example #26
0
 def test_reverse_many(self):
     stack = Stack()
     for i in range(100):
         stack.push(i)
     reverse(stack)
     for i in range(100):
         self.assertEqual(stack.pop(), i)
     self.assertTrue(stack.is_empty())
def rev_string(my_str):
    s = Stack()
    for mental in my_str:
        s.push(mental)
    jogi = ''
    for gh in range(len(s.items)):
        jogi = jogi + s.pop()
    return jogi
Example #28
0
def revstring(mystr):
    myStack = Stack()
    for ch in mystr:
        myStack.push(ch)
    revstr = ''
    while not myStack.isEmpty():
        revstr = revstr + myStack.pop()
    return revstr
Example #29
0
def codeeval_input2():
    stack = Stack()
    node1 = Node(10, None)
    node2 = Node(-2, node1)
    node3 = Node(3, node2)
    node4 = Node(4, node3)
    stack.head = node4
    return stack
Example #30
0
    def test_history_depth_limit(self):
        s = Stack()
        [s.push('X') for n in range(Stack.DEPTH_HISTORY * 2)]
        self.assertEqual(len(s.depth_history()), Stack.DEPTH_HISTORY)

        self.assertEqual(len(s.depth_history(Stack.DEPTH_HISTORY * 2)), Stack.DEPTH_HISTORY)

        self.assertEqual(len(s.depth_history(17)), 17)
Example #31
0
    def path(self, method="BFS"):
        ''' Find path for the maze. The default method is Breadth First Search (BFS). The other method is Depth First Search (DFS).
        Also created is a matrix, _pmatrix, to represent the path. With the same dimension as _matrix, that of the maze, the matrix element is 
        set to P(=2) for the path, otherwise remains 0.'''

        print(f"Path - {method}")

        # Initialize the path matrix, _pmatrix
        self._pmatrix = np.zeros((self.nrow * 2 + 1, self.nrow * 2 + 1),
                                 dtype=int)

        # Availabe methods for solving for path
        methods = {"BFS": self._bfs, "DFS": self._dfs}

        # Using _edgeTo from BFS or DFS, from the last room, i.e. room number nmaze-1,
        # the path from 0 to nmaze-1 can be obtained.
        i = self.nmaze - 1
        methods[method]()

        s = Stack()

        while self._edgeTo[i] is not i:
            s.push(i)
            i = self._edgeTo[i]

        s.push(i)

        self._path = [s.pop() for i in range(len(s))]

        # With the path from room 0 to room nmaze-1 obtained, set those correspond to rooms
        # and passages in _pmatrix to be 2; others remain 0.

        self._pmatrix[0, 1] = self._pmatrix[self.nrow * 2,
                                            self.nrow * 2 - 1] = P
        for i in range(len(self._path) - 1):
            ir = (self._path[i] // self.nrow * 2 + 1)
            ic = (self._path[i] % self.nrow * 2 + 1)
            self._pmatrix[ir, ic] = P
            step = self._path[i + 1] - self._path[i]
            if step in (1, -1):
                ic += step
                self._pmatrix[ir, ic] = P
            else:
                ir += step // self.nrow
                self._pmatrix[ir, ic] = P
        ir = (self._path[len(self._path) - 1] // self.nrow * 2 + 1)
        ic = (self._path[len(self._path) - 1] % self.nrow * 2 + 1)
        self._pmatrix[ir, ic] = P

        # Print path in ASCII format
        for i in range(1, 2 * self.nrow, 2):
            for j in range(1, 2 * self.nrow, 2):
                if self._pmatrix[i, j] == P:
                    print("x", end="")
                else:
                    print(" ", end="")
            print()
        print()

        # Plot path in graphics
        self.plotMaze(f"Maze: {self.nrow} x {self.nrow}\nSolution: " + method,
                      self._matrix,
                      solution=True)

        return self._path, [i for i in self._visited]
Example #32
0
#define a function to retrieve our infix string from the command line. Argparse is awesome, so why done we use it??
def parse_args():
        parser = argparse.ArgumentParser()
        parser.add_argument('-s', action='store',dest='infix_string',help="use infix_prefix.py -s 'A * (B+ C)' ",required=True)
        return parser.parse_args()

#get our arguments in a neat result variable
results = parse_args()

#lets split our string directly from the results variable
split_infix_string = results.infix_string

#print 'infix stringzee to be proccessed: ',split_infix_string
#test our infix string out
#print split_infix_string
operatorStack = Stack()
operandStack = Stack()


for token in split_infix_string:
    #print "First Token thru: ",token,"\n"
    if token.isalpha() or token in ['+','-','/','*',')','(']:
        if token.isalpha():
            operandStack.push(token)
            #print 'Pushing Operand:',token,"\n"
        elif token == '(' or operatorStack.is_empty() or (prec[token] >= prec[operatorStack.peek()]):
                #print 'pushing token: ', token, "\n"
                operatorStack.push(token)
        elif token == ')':
            #print 'right paren found'
            while(operatorStack.peek() != '('):
def test_has_method(method):
    """Test that queue has all the correct methods."""
    from stack import Stack
    assert hasattr(Stack(), method)
Example #34
0
def segment(query):
    # get the request from terminal, split it and put parts into a list
    flag = 0
    query = pre_processing(query)
    # print(query)
    request = query.split()
    # result of semantic: a operation sequence
    request = detect_input_lists(request)
    seq = []
    # stack used to analysis
    stk = Stack()
    for w in request:
        # print(w)
        # operator in bracket would be pushed until meet a ")"
        if w in bracket:
            if w in methods:
                flag = 1
                stk.push(w)
            else:
                if stk.peek() in methods and w == "(" and flag == 1:
                    flag = 0
                    continue
                stk.push(w)
        # if w is a number (could be int or float)
        else:
            flag = 0
            if is_number(w):
                seq.append(float(w))
            # compare the priority of w and operator on the top of the stack
            elif type(w) is list:
                seq.append(w)
            elif w in priority:
                top = stk.peek()
                # if the priority of w is not bigger than the top
                # pop the top into result until priority of w is bigger than top
                while top is not None and priority[w] <= priority[top]:
                    seq.append(stk.pop())
                    top = stk.peek()
                stk.push(w)
            # meet a ")", continue popping until meet operator in bracket
            elif w == ")":
                top = stk.peek()
                while top is not None and top not in bracket:
                    # print(top)
                    seq.append(stk.pop())
                    top = stk.peek()
                # assert(stk.peek() != "(")
                # ignore "("
                if top != "(":
                    seq.append(stk.pop())
            # append the external name
            else:
                seq.append(w)
        # request end
        # append remain operator
    while stk.peek() is not None:
        # ignore "("
        if stk.peek() != "(":
            seq.append(stk.pop())
        else:
            stk.pop()
    # print(seq)
    return seq
Example #35
0
'''Zadanie1 Napisz funkcję w języku Python (lub wykorzystaj funkcję z poprzednich zajęć), który w oparciu o stos
oblicza wartość wyrażenia zapisanego w notacji postfiksowej. Zakładamy, że korzystamy z 4 klasycznych
operacji arytmetycznych +, -, * oraz /. Przykładowo dla danych wejściowych ”20 10 + 75 45 - * ” wynik
powinien wynosić 900.
Funkcję proszę nazwać Postfix Eval().'''
from stack import Stack

stos = Stack()


def Postfix_Eval(word):
    tempdig = ''
    for c in word:
        if c.isdigit():
            tempdig += c
        elif c in '/*-+':
            temp = str(stos.pop())
            stos.push(eval(str(stos.pop()) + c + temp))
        elif c == ' ' and tempdig != '':
            stos.push(tempdig)
            tempdig = ''
    return stos.pop()


print(Postfix_Eval('20 10 + 75 45 - *'))
Example #36
0
 def __init__(self):
     super().__init__()
     self.stack1 = Stack()
     self.stack2 = Stack()
Example #37
0
from stack import Stack


def reverse_string(stack, input_str):

    #loop through the string and push contents
    #char by char onto stack

    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


input_str = "Hello"
s = Stack()
print(reverse_string(s, input_str))
Example #38
0
    def setUp(self):
        """Set up an empty queue.
        """

        self.stack = Stack()
Example #39
0
class Queue:
    def __init__(self):
        self.first = Stack()
        self.second = Stack()

    def empty(self):
        # if len(self.container):
        #     return False
        # return True
        if self.first.empty() and self.second.empty():
            return True
        return False

    def enqueue(self, data):
        self.first.push(data)

    def dequeue(self):
        if self.empty():
            return None

        if self.second.empty():
            while not self.first.empty():
                self.second.push(self.first.pop())

        return self.second.pop()

    def peek(self):
        # return self.container[0]
        if self.empty():
            return None

        if self.second.empty():
            while not self.first.empty():
                self.second.push(self.first.pop())

        return self.second.peek()
Example #40
0
def generatePostfixTokens(expression: List[str], operators: List[str] = []):
    # Reference:
    # https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/
    precidence = {"^": 3, "*": 2, "/": 2, "+": 1, "-": 1, "=": 0}
    stack = Stack()
    postfix = []

    for token in expression:
        if token not in ["^", "*", "/", "+", "-", "(", ")", '='] + operators:
            # If it's an operand, add it into the postfix
            postfix.append(token)

        elif token == '(':
            # If it's an opening parenthesis, add it to the stack
            stack.push('(')

        elif token == ')':
            # If it's a closing parenthesis, add operators to postfix
            # Until a '(' is found or the stack is empty
            while not stack.isEmpty() and stack.peek() != '(':
                postfix.append(stack.pop())

            # Remove closing parenthesis from stack
            if stack.peek() == '(':
                stack.pop()

        else:  # It's an operator
            # If the current token's 'precidence' (Eg, * is evaluated before +)
            # is less than or equal to the one in the stack,
            while not stack.isEmpty(
            ) and stack.peek() != '(' and precidence.get(
                    token, 1) <= precidence.get(stack.peek(), 1):
                postfix.append(stack.pop())

            stack.push(token)

    while not stack.isEmpty():
        postfix.append(stack.pop())

    return postfix
from linked_list import Node
from stack import Stack

## Stack Test Cases
## Set up seme Elements
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)

# Start setting up a Stack
stack = Stack(node1)

# Test stack functionality
stack.push(node2)
stack.push(node3)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop())
stack.push(node4)
print(stack.pop().value)
Example #42
0
 def push(self, item):
     if len(self.stacks[self.current_stack]) >= self.capacity:
         self.stacks.append(Stack())
         self.current_stack += 1
     self.stacks[self.current_stack].push(item)
Example #43
0
 def __init__(self, capacity=3):
     self.stacks = [Stack()]
     self.current_stack = 0
     self.capacity = capacity
Example #44
0
 def setUp(self):
     """Set up an empty stack."""
     self.stack = Stack()
Example #45
0
 def __init__(self, type=DagNode):
     self._type = type
     self._nodes = {}
     self._stack = Stack()
     self._root = self._type("root")
     self._stack.push(self._root)
Example #46
0
 def __init__(self):
     super(StackMin, self).__init__()
     self._stack_min = Stack()
Example #47
0
from stack import Stack
s = Stack()

s.push("Hello")
s.push("World")
s.push('1')
s.push('4')
print(s.pop())
print(s.pop())
print(s.pop())
Example #48
0
#!/usr/bin/env python3
from stack import Stack

def str_rev(stack,inp_str):
    for word in inp_str:
        stack.push(word)
    rev_str = ""
    while not stack.is_empty():
        rev_str+=stack.pop()    

    return rev_str


stack = Stack()
inp_str = input("Enter your str: ")
print(str_rev(stack,inp_str))        
Example #49
0
class Dag:
    def __init__(self, type=DagNode):
        self._type = type
        self._nodes = {}
        self._stack = Stack()
        self._root = self._type("root")
        self._stack.push(self._root)

    def add(self, depth, object):
        assert depth > 0, 'depth cant be less equal zero'

        if depth > self.__getDepth() + 1:
            raise Exception("Wrong depth, stack: ", self.__getDepth(),
                            ", depth: ", depth)

        depthDifference = self.__getDepth() - depth + 1

        for i in range(0, depthDifference):
            self._stack.pop()

        assert self._stack.empty() == False, 'stack cant be empty'

        header = self.__getOrCreate(object)

        if self.__areConnected(self._stack.top(), header) == False:
            if self.__checkForCycle(self._stack.top(), header) == False:
                self.__connect(self._stack.top(), header)

        self._stack.push(header)
        return header

    def get(self, object):
        if object not in self._nodes:
            raise Exception("object does not exist")

        return self._nodes[object]

    def getNodes(self):
        return self._nodes.values()

    def getRoot(self):
        return self._root

    def deepPrint(self):
        self._root.deepPrint()

    def __areConnected(self, node1, node2):
        return node2 in node1.getChildren()

    def __connect(self, node1, node2):
        node1.addChild(node2)
        node2.addParent(node1)

    def __getDepth(self):
        return self._stack.size() - 1

    def __getOrCreate(self, object):
        if object not in self._nodes:
            self._nodes[object] = self._type(object)

        return self._nodes[object]

    def __checkForCycle(self, parent, node):
        result = self.__checkForCycleImpl(parent, node)

        node.setColorRecursively(DfsNode.White)

        return result

    def __checkForCycleImpl(self, parent, node):
        if node.getColor() == DfsNode.Black:
            return False

        node.setColor(DfsNode.Black)

        if parent == node:
            return True

        for child in node.getChildren():
            if self.__checkForCycleImpl(parent, child) == True:
                return True

        return False
Example #50
0
def infix_parts_to_postfix(terms):
    result = []
    stack = Stack()
    for elem in terms:
        if isinstance(elem, int):
            result.append(elem)
        elif elem == '(':
            stack.push(elem)
        elif elem == ')':
            while not stack.is_empty():
                top = stack.pop()
                if top != '(':
                    result.append(top)
                else:
                    break
        elif not stack or PRECEDENCE[elem] > PRECEDENCE[stack.top()]:
            stack.push(elem)
        else:
            while stack and PRECEDENCE[elem] <= PRECEDENCE[stack.top()]:
                result.append(stack.pop())
            stack.push(elem)
    while stack:
        result.append(stack.pop())
    return result
Example #51
0
from stack import Stack


def reverse_string(stack, str_in):
    s = Stack()
    for i in range(len(str_in)):
        s.push(str_in[i])

    rev_str = ""
    while not s.is_empty():
        rev_str += s.pop()

    return rev_str


a = Stack()
str_in = "Hello"

print(reverse_string(a, str_in))
Example #52
0

from stack import Stack

if __name__ == '__main__':
    s = Stack(3)
    s.push(5)
    s.push(8)
    s.push(9)
    s.push(10)
    s.pop()
    s.pop()
    print(s)

 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
 def test_length(self):
     s = Stack()
     assert s.length() == 0
     s.push('A')
     assert s.length() == 1
     s.push('B')
     assert s.length() == 2
     s.pop()
     assert s.length() == 1
     s.pop()
     assert s.length() == 0
Example #55
0
from stack import Stack

print("\nLet's play Towers of Hanoi!!")

# Create the Stacks
stacks = []
left_stack = Stack("Left")
middle_stack = Stack("Middle")
right_stack = Stack("Right")

stacks.extend([left_stack, middle_stack, right_stack])
# Set up the Game
num_disks = int(input("\nHow many disks do you want ot 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):
    left_stack.push(i)

num_optimal_moves = 2**num_disks - 1
print("\nThe fastest you can solve this game is in {} moves".format(
    num_optimal_moves))

# Get User Input


def get_input():
    choices = [i.get_name()[0] for i in stacks]
    while True:
        for i in range(len(stacks)):
Example #56
0
def zig_zag_traverse(node):
    if node is None:
        return

    current_stack = Stack()
    next_stack = Stack()
    left_to_right = True
    current_stack.push(node)

    while not current_stack.is_empty():
        temp = current_stack.pop().data
        #print ("inslide node {}".format(temp.data))
        if temp:
            print(temp.data)
            if left_to_right:
                if temp.left:
                    next_stack.push(temp.left)
                if temp.right:
                    next_stack.push(temp.right)
            else:
                if temp.right:
                    next_stack.push(temp.right)
                if temp.left:
                    next_stack.push(temp.left)

        if current_stack.is_empty():
            left_to_right = not left_to_right
            current_stack, next_stack = next_stack, current_stack
    return
Example #57
0
def postEval(expression, assignments):

    digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    operators = ['+', '*', '-']
    variables = assignments.keys()
    s = Stack()

    for c in expression:

        if c == ' ':
            continue

        if c in digits:
            s.push(c)
            continue

        if c in variables:
            s.push(assignment[c])
            continue

        if c in operators:
            try:
                op1 = s.pop()
            except EmptyStack as errore:
                raise BadExpression
            try:
                op2 = s.pop()
            except EmptyStack as errore:
                raise BadExpression

            if c == '-':
                s.push(int(op2) - int(op1))
            if c == '*':
                s.push(int(op1) * int(op2))
            if c == '+':
                s.push(int(op1) + int(op2))

            continue

        raise BadExpression

    val = s.pop()

    if not s:
        return val
    else:
        raise BadExpression

    return s.pop()
Example #58
0
def stock_span(array):
    result = []
    stack = Stack()
    for index, item in enumerate(array):
        # If STack is empty
        d = {"key": index, "value": item}
        if (stack.is_empty()):
            result.append(-1)
        # If top is greater then item
        elif (stack.peek().get('value') > item):
            result.append(stack.peek().get('key'))
        # if top is less than or equal to item
        elif (stack.peek().get('value') <= item):
            while (stack.peek().get('value') <= item):
                popped = stack.pop()
                if (stack.peek() is None):
                    break
            if (stack.is_empty()):
                result.append(-1)
            else:
                result.append(stack.peek().get('key'))
        stack.push(d)
    return [ind - val for ind, val in enumerate(result)]
Example #59
0
    def setUp(self):
        """Set up a queue with a single element.
        """

        self.stack = Stack()
        self.stack.add('a')
Example #60
0
 def __init__(self):
     self.first = Stack()
     self.second = Stack()