Exemple #1
0
def rpn_calc(postfix_expr):
    """Evaluate a postfix expression"""

    operandStack = Stack()
    tokenList = postfix_expr.split()
    try:
        for token in tokenList:
            if token in "0123456789":
                operandStack.push(int(token))
            elif token in "+-*/":
                if operandStack.size() < 2:
                    raise StackError("Stack is empty")
                else:
                    operand2 = operandStack.pop()
                    operand1 = operandStack.pop()
                    result = doMath(token, operand1, operand2)
                    operandStack.push(result)
            else:
                raise TokenError(f"Unknown token: {token}")
        if operandStack.size() > 1:
            raise StackError("Stack is not empty")

    except TokenError as err:
        raise TokenError(f"{err}")
    except SyntaxError:
        raise SyntaxError("Invalid syntax")
    except StackError as err:
        raise StackError(f"{err}")
    else:
        return operandStack.pop()
Exemple #2
0
def postfix_eval(postfix_expr: str) -> int:
    """Evaluate an expression"""
    operand_stack = Stack()
    token_list = postfix_expr[:-2].split()

    for token in token_list:
        # if token in "0123456789":
        try:
            if isinstance(int(token), int):
                operand_stack.push(int(token))
        except ValueError:
            if token in ("+", "-", "*", "/", "%", "//", "**"):
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                result = do_math(token, operand1, operand2)
                operand_stack.push(result)
            else:
                raise TokenError(f"Unknown token: {token}")
    try:
        answer = operand_stack.pop()
    except IndexError:
        raise StackError("Stack is empty") from IndexError

    if not operand_stack.is_empty():
        raise StackError("Stack is not empty")

    return answer
Exemple #3
0
def par_checker_ext(line):
    """Check if parentheses & brackets are balanced"""
    stack = Stack()
    balanced = True
    i = 0
    while i < len(line) and balanced:
        symbol = line[i]
        if symbol in "( { [ <":
            stack.push(symbol)
        else:
            if stack.is_empty():
                balanced = False
            else:
                sym2 = (
                    symbol.replace(")", "(")
                    .replace("]", "[")
                    .replace("}", "{")
                    .replace(">", "<")
                )
                if sym2 == stack.peek():
                    stack.pop()
                else:
                    balanced = False
        i = i + 1
    return balanced and stack.is_empty()
def par_checker(symbol_string):
    s = Stack()
    for symbol in symbol_string:
        if symbol == "(":
            s.push(symbol)
        else:
            if s.is_empty():
                return False
            else:
                s.pop()

    return s.is_empty()
def to_str(n, base):
    r_stack = Stack()
    convert_string = "0123456789ABCDEF"
    while n > 0:
        if n < base:
            r_stack.push(convert_string[n])
        else:
            r_stack.push(convert_string[n % base])
        n = n // base
    res = ""
    while not r_stack.is_empty():
        res = res + str(r_stack.pop())
    return res
Exemple #6
0
def rpn_calc(postfix_expr):
    """Evaluate a postfix expression"""
    operand_stack = Stack()
    token_list = postfix_expr.split()

    try:
        for token in token_list:
            if token in "0123456789":
                operand_stack.push(int(token))
            elif token in "+-*/":
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                result = do_math(token, operand1, operand2)
                operand_stack.push(result)
            else:
                raise TokenError(f'Unknown token: {token}')
        answer = operand_stack.pop()
        print(operand_stack.is_empty())
        if operand_stack.is_empty() is False:
            raise StackError("Stack is not empty")
        return answer
    except IndexError:
        raise StackError("Stack is empty") from IndexError
Exemple #7
0
def par_checker(line):
    """Textbook implementation"""
    stack = Stack()
    balanced = True
    i = 0
    while i < len(line) and balanced:
        symbol = line[i]
        if symbol == "(":
            stack.push(symbol)
        else:
            if stack.is_empty():
                balanced = False
            else:
                stack.pop()
        i = i + 1
    return balanced and stack.is_empty()
Exemple #8
0
def rev_string(my_str):
    """Reverse characters in a string using a stack"""
    stack = Stack()
    rev_str = ''
    for i in my_str:
        stack.push(i)
    while stack.is_empty() is False:
        rev_str += stack.pop()
    return rev_str
Exemple #9
0
def balance_checker(symbol_string):
    s = Stack()
    for symbol in symbol_string:
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.is_empty():
                return False
            else:
                if not matches(s.pop(), symbol):
                    return False

    return s.is_empty()
Exemple #10
0
def rev_string(my_str):
    """Reverse characters in a string using a stack"""
    char_stack = Stack()
    for char in my_str:
        char_stack.push(char)
    new_chars = []
    while char_stack.size() > 0:
        new_chars.append(char_stack.pop())
    new_str = "".join(str(char) for char in new_chars)
    return new_str
Exemple #11
0
    def __init__(self, degree, nodes={}, rootIndex=1, freeIndex=2):
        # This method is complete
        self.degree = degree

        if len(nodes) == 0:
            self.rootNode = BTreeNode(degree)
            self.nodes = {}
            self.rootNode.setIndex(rootIndex)
            self.writeAt(1, self.rootNode)
        else:
            self.nodes = deepcopy(nodes)
            self.rootNode = self.nodes[rootIndex]

        self.stackOfNodes = Stack()
        self.rootIndex = rootIndex
        self.freeIndex = freeIndex
Exemple #12
0
def rev_string(my_str):
    tmpStack = Stack()
    revStr = ""

    for ch in my_str:
        tmpStack.push(ch)

    while not tmpStack.is_empty():
        revStr = revStr + str(tmpStack.pop())

    return revStr
Exemple #13
0
def par_checker_ext(line):
    """Check if parentheses are balanced"""
    stack = Stack()
    lefts = "([{<"
    rights = ")]}>"
    for i in line:
        if i in "([{<":
            stack.push(i)
        else:
            if stack.is_empty():
                return False
            if lefts.index(stack.pop()) != rights.index(i):
                return False
    return True
def base_converter(decimal_num, base):
    digits = "0123456789ABCDEF"
    rem_stack = Stack()

    while decimal_num > 0:
        rem = decimal_num % base
        rem_stack.push(rem)
        decimal_num = decimal_num // base

    new_string = ""
    while not rem_stack.is_empty():
        new_string = new_string + digits[rem_stack.pop()]

    return new_string
Exemple #15
0
def base_converter(dec_num, base):
    """Convert a decimal number to any base"""
    if base not in [2, 8, 16]:
        raise ValueError(f'Cannot convert to base {base}.')

    digits = "0123456789ABCDEF"
    remains = Stack()

    while dec_num > 0:
        rem = dec_num % base
        remains.push(rem)
        dec_num = dec_num // base

    output = ''
    while not remains.is_empty():
        output += digits[remains.pop()]

    return output
Exemple #16
0
def base_converter(dec_num, base):
    """Convert a decimal number to any base"""
    digits = "0123456789ABCDEF"
    remstack = Stack()
    try:
        if base in (2, 8, 16):
            while dec_num > 0:
                rem = dec_num % base
                remstack.push(rem)
                dec_num = dec_num // base
            new_string = ""
            ctr = remstack.size()
            while ctr > 0:
                new_string = new_string + digits[remstack.pop()]
                ctr -= 1
            return new_string
        else:
            raise BaseError
    except BaseError:
        print("Invalid base:  only 2, 8, or 16 may be used")
# Specifies the absolute path to the pythonds3 module
import os
import sys

sys.path.insert(0,
                os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

import pytest
from pythonds3.basic import Deque
from pythonds3.basic import OrderedList
from pythonds3.basic import Queue
from pythonds3.basic import Stack
from pythonds3.basic import UnorderedList

data_structures = {
    "stack": Stack(),
    "queue": Queue(),
    "deque": Deque(),
    "olist": OrderedList(),
    "ulist": UnorderedList(),
}


# Setup
@pytest.fixture(params=data_structures)
def set_up(request):
    """Setting up"""
    return data_structures[request.param]


# Test if new instances of these ds's are empty
Exemple #18
0
def postfix_eval(postfix_expr: str) -> int:
    """ evaluate postfix expressions in a string """
    operandStack = Stack()
    tokenList = postfix_expr.split()
    try:
        for token in tokenList:
            if token.isnumeric():
                operandStack.push(int(token))
            elif token in "* ** / // % + -":
                ## this if statement is not working - why not?
                if operandStack.size() < 2:
                    raise SyntaxError("invalid syntax")
                else:
                    operand2 = operandStack.pop()
                    operand1 = operandStack.pop()
                    result = do_math(token, operand1, operand2)
                    operandStack.push(result)
            elif token == "=":
                if operandStack.size() > 1:
                    raise StackError("Stack is not empty")
                elif operandStack.size() == 0:
                    raise StackError("Stack is empty")
                else:
                    return operandStack.pop()
            else:
                raise TokenError(f"Unknown token: {token}")
    except ZeroDivisionError as err:
        raise ZeroDivisionError(f"{err}")
    except SyntaxError:
        raise SyntaxError(f"Invalid syntax")
    except TokenError as err:
        raise TokenError(f"{err}")
# Specifies the absolute path to the pythonds3 module
import os
import sys
sys.path.insert(0,
                os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import pytest
from pythonds3.basic import Deque
from pythonds3.basic import OrderedList
from pythonds3.basic import Queue
from pythonds3.basic import Stack
from pythonds3.basic import UnorderedList

data_structures = {
    'stack': Stack(),
    'queue': Queue(),
    'deque': Deque(),
    'olist': OrderedList(),
    'ulist': UnorderedList()
}


# Setup
@pytest.fixture(params=data_structures)
def set_up(request):
    '''Setting up'''
    return data_structures[request.param]


# Test if new instances of these ds's are empty
my_list.add(31)
my_list.add(77)
my_list.add(17)
my_list.add(93)
my_list.add(26)
my_list.add(54)

print(my_list.size())
print(my_list.search(93))
print(my_list.search(100))

# Alternative implementation from the pythonds3 library
# -> sudo pip3 install pythonds3
from pythonds3.basic import Stack

s = Stack()

print(s.is_empty())
s.push(4)
s.push("dog")
print(s.peek())
s.push(True)
print(s.size())
print(s.is_empty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())

m = Stack()
m.push("x")