Exemple #1
0
def infix_to_postfix(infix_exp):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    op_stack = Stack()
    postfix_list = []
    token_list = infix_exp.split()

    for token in token_list:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "1234567890":
            postfix_list.append(token)
        elif token == '(':
            op_stack.push(token)
        elif token == ')':
            top_token = op_stack.pop()
            while token != ')':
                postfix_list.append(top_token)
                top_token = op_stack.pop()
        else:
            while (not op_stack.is_empty()) and \
                (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
            op_stack.push(token)
    while not op_stack.is_empty():
        postfix_list.append(op_stack.pop())

    return " ".join(postfix_list)
def check_tags(doc):
    s = Stack()
    tags = Stack()
    i = 0
    stub = ""
    which = None
    balanced = True
    while balanced and i < len(doc):
        if doc[i] == "<":
            if s.is_empty():
                s.push("<")
                if doc[i+1] == "/":
                    which = "close"
                else:
                    which = "open"
            else:
                balanced = False
        if not s.is_empty():
            if doc[i] == ">":
                s.pop()
                if which == "open"
                    tags.append(stub)
                    stub = ""
                elif which == "close":
                    last = tags.pop()
                    if stub != last:
                        balanced = False
                which = None
                stub = ""
            else:
                stub += doc[i]
        i += 1
    if balanced and s.is_empty() and tags.is_empty():
        return True
    return False
Exemple #3
0
 def test_pop_in_correct_order_from_2_item_stack(self):
     test_obj = Stack()
     test_data1 = 'data1'
     test_data2 = 'data2'
     test_obj.push(test_data1)
     test_obj.push(test_data2)
     self.assertEqual(test_data2, test_obj.pop())
     self.assertEqual(False, test_obj.is_empty())
     self.assertEqual(test_data1, test_obj.pop())
     self.assertEqual(True, test_obj.is_empty())
Exemple #4
0
def validate(string):
    seen = Stack()
    opening = '({['
    closing = ')}]'
    for char in string:
        if char in opening:
            seen.push(char)
        elif char in closing:
            same_place = closing.index(char)
            if seen.is_empty() or seen.pop() != opening[same_place]:
                return False
    if not seen.is_empty():
        return False
    return True
Exemple #5
0
def sort_stack(stack):
    if stack.is_empty():
        return stack

    temp = Stack()
    while not stack.is_empty():
        if temp.is_empty():
            temp.push(stack.pop())
        else:
            val = stack.pop()
            while not temp.is_empty() and temp.peek() > val:
                stack.push(temp.pop())
            temp.push(val)

    while not temp.is_empty():
        stack.push(temp.pop())
def check_balanced_brackets(bracket_str):
    bracket_list = list(bracket_str)
    bracket_stack = Stack()
    for symbol in bracket_list:
        if symbol in ['(', '{', '[']:
            bracket_stack.push(symbol)
            continue
        elif symbol in [')', '}', ']']:
            if not bracket_stack.is_empty() and pair_match(
                    symbol, bracket_stack.peak()):
                bracket_stack.pop()
            else:
                return False
        else:
            raise Exception('Invalid symbol found')
    return bracket_stack.is_empty()
def rpn_calc(postfix_expr: str):
    '''Evaluate a postfix expression'''
    operand_stack = Stack()
    token_list = postfix_expr.split()

    print(postfix_expr)
    print(token_list)

    try:
        for ind in range(len(token_list)):
            if token_list[ind] in "0123456789":
                # Seperates the operands in a Stack
                operand_stack.push(int(token_list[ind]))
            else:
                # Does calculations with the operands
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                result = do_math(token_list[ind], operand1, operand2)

                # If the Stack still has elements
                if ind == len(token_list) - 1 and not operand_stack.is_empty():
                    raise StackError(
                        "Unknown expression {}".format(postfix_expr))
                else:
                    operand_stack.push(result)
                    return (operand_stack.pop())
    except IndexError:
        raise StackError("Stack is empty")
Exemple #8
0
def test_check_not_empty():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.is_empty()
    expected = False
    assert actual == expected
def reverse_queue(queue):
    stack = Stack()

    while not queue.is_empty():
        stack.push(queue.dequeue())

    while not stack.is_empty():
        queue.enqueue(stack.pop())
Exemple #10
0
def par_checker(string):
	st=Stack()
	flag=True
	i=0
	while i<len(string) and flag:
		ch=string[i]
		if(ch=="("):
			st.push(ch)
		else:
			if st.is_empty():
				flag=False
			else:
				st.pop()
		i=i+1
	if flag and st.is_empty():
		return True
	else:
		return False
Exemple #11
0
 def test_peek_shows_top_of_2_item_stack(self):
     test_obj = Stack()
     test_data1 = 'data1'
     test_data2 = 'data2'
     test_obj.push(test_data1)
     test_obj.push(test_data2)
     self.assertEqual(test_data2, test_obj.peek())
     self.assertEqual(False, test_obj.is_empty())
     self.assertEqual(test_data2, test_obj.peek())
def convert(num):
    s = Stack()
    while num > 0:
        remainder = num % 2
        s.push(remainder)
        num = num // 2
    bin_num = " "
    while not s.is_empty():
        bin_num += str(s.pop())
    return bin_num
def find_closing_paren(string, start_paren):
    paren_stack = Stack()
    for i in range(start_paren, len(string)):
        ch = search_string[i]
        if ch == "(":
            paren_stack.push("(")
        elif ch == ")":
            paren_stack.pop()
            if paren_stack.is_empty():
                return i
Exemple #14
0
def par_checker(string):
    st = Stack()
    flag = True
    i = 0
    while i < len(string) and flag:
        ch = string[i]
        if (ch in "([{"):
            st.push(ch)
        else:
            if st.is_empty():
                flag = False
            else:
                top = st.pop()
                if not equal(top, ch):
                    flag = False
        i = i + 1
    if flag and st.is_empty():
        return True
    else:
        return False
Exemple #15
0
def test_pop_until_empty():
    s = Stack()
    s.push("apple")
    s.push("banana")
    s.push("cucumber")
    s.pop()
    s.pop()
    s.pop()
    actual = s.is_empty()
    expected = True
    assert actual == expected
Exemple #16
0
def reverse_str(string):
    s = Stack()

    for i in range(len(string)):
        s.push(string[i])

    reverse_string = ""

    while not s.is_empty():
        reverse_string += s.pop()

    return reverse_string
Exemple #17
0
def is_paren_balanced(paren_string):
    s = Stack()
    is_balanced = True
    index = 0

    while index < len(paren_string) and is_balanced:
        paren = paren_string[index]
        if paren in '([{':
            s.push(paren)
        else:
            if s.is_empty():
                is_balanced = False
            else:
                top = s.pop()
                if not is_match(top, paren):
                    is_balanced = False
        index += 1
    if s.is_empty() and is_balanced:
        return True
    else:
        return False
def checker(paren):
    s = Stack()
    balanced = True
    index = 0
    while index < len(paren) and balanced:
        symbol = paren[index]
        if symbol in "({[":
            s.push(symbol)
        else:
            if s.is_empty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top, symbol):
                    balanced = False
                    
        index = index +1
      
    if balanced and s.is_empty():
        return True
    else:
        return False
def check_symbols(thing):
    """checking a string of symbols only to see if balanced"""
    s = Stack()
    i = 0
    balanced = True
    symbols = {"(": ")",
               "{": "}",
               "[": "]"}
    while balanced and i < len(thing):
        char = thing[i]
        if symbols.get(char):
            s.push(char)
        elif s.is_empty():
            balanced = False
        else:
            last = s.pop()
            if char != symbols[last]:
                balanced = False
        i += 1
    if balanced and s.is_empty():
        return True
    return False
def conversion(num , base):
    digits = "0123456789ABCDEF"
    
    rem = Stack()
    
    while num > 0:
        rem.push(num % base)
        num = num // base
        
        
    num_string = ""
    while not rem.is_empty():
        num_string = num_string + digits[rem.pop()]
    return num_string
Exemple #21
0
def parenthesis_balanced(
        string):  # function to check the balance of the bracket
    s = Stack()  # initializing the stack
    i = 0  # first index
    balanced = True
    while i < len(string) and balanced:  # going through all the brackets
        paren = string[i]
        if paren in '({[':  # checking is starting brackets are these or not if true then pushing into the stack
            s.push(paren)
        else:
            if s.is_empty():
                balanced = False
            else:
                top = s.pop()  # pop the last bracket
                if not is_match(
                        top,
                        paren):  # and calling the function for the validity
                    balanced = False
        i += 1

    if s.is_empty() and balanced:
        return True
    else:
        return False
Exemple #22
0
def parentheses_parser(a_string):

    s = Stack()

    index = 0
    balanced = True

    while index < len(a_string) and balanced:
        symbol = a_string[index]

        if symbol == '(':
            s.push('(')
        else:
            if s.is_empty():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.is_empty():
        return True
    else:
        return False, balanced
def divide_by_2(num):   
    s = Stack()
    
    if num == 0:
        return 0
    
    while num > 0:      # iterating through the number 
        remainder = num % 2     # taking out the remainder and pushing it into the stack
        s.push(remainder)   
        num = num // 2  # taking out the num for further results
    
    binary_num = ""
    while not s.is_empty():     # iterating the stack up till it is not empty 
        binary_num += str(s.pop())  # and adding it into the binary string
    
    return binary_num
Exemple #24
0
def divideBy2(num):
    
    """ in this function we are gonna find  the binary of the given 
    argument by using the divide by 2 algorithm and concatenating and 
    reversing it remiders when we dived the given number the the
    function by 2"""
    rem = Stack()
    
    while num > 0:
        rem.push(num%2)
        num = num // 2
    binary_num = ""
    
    while not rem.is_empty():
       binary_num = binary_num + str(rem.pop())
       
    return binary_num
def is_balanced(string):
    """Check that the paranthesis in a strigng are balanced."""
    s = Stack()
    match_dict = {')': '(', ']': '[', '}': '{'}

    for char in string:
        if char in match_dict.values():
            s.push(char)

        elif char in match_dict.keys():
            if s.size() == 0:
                return print('The paranthesis are not balanced')

            elif s.size() != 0 and char != s.peek():
                s.pop()

            else:
                pass

    if s.is_empty():
        return print('The paranthesis are balanced')
Exemple #26
0
class MyStackQueue:
    def __init__(self, data):
        self.in_stack = Stack()
        self.out_stack = Stack()
        self.first = None
        self.last = None

    def add(self, data):
        self.in_stack.push(data)

    def remove(self):
        if not self.out_stack.is_empty():
            return self.out_stack.pop()

        self._shift_between_stacks()

        if not self.out_stack.is_empty():
            return self.out_stack.pop()
        else:
            return None

    def peek(self):
        if not self.out_stack.is_empty():
            return self.out_stack.peek()

        self._shift_between_stacks()

        if not self.out_stack.is_empty():
            return self.out_stack.peek()
        else:
            return None

    def is_empty(self):
        return self.out_stack.is_empty() and self.in_stack.is_empty()

    def _shift_between_stacks(self):
        #Move all elements from in_stack to out_stack,
        #then pop from out_stack.
        while not self.in_stack.is_empty():
            self.out_stack.push(self.in_stack.pop())
Exemple #27
0
def is_balanced(string):
    s = Stack()
    is_balanced = True
    index = 0

    while index < len(string) and is_balanced:
        par = string[index]

        if par in "({[":
            s.push(par)
        else:
            if s.is_empty():
                is_balanced = False
            else:
                top = s.pop()

                if not is_match(top, par):
                    is_balanced = False
        index += 1

    if s.is_empty and is_balanced:
        return True
    else:
        return False
Exemple #28
0
class Ghost(MazeRunner):
    def __init__(self, nodes, spritesheet, row):
        MazeRunner.__init__(self, nodes, spritesheet)
        self.name = "ghost"
        self.color = PINK
        self.goal = Vector2D()
        self.modeStack = self.setup_mode_stack()
        self.mode = self.modeStack.pop()
        self.modeTimer = 0
        self.spawnNode = self.find_spawn_node()
        self.set_guide_stack()
        self.set_start_position()
        self.points = 200
        self.released = True
        self.pelletsForRelease = 0
        self.bannedDirections = []
        self.speed = GHOST_SPEED

        self.animate = AnimationGroup()
        self.animateName = "left"
        self.define_animations(row)
        self.animate.set_animation(self.animateName, 0)
        self.image = self.animate.get_image()
        self.previousDirection = self.direction
        self.started = True
        self.hide = True

    def set_guide_stack(self):
        self.guide = Stack()
        self.guide.push(UP)

    def get_valid_directions(self):
        valid_directions = []
        for key in self.node.neighbors.keys():
            if self.node.neighbors[key] is not None:
                if not (key == self.direction * -1):
                    if not self.mode.name == "SPAWN":
                        if not self.node.is_home_entrance:
                            if key not in self.bannedDirections:
                                valid_directions.append(key)
                        else:
                            if key != DOWN:
                                valid_directions.append(key)
                    else:
                        valid_directions.append(key)
        if len(valid_directions) == 0:
            valid_directions.append(self.force_backtrack())
        return valid_directions

    def force_backtrack(self):
        if self.direction * -1 == UP:
            return UP
        if self.direction * -1 == DOWN:
            return DOWN
        if self.direction * -1 == LEFT:
            return LEFT
        if self.direction * -1 == RIGHT:
            return RIGHT

    def get_closest_direction(self, valid_directions):
        distances = []
        for direction in valid_directions:
            diff_vector = self.node.position + direction * TILE_WIDTH - self.goal
            distances.append(diff_vector.magnitude_squared())
        index = distances.index(min(distances))
        return valid_directions[index]

    def move_by_self(self):
        if self.overshot_target():
            self.node = self.target
            self.portal()
            valid_directions = self.get_valid_directions()
            self.direction = self.get_closest_direction(valid_directions)
            self.target = self.node.neighbors[self.direction]
            self.set_position()
            if self.mode.name == "SPAWN":
                if self.position == self.goal:
                    # self.mode = self.modeStack.pop()
                    self.mode = Mode("GUIDE", speedmult=0.2)
            if self.mode.name == "GUIDE":
                if self.guide.is_empty():
                    self.mode = self.modeStack.pop()
                    self.set_guide_stack()
                    self.started = True
                else:
                    self.direction = self.guide.pop()
                    self.target = self.node.neighbors[self.direction]
                    self.set_position()

    def scatter_goal(self):
        self.goal = Vector2D(SCREENSIZE[0], 0)

    def chase_goal(self, pacman):
        self.goal = pacman.position

    def mode_update(self, dt):
        self.modeTimer += dt

        if self.mode.time is not None:
            if self.modeTimer >= self.mode.time:
                self.mode = self.modeStack.pop()
                self.modeTimer = 0

    def find_start_node(self):
        for node in self.nodes.homelist:
            if node.is_ghost_start:
                return node
        return None

    def set_start_position(self):
        self.node = self.find_start_node()
        self.target = self.node
        self.set_position()

    def freight_mode(self):
        if self.mode.name != "SPAWN":
            if self.mode.name != "FREIGHT":
                if self.mode.time is not None:
                    dt = self.mode.time - self.modeTimer
                    self.modeStack.push(Mode(name=self.mode.name, time=dt))
                else:
                    self.modeStack.push(Mode(name=self.mode.name))
                self.mode = Mode("FREIGHT", time=7, speedmult=0.5)
                self.modeTimer = 0
                self.animateName = "freight"
                self.animate.set_animation(self.animateName, 0)
            else:
                self.mode = Mode("FREIGHT", time=7, speedmult=0.5)
                self.modeTimer = 0

    def check_direction_change(self):
        if self.direction != self.previousDirection:
            self.previousDirection = self.direction

        if self.mode.name == "SPAWN":
            self.set_spawn_images()
        elif self.mode.name != "FREIGHT":
            self.set_normal_images()

    def spawn_mode(self):
        self.mode = Mode("SPAWN", speedmult=2)
        self.modeTimer = 0
        self.set_spawn_images()

    def random_goal(self):
        x = randint(0, N_COLS * TILE_WIDTH)
        y = randint(0, N_ROWS * TILE_HEIGHT)
        self.goal = Vector2D(x, y)

    def spawn_goal(self):
        self.goal = self.spawnNode.position

    @staticmethod
    def setup_mode_stack():
        modes = Stack()
        modes.push(Mode(name="CHASE"))
        modes.push(Mode(name="SCATTER", time=5))
        modes.push(Mode(name="CHASE", time=20))
        modes.push(Mode(name="SCATTER", time=7))
        modes.push(Mode(name="CHASE", time=20))
        modes.push(Mode(name="SCATTER", time=7))
        modes.push(Mode(name="CHASE", time=20))
        modes.push(Mode(name="SCATTER", time=7))
        return modes

    def find_spawn_node(self):
        for node in self.nodes.homelist:
            if node.is_spawn_node:
                return node
        return None

    def set_spawn_images(self):
        if self.started:
            if self.direction == LEFT:
                self.animateName = "spawnleft"
            if self.direction == RIGHT:
                self.animateName = "spawnright"
            if self.direction == UP:
                self.animateName = "spawnup"
            if self.direction == DOWN:
                self.animateName = "spawndown"
            self.animate.set_animation(self.animateName, 0)
        else:
            self.set_normal_images()

    def set_normal_images(self):
        if self.direction == LEFT:
            self.animateName = "left"
        if self.direction == RIGHT:
            self.animateName = "right"
        if self.direction == UP:
            self.animateName = "up"
        if self.direction == DOWN:
            self.animateName = "down"
        self.animate.set_animation(self.animateName, 0)

    def update(self, dt, pacman):
        speed_modifier = self.speed * self.mode.speedmult
        self.position += self.direction * speed_modifier * dt
        self.mode_update(dt)
        self.check_direction_change()
        self.image = self.animate.loop(dt)
        if self.mode.name == "CHASE":
            self.chase_goal(pacman)
        elif self.mode.name == "SCATTER":
            self.scatter_goal()
        elif self.mode.name == "FREIGHT":
            self.random_goal()
        elif self.mode.name == "SPAWN":
            self.spawn_goal()
        self.move_by_self()

    def define_animations(self, row):
        animation = Animation("up")

        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(0, row, 32, 32))
        animation.add_frame(self.spritesheet.get_image(1, row, 32, 32))
        self.animate.add(animation)

        animation = Animation("down")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(2, row, 32, 32))
        animation.add_frame(self.spritesheet.get_image(3, row, 32, 32))
        self.animate.add(animation)

        animation = Animation("left")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(4, row, 32, 32))
        animation.add_frame(self.spritesheet.get_image(5, row, 32, 32))
        self.animate.add(animation)

        animation = Animation("right")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(6, row, 32, 32))
        animation.add_frame(self.spritesheet.get_image(7, row, 32, 32))
        self.animate.add(animation)

        animation = Animation("freight")
        animation.speed = 10
        for i in range(25):
            animation.add_frame(self.spritesheet.get_image(0, 6, 32, 32))
            animation.add_frame(self.spritesheet.get_image(1, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(2, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(3, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(0, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(1, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(2, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(3, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(0, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(1, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(2, 6, 32, 32))
        animation.add_frame(self.spritesheet.get_image(3, 6, 32, 32))
        self.animate.add(animation)

        animation = Animation("spawnup")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(4, 6, 32, 32))
        self.animate.add(animation)

        animation = Animation("spawndown")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(5, 6, 32, 32))
        self.animate.add(animation)

        animation = Animation("spawnleft")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(6, 6, 32, 32))
        self.animate.add(animation)

        animation = Animation("spawnright")
        animation.speed = 10
        animation.add_frame(self.spritesheet.get_image(7, 6, 32, 32))
        self.animate.add(animation)
Exemple #29
0
 def test_size_returns_1_for_1_item_stack(self):
     test_obj = Stack()
     test_data = 'data1'
     test_obj.push(test_data)
     self.assertEqual(1, test_obj.size())
     self.assertEqual(False, test_obj.is_empty())
Exemple #30
0
 def test_is_empty_false(self):
     test_obj = Stack()
     test_obj.push('data')
     self.assertEqual(False, test_obj.is_empty())
Exemple #31
0
 def test_is_empty(self):
     stack = Stack()
     self.assertEqual(stack.is_empty(), True)
     stack.push(5)
     self.assertEqual(stack.is_empty(), False)