def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString
def baseConverter(decNumber, base):
    digits = "0123456789ABCDEF"

    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % base
        remstack.push(rem)
        decNumber = decNumber // base

    newString = ""
    while not remstack.isEmpty():
        newString = newString + digits[remstack.pop()]

    return newString
コード例 #3
0
def toStr(n, base):
    convertString = '0123456789ABCDEF' # can cover base upto 16
    rStack = Stack()
    while n >0:
        if n<base:
            rStack.push(convertString[n])
        else:
            rStack.push(convertString[n % base])
        n= n // base
    res = ''
    while not rStack.isEmpty():
        res = res + rStack.pop()
    return res
def postfixEval(postfixExpr):
    operandStack = Stack()

    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)

    return operandStack.pop()
def parChecker(symbolString):
    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
def parChecker(symbolString):
    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
コード例 #7
0
ファイル: revstring.py プロジェクト: XyK0907/for_work
def revstring(mystr):
    s = Stack()
    for each in mystr:
        s.push(each)
    result = ''.join(s.pop() for i in range(s.size()))
    print(result)
コード例 #8
0
    def size(self):
        return len(self.items)

'''
Remember that nothing happens when we click the run button other than
the definition of the class. We must create a Stack object and then use
it. ActiveCode 2 shows the Stack class in action as we perform the
sequence of operations from Table 1. Notice that the definition of the
Stack class is imported from the pythonds module.
'''

# Make sure to pip install pythonds. I was able to use that import 
# statement in the Python prompt without any issues:
from pythonds.basic import Stack

s=Stack()

print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())


'''
コード例 #9
0
from pythonds.basic import Stack

s = Stack()

print(s.isEmpty())

s.push(4)
s.push('dog')

print(s.peek())  # dog
print(s.pop())  # dog
print(s.size(), s.items)
print('dfsdf %s' % 'xxx')
コード例 #10
0
 def creatS(self, fpexp):
     fplist = fpexp.split()
     p_stack = Stack()
     e_tree = BinaryTree('')
     p_stack.push(e_tree)
     current_tree = e_tree
     for i in fplist:
         if i == "(":
             current_tree.insert_left('')
             p_stack.push(current_tree)
             current_tree = current_tree.get_left_child()
         elif i in "'and','or'":
             current_tree.set_root_val(i)
             current_tree.insert_right('')
             p_stack.push(current_tree)
             current_tree = current_tree.get_right_child()
         elif i in "'not'":
             current_tree = p_stack.pop()
             current_tree.set_root_val(i)
             current_tree.insert_left(False)
             current_tree.insert_right('')
             p_stack.push(current_tree)
             current_tree = current_tree.get_right_child()
         elif i == ')':
             current_tree = p_stack.pop()
         else:
             current_tree.set_root_val(i)
             parent = p_stack.pop()
             current_tree = parent
             if i not in self.symbols:
                 self.symbols.append(i)
     self.val = e_tree
コード例 #11
0
def infixToPostfix(tokenList):
    """Converts an infix arithmetic expression to postfix"""

    # Creating a dictionary to hold oprator precedence
    prec = {}
    prec['*'] = 3
    prec['/'] = 3
    prec['+'] = 2
    prec['-'] = 2
    prec['('] = 1

    opStack = Stack()
    postfixList = []

    for token in tokenList:
        # Adding any operands to the postFix list
        if token in string.ascii_uppercase:
            postfixList.append(token)

        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()
                   and (prec[opStack.peek()] >= prec[token])):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)
コード例 #12
0
def infixToPostfix(infixexpr):
    prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    opStack = Stack()
    postfixList = []
    try:
        tokenList = infixexpr.split()
        for token in tokenList:
            if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
                postfixList.append(token)
            elif token == '(':
                opStack.push(token)
            elif token == ')':
                topToken = opStack.pop()
                while topToken != '(':
                    postfixList.append(topToken)
                    topToken = opStack.pop()
            else:
                while (not opStack.isEmpty()) and \
                        (prec[opStack.peek()] >= prec[token]):
                    postfixList.append(opStack.pop())
                opStack.push(token)
    except:
        return f"Incorrect object type for infix expression.{TypeError}"

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
コード例 #13
0
def infix2postfix(infix):
    prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1}

    opStack = Stack()
    postfixLst = []

    token_lst = infix.split()

    for token in token_lst:
        if token in string.ascii_uppercase:
            postfixLst.append(token)

        elif token == '(':
            opStack.push(token)

        elif token == ')':
            topToken = opStack.pop()
            while topToken != "(":
                postfixLst.append(topToken)
                topToken = opStack.pop()

        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                               prec[token]):  # peek可看顶端元素
                postfixLst.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixLst.append(opStack.pop())

    return " ".join(postfixLst)
コード例 #14
0
def infix_to_postfix(infix_expr):
    """
    Convert an infix mathematical expression into an postfix expression.
    :param infix_expr: String of infix expression
    :return: original infix expression as a postfix expression
    """
    prec = {"**": 4, "//": 3, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    op_stack = Stack()  # Stack to hold operators
    postfix_list = []  # Where we will insert our postfix expression to print
    token_list = []
    tmp_str = ''
    operator_str = ''
    for ch in infix_expr:  # Convert expression into a list  3.0*5 + 4
        if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or ch in "0123456789.":
            if operator_str != '':
                token_list.append(operator_str)
                operator_str = ''
            tmp_str = tmp_str + ch
        elif ch in "*+/-":
            if tmp_str != '':
                token_list.append(tmp_str)
                tmp_str = ''
            operator_str = operator_str + ch
        elif ch in "()":
            if tmp_str != '':
                token_list.append(tmp_str)
                tmp_str = ''
            elif operator_str != '':
                token_list.append(operator_str)
                operator_str = ''
            token_list.append(ch)
    if tmp_str != '':
        token_list.append(tmp_str)
    if tmp_str != '':
        token_list.append(operator_str)

    for token in token_list:  # Go through each item in the list.
        if token not in "+-**//()":
            postfix_list.append(token)  # add expression to list, not operator
        elif token == '(':  # Notify that we'll have an operator of top priority coming up
            op_stack.push(token)
        elif token == ')':
            top_token = op_stack.pop()
            while top_token != '(':  # Take the operator out of the stack and insert into our pfix list
                postfix_list.append(
                    top_token)  # continue for as many tokens were in the ()
                top_token = op_stack.pop()
        elif token == '':
            pass
        else:
            while (not op_stack.isEmpty()) and \
                    (prec[op_stack.peek()] >= prec[token]):  # compare operator precedence, decide which goes first
                postfix_list.append(op_stack.pop())
            op_stack.push(token)

    while not op_stack.isEmpty():
        postfix_list.append(op_stack.pop())
    return " ".join(postfix_list)
コード例 #15
0
# 5_convert_integer_string_stack.py
from pythonds.basic import Stack

rStack = Stack()


def toStr(n, base):
    convertString = "0123456789ABCDEF"
    while n > 0:
        if n < base:
            rStack.push(convertString[n])
        else:
            rStack.push(convertString[n % base])
        n = n // base
    res = ""

    while not rStack.isEmpty():
        res = res + str(rStack.pop())

    return res


print(toStr(1453, 16))
コード例 #16
0
def buildParseTree(expr):
    lot = expr.split()
    tree = BinaryTree("")
    posStack = Stack()
    posStack.push(tree)
    currentTree = tree

    for token in lot:
        if token == "(":
            currentTree.insertLeft("")
            posStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif token == ")":
            currentTree = posStack.pop()
        elif token in ["and", "or"]:
            currentTree.setRootVal(token)
            currentTree.insertRight("")
            posStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif token == "not":
            parent = posStack.pop()
            currentTree = parent
            currentTree.setRootVal(token)
            posStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif token in ["1", "0"]:
            currentTree.setRootVal(int(token))
            parent = posStack.pop()
            currentTree = parent
    return tree
コード例 #17
0
def infixToPostfixEval(expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    opStack = Stack()
    operandStack = Stack()
    postfixList = []
    tokenList = expr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789!":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                               prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    str = " ".join(postfixList)
    tokenList2 = str.split()

    for token in tokenList2:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            return "Cannot be evaluated"
        elif token in "0123456789":
            operandStack.push(int(token))
        elif token == '!':
            operand = operandStack.pop()
            result = math.factorial(operand)
            operandStack.push(result)
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)

    x = str, "Evaluates to: ", operandStack.pop()

    return x
コード例 #18
0
class ASM_COMPLEX_IF():
    args_list = []
    reserved_bool1 = 0
    reserved_bool2 = 0
    stack_args = ''
    list_completed = []
    formed_code = ''
    target_if_true = ''
    target_if_false = ''

    def __init__(self, args_list, target_if_true, target_if_false):
        self.args_list = args_list
        self.target_if_true = target_if_true
        self.target_if_false = target_if_false
        # init a empty stack
        self.stack_args = Stack()
        # insert each value in the args list into the stack
        for item in self.args_list[::-1]:
            self.stack_args.push(item)

    def detect_conditions(self, cmp):
        return conditions[cmp]

    def detect_contrary(self, cmp):
        return contrary_conditions[cmp]

    def detect_bool_available(self):
        if self.reserved_bool1 == 0:
            self.reserved_bool1 = 1
            return 'r_bool_1'
        if self.reserved_bool2 == 0:
            self.reserved_bool2 = 1
            return 'r_bool_1'

    def get_params(self):
        # peek the value in the stack
        temp_op1 = ''
        temp_op2 = ''

        while self.stack_args.size() > 0:
            # peek the value found in stack
            curr_val = self.stack_args.peek()

            if curr_val not in operands:
                if temp_op1 == '':
                    temp_op1 = self.stack_args.pop()
                if temp_op2 == '':
                    temp_op2 = self.stack_args.pop()
            else:
                # FOUND A OPERAND
                op = self.stack_args.pop()
                # generate the if code based on the operand
                if op in rel_eq_op:
                    # get the type of comparison and contrary
                    cond = self.detect_conditions(op)
                    contr = self.detect_contrary(cond)
                    temp = self.detect_bool_available()
                    # generate the template
                    template = Template(if_complex['if_false'])
                    # if reserved bool
                    # replace the values in template
                    template = template.safe_substitute(reg1 = temp_op1, reg2 = temp_op2, comp = cond, temp = temp, contr = contr, t_false = self.target_if_false)
                    # append to the completed code
                    self.formed_code = self.formed_code + template

                # IF IN CASE NOT IN THE BASIC OPERANDS IT IS && OR ||
                else:
                    # DOESNT DO ANYTHING UP TO NOW
                   op = 0  
                    

                    

# test area
# a = ASM_COMPLEX_IF(['r2', 'r1', '>', 'r1', 'r2', '==', '&&', 'sucasa', 'ddfa', '>', '||'])
# a.get_params()
コード例 #19
0
def tranfortExpress(expression):
    priority = {}
    priority["/"] = 3
    priority["*"] = 3
    priority["+"] = 2
    priority["-"] = 2
    priority["("] = 1

    emptyStack = Stack()
    emptyList = []

    tokenList = expression.split()

    for token in tokenList:
        if token in string.ascii_uppercase:
            emptyList.append(token)
        elif token == '(':
            emptyStack.push(token)
        elif token == ')':
            topToken = emptyStack.pop()
            while topToken != '(':
                emptyList.append(topToken)
                topToken = emptyStack.pop()
        else:
            while (not emptyStack.isEmpty()) and \
                    (priority[emptyStack.peek()] >= priority[token]):
                emptyList.append(emptyStack.pop())
            emptyStack.push(token)
    while not emptyStack.isEmpty():
        emptyList.append(emptyStack.pop())

    return ' '.join(emptyList)
コード例 #20
0
def base_conversion(base, number):
    s = Stack()
    while number > 0:
        s.push(number % base)
        number = number // base
    return s
コード例 #21
0
def infixToPostfit(infixexpr):
    # 记录操作符优先级
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    # 解析表达式到单词列表
    tokenList = infixexpr.split()
    #print(tokenList)
    
    for token in tokenList:
        if token in "+-*/":
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            postfixList.append(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())   # 操作符
    return " ".join(postfixList)    # 合成后缀表达式
コード例 #22
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["**"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
コード例 #23
0
def infixToPostfix(infix):
    #infix = '(' + infix + ')'
    #Initialize Stack.
    opStack = Stack()
    output = ""
    #print(infix)
    #Loop Through All Tokens:
    for token in infix:
        #Case 1: Operator.
        if (isOperator(token)):
            while (not (opStack.isEmpty()) and isOperator(opStack.peek()) and (
                (getAssociativity(token) == 'L'
                 and getPrecedence(opStack.peek()) >= getPrecedence(token)) or
                (getAssociativity(token) == 'R'
                 and getPrecedence(opStack.peek()) > getPrecedence(token)))):
                output += opStack.peek()
                opStack.pop()
            opStack.push(token)
        #Case 2: Left Paranthesis.
        elif (token == '('):
            opStack.push(token)
        #Case 3: Right Paranthesis.
        elif (token == ')'):
            while (not (opStack.isEmpty()) and opStack.peek() != '('):
                output += opStack.peek()
                opStack.pop()
            #Error-Checking:
            if (opStack.isEmpty()):
                # print("Empty Stack.")
                print(output)
                # return "ERROR"
            if (opStack.peek() == '('):
                opStack.pop()
        else:
            #Check For Non-Alpha Characters:
            if (not (token.isalpha())):
                # print("Not Alpha Not Space:", token, ".")
                return "ERROR"
            output += token
    #Append All Remaining Characters From opStack.
    while (not (opStack.isEmpty())):
        if (opStack.peek() == '(' or opStack.peek() == ')'):
            # print("Uh-OH! Mismatched Paranthesis")
            return "ERROR"
        output += opStack.peek()
        opStack.pop()
    #Return Output.
    return output
コード例 #24
0
- The base of the stack is significant since items stored in the stack that are closer to the base represent those that have beeen in 
the stack the longest.

- LIFO: Last-in first-out
  - The most recently added item is the one that is in position to be removed first.
  - This principle provides an ordering based on length of time in the collection. 
  - Newer items are near the top, while older items are near the base. 

Strength of Stacks:
- GREAT for reversing the order of items. 
- Keeping track of state or when things have occured. 
'''

# 4.4 ----------------- THE STACK ABSTRACT DATA TYPE
'''
Stack() : Creates a new stack that is empty. It needs no parameters and returns an empty stack.

push(item) : Adds a new item to the top of the stack. It needs the item and returns nothing.

pop() : Removes the top item from the stack. It needs no parameters and returns the item. The stack is modified.

peek() : Returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified.

isEmpty() : Tests to see whether the stack is empty. It needs no parameters and returns a boolean value.

size() : Returns the number of items on the stack. It needs no parameters and returns an integer.
'''

# 4.5 ----------------- IMPLEMENTATING A STACK IN PYTHON
コード例 #25
0
def infixToPostfix(expression):

    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    tempStack = Stack()
    postfixList = []
    tokenList = expression.split()
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":

            postfixList.append(token)
        elif token == "(":
            tempStack.push(token)
        elif token == ")":
            toptoken = tempStack.pop()
            while toptoken != '(':
                postfixList.append(toptoken)
                toptoken = tempStack.pop()
        else:
            while (not tempStack.isEmpty()) and (prec[tempStack.peek()] >= prec[token]):
                postfixList.append(tempStack.pop())
            tempStack.push(token)

    while not tempStack.isEmpty():
        postfixList.append(tempStack.pop())

    return " ".join(postfixList)
コード例 #26
0
def convertToTree(postfix):
    #If Output convertInfixToPrefix Returned "ERROR" + Postfix = "RORRE".
    if (postfix == "RORRE"):
        return
    #Initialize Stack.
    convertToTree = Stack()
    for k in range(0, len(postfix)):
        #Case 1: Operator + Not-Negation
        if (isOperator(postfix[k]) and postfix[k] != "~"):
            #Pop Previous One TreeNode.
            prevOne = None
            if (not (convertToTree.isEmpty())):
                prevOne = convertToTree.peek()
                convertToTree.pop()
            #Pop Previous Two TreeNode.
            prevTwo = None
            if (not (convertToTree.isEmpty())):
                prevTwo = convertToTree.peek()
                convertToTree.pop()
            #Create + Set New TreeNode.
            currentNode = TreeNode(postfix[k])
            currentNode.left = prevTwo
            currentNode.right = prevOne
            convertToTree.push(currentNode)
        #Case 2: Operator + Negation.
        elif (isOperator(postfix[k]) and postfix[k] == "~"):
            #Pop Previous One TreeNode.
            prevOne = None
            if (not (convertToTree.isEmpty())):
                prevOne = convertToTree.peek()
                convertToTree.pop()
            #Create + Set New TreeNode.
            currentNode = TreeNode(postfix[k])
            currentNode.left = prevOne
            convertToTree.push(currentNode)
        #Case 3: New Leaf Node.
        else:
            currentNode = TreeNode(postfix[k])
            convertToTree.push(currentNode)

    #Assert Only Root:
    # if(convertToTree.size() != 1):
    # print("Error In Construction. Must Review Input/Output.")
    #Set New Head Value = Top/Root of Stack.
    return convertToTree.peek()
コード例 #27
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            found = False
            while topToken != '(' and not opStack.isEmpty():
                found = True
                postfixList.append(topToken)
                topToken = opStack.pop()
            if not found:
                raise Exception('Unbalanced parentheses,too much ")"')
        else:
            while (not opStack.isEmpty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)
    unbalanced_found = False
    while not opStack.isEmpty():
        last = opStack.pop()
        if last == '(':
            unbalanced_found = True
            raise Exception('Unbalanced parentheses,too much "("')
        postfixList.append(last)
    return " ".join(postfixList)
コード例 #28
0
def direct_infix_evaluator(infixexpr: str) -> int or float:
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixEvaluation = Stack()
    tokenList = infixexpr.split()
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixEvaluation.push(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            found = False
            while topToken != '(' and not opStack.isEmpty():
                found = True
                operator = topToken
                operand2 = postfixEvaluation.pop()
                operand1 = postfixEvaluation.pop()
                postfixEvaluation.push(doMath(operator, operand1, operand2))
                topToken = opStack.pop()
            if not found:
                raise Exception('Unbalanced parentheses,too much ")"')
        else:
            while (not opStack.isEmpty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                operator = opStack.pop()
                operand2 = postfixEvaluation.pop()
                operand1 = postfixEvaluation.pop()
                postfixEvaluation.push(doMath(operator, operand1, operand2))
            opStack.push(token)
    unbalanced_found = False
    while not opStack.isEmpty():
        last = opStack.pop()
        if last == '(':
            unbalanced_found = True
            raise Exception('Unbalanced parentheses,too much "("')
        operator = last
        operand2 = postfixEvaluation.pop()
        operand1 = postfixEvaluation.pop()
        postfixEvaluation.push(doMath(operator, operand1, operand2))
    return postfixEvaluation.pop()
コード例 #29
0
ファイル: stackframes.py プロジェクト: cypherphage/__python__
from pythonds.basic import Stack

s = Stack()


def tostr(num, base):
    strconv = "0123456789ABCDEF"
    while num > 0:
        if num < base:
            s.push(strconv[num])
        else:
            s.push(strconv[num % base])
        num = num // base
    out = ""
    while not s.isEmpty():
        out = out + str(s.pop())

    return out


print(tostr(999999, 2))
コード例 #30
0
ファイル: kth_search.py プロジェクト: Suredammy/Pythond
from pythonds.basic import Stack
s = Stack()
s.push(4)
print(s.peek())
コード例 #31
0
def infixToPostfix(infixQuery,term):
    queryList = infixQuery.split() 
    queryStack = Stack()
    postfixQuery = []
    precOperator = {}
    precOperator["not"] = 4
    precOperator["and"] = 3
    precOperator["or"] = 2
    precOperator["("] = 1

    for query in queryList:
        if query in term:
            postfixQuery.append(query)
            indexNext = queryList.index(query)+1
            if indexNext != len(queryList) and (queryList[indexNext] in term):
                queryStack.push("and")
        elif query == '(':
            queryStack.push(query)
        elif query == ')':
            stackTeratas = queryStack.pop()
            while stackTeratas != '(':
                postfixQuery.append(stackTeratas)
                stackTeratas = queryStack.pop()
        else:
            while (queryStack.isEmpty() != True) and (precOperator[queryStack.peek()] >= precOperator[query]):
                  postfixQuery.append(queryStack.pop())
            queryStack.push(query)

    while (queryStack.isEmpty() != True):
        postfixQuery.append(queryStack.pop())

    return postfixQuery
コード例 #32
0
def infixToPrefix(infixexpr):
    exprList = infixexpr.split(' ')
    exprList.reverse()
    output = []
    opStack = Stack()

    for token in exprList:
        if token == ')':
            opStack.push(token)
        elif token == '(':  # pop until find the left-parenthesis.
            while True:
                op = opStack.pop()
                if op == ')':
                    break
                else:
                    output.append(op)
        elif token in ['+', '-', '*', '/']:
            # pop superior or equal operators then push operator.
            # do not pop `)` here.
            while not opStack.isEmpty() and opStack.peek() != ')':
                if isSuperiorOrEqual(opStack.peek(), token):
                    output.append(opStack.pop())
                else:
                    break
            opStack.push(token)
        else:
            output.append(token)

    # retrieve the remain marks in operation stack.
    while not opStack.isEmpty():
        output.append(opStack.pop())

    output.reverse(
    )  # output is a reverse of prefix as a result of beginning reverse operation.
    return ' '.join(output)
コード例 #33
0
def infixEval(infixexpr):
    prec = {}
    prec["^"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    infixexpr = list(infixexpr)
    tokenList = []
    
    for token in infixexpr:
        if token != ' ':
            tokenList.append(token)
            tokenList.append(' ')
        else:
            continue
               
    tokenList = ''.join(tokenList).split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    postfixExpr = " ".join(postfixList)
    
    solution = postfixEval(postfixExpr)
    return postfixExpr
コード例 #34
0
def evalPostfix(postfixExpr):
    exprList = postfixExpr.split(' ')
    operandStack = Stack()

    for token in exprList:
        if token == '+':
            operandStack.push(operandStack.pop() + operandStack.pop())
        elif token == '-':  # in minus, calculation order is opposite to pop order.
            operand1 = operandStack.pop()
            operand2 = operandStack.pop()
            operandStack.push(operand2 - operand1)
        elif token == '*':
            operandStack.push(operandStack.pop() * operandStack.pop())
        elif token == '/':  # in division, calculation order is opposite to pop order.
            operand1 = operandStack.pop()
            operand2 = operandStack.pop()
            operandStack.push(operand2 / operand1)
        else:
            operandStack.push(float(token))

    return operandStack.pop()
コード例 #35
0
def infixToPostfixEval(infixExpre):
    prec = {}
    prec["!"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixExpre.split()

    #infix to postfix
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    postfixExpre = (" ".join(postfixList))

    #postfix to eval
    operandStack = Stack()
    tokenList = postfixExpre.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        #seperate statements for factorial
        elif token == "!":
            operand1 = operandStack.pop()
            result = doFactorial(operand1)
            operandStack.push(result)
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)

    return postfixExpre, operandStack.pop()
コード例 #36
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    opStack = Stack()
    postfixList = []

    tokenList = infixexpr.split()

    for token in tokenList:
        if token in string.ascii_uppercase:
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)