Beispiel #1
0
def reverse(str):
    str2 = []
    s = Stack()
    for i in str:
        s.push(i)
    while (str != []):
        t = s.pop()
        str2.append(t)
    return str2
    def test_pop_odd(self):
        test = Stack('1 2 3')

        self.assertEqual('3', test.pop())
        self.assertEqual(['1', '2'], test.data)

        self.assertEqual('2', test.pop())
        self.assertEqual(['1'], test.data)
        self.assertEqual('1', test.pop())
        self.assertEqual(None, test.pop())
    def test_pop_even(self):
        test = Stack('1 2 3 4')

        self.assertEqual('4', test.pop())
        self.assertEqual(['1', '2', '3'], test.data)

        self.assertEqual('3', test.pop())
        self.assertEqual(['1', '2'], test.data)
        self.assertEqual('2', test.pop())
        self.assertEqual('1', test.pop())
        self.assertEqual(None, test.pop())
def decimal_to_bin(number):
    s = Stack()

    while number > 0:
        s.push( number % 2 )
        number //= 2

    bin_str = ''
    while not s.isEmpty():
        bin_str += str(s.pop())

    return bin_str
def convert_to_base(number, base):
    convert = '0123456789ABCDEF'

    s = Stack()

    while number > 0:
        s.push( convert[number % base] )
        number //= base

    result = ''
    while not s.isEmpty():
        result += str(s.pop())

    return result
def parenthesesChecker(symbolString):
    """
    Checks whether or not a set of parentheses is correctly balanced
    """
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.isEmpty():
        return True
    else:
        return False

# test
#print(parenthesesChecker('((()))'))
#print(parenthesesChecker('(()'))
def revString(myStr):
    """
    Reverses a String
    """
    
    s = Stack()
    
    for c in myStr:
        s.push(c)
        
    newStr = ""
    
    while not s.isEmpty():
        newStr += s.pop()
        
    return newStr

# test
#print(revString("hello"))
def divideBy2(n):
    """
    Returns the binary form of a decimal number
    """
    
    s = Stack()
    
    while n != 0:
        reminder = n % 2
        s.push(reminder)
        n = n / 2
        
    binaryString = ""
    
    while not s.isEmpty():
        binaryString += str(s.pop())
        
    return binaryString

# test
#print(divideBy2(233))
Beispiel #9
0
def baseConverter(n, base):
    """
    Returns a decimal number into another base between 1 and 16
    """

    digits = "0123456789ABCDEF"

    s = Stack()

    while n != 0:
        reminder = n % base
        s.push(reminder)
        n = n / base

    baseString = ""

    while not s.isEmpty():
        baseString += digits[s.pop()]

    return baseString


# test
#print(baseConverter(25, 2))
#print(baseConverter(256, 16))
def eval_postfix(postfix_exp):
    operands = Stack()
    postfix = postfix_exp.split()

    for sym in postfix:
        if sym.isdigit():
            operands.push(int(sym))
        elif sym in operators.keys():
            second = operands.pop()
            first = operands.pop()
            operands.push(operators[sym](first, second))
        else:
            raise TypeError("Wrong expression")
    return operands.pop()
def baseConverter(n, base):
    """
    Returns a decimal number into another base between 1 and 16
    """
    
    digits = "0123456789ABCDEF"
    
    s = Stack()
    
    while n != 0:
        reminder = n % base
        s.push(reminder)
        n = n / base
        
    baseString = ""
    
    while not s.isEmpty():
        baseString += digits[s.pop()]
        
    return baseString

# test
#print(baseConverter(25, 2))
#print(baseConverter(256, 16))
def dec_to_bin(dec_num):
    rs = Stack()
    while dec_num > 0:
        r = dec_num % 2
        rs.push(r)
        dec_num = dec_num // 2

    return_str = ""
    while not rs.isEmpty():
        return_str = return_str + str(rs.pop())

    return return_str
def general_parentheses_checker(expression):

    sym_dict = {')':'(', '}': '{', ']': '['}

    s = Stack()
    for symbol in expression:
        if symbol in '([{':
            s.push(symbol)
        elif symbol in ')]}':
            if s.isEmpty():
                return False
            else:
                if sym_dict[symbol] == s.peek():
                    s.pop()
                else:
                    return False
    if s.isEmpty():
        return True
    else:
        return False
def check_parentheses(expression):
    """

    """
    s = Stack()
    for symbol in expression:
        if symbol == '(':
            s.push(symbol)
        elif symbol == ')':
            if s.isEmpty():
                return False
            else:
                s.pop()
    if s.isEmpty():
        return True
    else:
        return False
def dec_to_other_base(dec_num, base):
    digits = "0123456789ABCDEF"
    rs = Stack()
    while dec_num > 0:
        r = dec_num % base
        rs.push(r)
        dec_num = dec_num // base

    return_str = ""
    while not rs.isEmpty():
        return_str = return_str + digits[rs.pop()]

    return return_str


#print(dec_to_bin(233))

#print(dec_to_other_base(255,16))
Beispiel #16
0
def revString(myStr):
    """
    Reverses a String
    """

    s = Stack()

    for c in myStr:
        s.push(c)

    newStr = ""

    while not s.isEmpty():
        newStr += s.pop()

    return newStr


# test
#print(revString("hello"))
def tirpleParenthesesChecker(symbolString):
    """
    Checks whether or not a set of parentheses,
    square brackets and curly braces is correctly balanced
    """
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top, symbol):
                    balanced = False
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False
Beispiel #18
0
from stack_implementation import Stack
"""Import the stack class to create objects, test its functions."""
a = Stack()
a.push(4)
a.push(3)
a.display()
a.pop()
a.pop()
a.display()
def infix_to_postfix(infix_exp):
    operators = Stack()
    infix_exp = infix_exp.split()

    postfix = []
    for sym in infix_exp:
        if sym in string.ascii_letters or sym.isdigit():
            postfix.append(sym)
        elif sym == "(":
            operators.push(sym)
        elif sym == ")":
            while not operators.peek() == "(":
                postfix.append(operators.pop())
            operators.pop()
        elif sym in precedence.keys():
            while not operators.isEmpty() and precedence[operators.peek()] >= precedence[sym]:
                postfix.append(operators.pop())
            operators.push(sym)
        else:
            raise TypeError("Wrong expression")
    while not operators.isEmpty():
        postfix.append(operators.pop())
    return " ".join(postfix)
def eval_infix(infix_exp):
    operands = Stack()
    op_stack = Stack()
    infix = infix_exp.split()

    for sym in infix:
        if sym.isdigit():
            operands.push(sym)
        elif sym == "(":
            op_stack.push(sym)
        elif sym == ")":
            second = float(operands.pop())
            first = float(operands.pop())
            op = op_stack.pop()
            operands.push(operators[op](first, second))
            op_stack.pop()
        elif sym in operators.keys():
            if not op_stack.isEmpty() and precedence[op_stack.peek()] >= precedence[sym]:
                op = op_stack.pop()
                second = float(operands.pop())
                first = float(operands.pop())
                operands.push(operators[op](first, second))
            op_stack.push(sym)

    while not operands.size() == 1:
        second = float(operands.pop())
        first = float(operands.pop())
        op = op_stack.pop()
        operands.push(operators[op](first, second))
    return operands.pop()
    def test_push(self):
        test = Stack()
        test.push('5')

        self.assertEqual(['5'], test.data)