Example #1
0
def generalized_balanced_checker(
        tokens: str,
        supported_symbols: dict = {
            "opens": "({[",
            "closes": ")}]"
        }) -> bool:
    """
    Write an algorithm that will read a string of supported_symbols from left to
    right and decide whether the symbols are balanced
    """
    idx: int = 0
    s = Stack()
    balanced: bool = True

    def is_closing(top_symbol, closing_symbol):
        return supported_symbols["opens"].index(
            top_symbol) == supported_symbols["closes"].index(closing_symbol)

    while idx < len(tokens):
        symbol = tokens[idx]
        if symbol in supported_symbols["opens"]:
            s.push(symbol)
        else:
            if s.is_empty():
                balanced = False
            else:
                top_symbol = s.pop()
                if not is_closing(top_symbol, symbol):
                    balanced = False
        idx += 1

    if balanced and s.is_empty():
        return True
    else:
        return False
Example #2
0
 def test__stack_operations__ok(self):
     s = Stack()
     s.push(10)
     assert s.size() == 1
     assert s.peek() == 10
     s.push(22)
     assert s.size() == 2
     assert s.peek() == 22
     assert s.is_empty() == False
     s.pop()
     assert s.size() == 1
     s.pop()
     assert s.size() == 0
     assert s.is_empty() == True
Example #3
0
def balanced_parens_checker(tokens: str) -> bool:
    """
    Write an algorithm that will read a string of parentheses from left to
    right and decide whether the symbols are balanced
    """
    idx: int = 0
    s = Stack()
    balanced: bool = True

    while idx < len(tokens):
        symbol = tokens[idx]
        if symbol == "(":
            s.push(symbol)
        else:
            if s.is_empty():
                balanced = False
            else:
                s.pop()
        idx += 1

    if balanced and s.is_empty():
        return True
    else:
        return False
Example #4
0
def divide_by_2(num: int) -> str:
    """
    Takes an interger and returns its equivalent in binary
    """

    s = Stack()
    binary_str: str = ""

    if num == 0:
        s.push(num)

    while num > 0:
        num, remainder = divmod(num, 2)
        s.push(remainder)

    while not s.is_empty():
        digit = s.pop()
        binary_str += str(digit)

    return binary_str
Example #5
0
def base_converter(num: int, base: int) -> str:
    """
    Ref: http://calc.50x.eu/
    """
    stack = Stack()
    converted_str: str = ""
    digits = "0123456789ABCDEF"

    if num == 0:
        stack.push(num)

    while num > 0:
        num, remainder = divmod(num, base)
        stack.push(remainder)

    while not stack.is_empty():
        digit = stack.pop()
        converted_str += digits[digit]

    return converted_str
Example #6
0
 def test__new_stack__is_empty(self):
     s = Stack()
     assert s.size() == 0
     assert s.is_empty() == True
     assert s.peek() == None