Beispiel #1
0
def buildparsetree(exp):
    plist = exp.split()
    pstack = Stack()
    tree = BinaryTree('')
    pstack.push(tree)
    current_tree = tree

    for item in plist:

        if item == '(':
            current_tree.insert_left('')
            pstack.push(current_tree)
            current_tree = current_tree.get_lc()

        elif item not in ['+', '-', '*', '/', ')']:
            current_tree.set_root(float(item))
            current_tree = pstack.pop()

        elif item in ['+', '-', '*', '/']:
            current_tree.set_root(item)
            current_tree.insert_right('')
            pstack.push(current_tree)
            current_tree = current_tree.get_rc()

        elif item == ')':
            current_tree = pstack.pop()

        else:
            raise ValueError

    return tree
Beispiel #2
0
def convertbase2(n):
    
    a=Stack()
    binstring=""
    while n>0:
        a.push(n%2)
        n=n//2
    while not a.isEmpty():
        binstring+=str(a.pop())
    return binstring
def buildparsetree(exp):
    plist = exp.split()
    pstack = Stack()
    tree = BinaryTree('')
    pstack.push(tree)
    current_tree = tree

    for item in plist:

        if item == '(':
            current_tree.insert_left('')
            pstack.push(current_tree)
            current_tree = current_tree.get_lc()

        elif item not in ['+', '-', '*', '/', ')']:
            current_tree.set_root(float(item))
            current_tree = pstack.pop()

        elif item in ['+', '-', '*', '/']:
            current_tree.set_root(item)
            current_tree.insert_right('')
            pstack.push(current_tree)
            current_tree = current_tree.get_rc()

        elif item == ')':
            current_tree = pstack.pop()

        else:
            raise ValueError

    return tree
def int_to_bin(value):
    stack = Stack()
    num = int(value)
    binary_num = ''

    while num > 0:
        stack.push(num % 2)
        num //= 2
    while stack.contains_items():
        binary_num += str(stack.pop())
    return binary_num
def base_converter():
    stack = Stack()
    digits = '0123456789ABCDEF'
    num = int(raw_input('Enter a number to convert: '))
    base = int(raw_input('Enter a base to convert to: '))
    new_num = ''

    while num > 0:
        stack.push(num % base)
        num //= base

    while stack.contains_items():
        new_num += str(digits[stack.pop()])
    return new_num
def base_converter():
    stack = Stack()
    digits = "0123456789ABCDEF"
    num = int(raw_input("Enter a number in base-10 to convert: "))
    base = int(raw_input("Enter a base to convert it to: "))
    new_num = ""

    while num > 0:
        stack.push(num % base)
        num //= base

    while stack.contains_items():
        new_num += str(digits[stack.pop()])
    print new_num
Beispiel #7
0
def postfixxer(prefix):
    s=Stack()
    l=len(prefix)
    for i in range(l-1,-1,-1):
        if(isOperator(prefix[i])):
            temp=s.pop()
            temp2=temp+s.pop()+prefix[i]
            s.push(temp2)
        else:
            s.push(prefix[i])

    return s.peek()       
def infixxer(postfix):
    s = Stack()
    l = len(postfix)
    for i in range(l):
        if (isOperator(postfix[i])):
            temp = s.pop()
            temp2 = '(' + s.pop() + postfix[i] + temp + ')'
            s.push(temp2)
        else:
            s.push(postfix[i])

    return s.peek()
Beispiel #9
0
def prefixxer(postfix):
    s = Stack()
    l = len(postfix)
    for i in range(l):
        if (isOperator(postfix[i])):
            temp = ''
            temp2 = ''
            temp = s.pop()
            temp2 = postfix[i] + s.pop() + temp
            s.push(temp2)
        else:
            s.push(postfix[i])

    return s.peek()
Beispiel #10
0
def postfix_evaluator(statement):
    operands_stack = Stack()
    statement_list = statement.split(' ')
    operators_dict = {'*': operator.mul, '/': operator.div,
                      '+': operator.add, '-': operator.sub}

    for char in statement_list:
        if char in operators_dict and operands_stack.size() >= 2:
            b = operands_stack.pop()
            a = operands_stack.pop()
            operands_stack.push(operators_dict[char](a,b))
        else:
            operands_stack.push(float(char))

    return operands_stack.pop()
Beispiel #11
0
 def solve(self):
     """
     Function to solve a sudoku puzzle using DFS (I think).
     Function modifies and returns a completed puzzle.
     """
     storage = Stack()
     attempt = self.trial(storage)
     while not attempt.is_solved():
         if len(storage) == 0:
             print "This sudoku puzzle is not solvable."
             return self
         else:
             (board, cell, moves) = storage.pop()
             board.set_pos(cell[0], cell[1], moves[0])
             if len(moves) > 1:
                 storage.push((board.clone(), cell, moves[1:]))
             attempt = board.trial(storage)
     print "Solution found."
     self = attempt
     return self
def revertOrder(a_list):
  the_stack = Stack()
  the_reverted_cards = []
  for i in a_list:
    the_stack.push(i)
  while not the_stack.is_empty():
    the_reverted_cards.append(the_stack.pop())
  return the_reverted_cards
def paren_checker(string):
    stack = Stack()

    for char in string:
        if char == '(':
            stack.push(char)
        elif char == ')':
            if stack.contains_items():
                stack.pop()
            else:
                return 'Unbalanced'

    if stack.contains_items():
        return 'Unbalanced'
    else:
        return 'Balanced'
class PalindromeChecker:

    # Initializtion/Constructor
    def __init__(self):
        self.stringToCheck = None
        self.stringStack = Stack()
        self.isPalindrome = False

# This method checks if a string (argument)
# is a palindrome. The method returns a
# boolean.

    def checkString(self, string):

        # Initialize return value to be True
        booleanValue = True

        # Show string to be evaluated
        print "Checking string %s" % string

        # Remove punctuations
        string = re.sub('[!@#$.?,]', '', string)

        # Set the attribute
        self.stringToCheck = string.lower()

        # Fill the stack
        for eachChar in self.stringToCheck:
            self.stringStack.push(eachChar)

        #print self.stringStack.printStack()
        for eachChar in self.stringToCheck:
            if eachChar != self.stringStack.pop():
                booleanValue = False

# return boolean
        return booleanValue
class PalindromeChecker:
    
	# Initializtion/Constructor
        def __init__(self):
            self.stringToCheck = None
            self.stringStack = Stack()
            self.isPalindrome = False
            
	# This method checks if a string (argument)
	# is a palindrome. The method returns a 
	# boolean.
        def checkString(self, string):
	
	    # Initialize return value to be True
            booleanValue = True

	    # Show string to be evaluated
            print "Checking string %s" % string
	    
            # Remove punctuations 
	    string = re.sub('[!@#$.?,]', '', string)	  

	    # Set the attribute
	    self.stringToCheck = string.lower()

            # Fill the stack            
            for eachChar in self.stringToCheck:
                self.stringStack.push(eachChar)
            
            #print self.stringStack.printStack()
            for eachChar in self.stringToCheck:
                if eachChar != self.stringStack.pop():
                    booleanValue = False
		
	    # return boolean
            return booleanValue
Beispiel #16
0
    def Evaluate(self, postfix):
        opStack = Stack()
        tokenList = postfix.split()

        for token in tokenList:
            if self.__is_number(token) or token == "pi" or token == "e":
                if token == "pi":
                    token = np.pi
                elif token == "e":
                    token = np.e
                opStack.push(float(token))
            else:
                op2 = opStack.pop()
                op1 = opStack.pop()
                result = self.__doMath(token, op1, op2)
                opStack.push(result)
        return opStack.pop()
def int_to_bin(value):
    stack = Stack()
    num = int(value)
    binary_num = ''

    while num > 0:
        stack.push(num % 2)
        num //= 2
    while stack.contains_items():
        binary_num += str(stack.pop())
    return binary_num
def base_converter():
    stack = Stack()
    digits = '0123456789ABCDEF'
    num = int(raw_input('Enter a number in base-10 to convert: '))
    base = int(raw_input('Enter a base to convert it to: '))
    new_num = ''

    while num > 0:
        stack.push(num % base)
        num //= base

    while stack.contains_items():
        new_num += str(digits[stack.pop()])
    print new_num
def general_checker(string):
    stack = Stack()
    opens = '([{<'
    closes = ')]}>'

    for char in string:
        if char in opens:
            stack.push(char)
        elif char in closes:
            if not stack.contains_items():
                return "Stack prematurely empty. Unbalanced."
            else:
                prior = stack.pop()
                return match_checker(char,
                                     prior)  # returns Balanced or Unbalanced
    if stack.contains_items():
        return 'Unbalanced'
    else:
        return 'Balanced'
Beispiel #20
0
def postfix(infix):
    
    #op stack is where we store left parentheses, it will count
    #how much we need to pop when we hit a right parenthesis
    opstack=Stack()
    #output will be the return of all our values
    output=[]
    #splits up the infix notation equation
    input1=list(infix)
    #declare a dict
    prec={}
    #determine the level of precedence for operators
    prec['*']=3
    prec['/']=3
    prec['+']=2
    prec['-']=2
    prec['(']=1
    
    for i in input1:
        #append non operators/ parenthesises into output
        if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1023456789':
            output.append(i)
        #if is a left parenthesis, append it to the stack
        elif i =='(':
            opstack.push(i)
        #if it is a right parenthesis,
        #pop a left parenthesis out of the stack
        elif i==')':
            topToken=opstack.pop()
        #while the top of the stack is NOT a left parenthesis and
        #is an operator, keep on popping that shit into the output
            while topToken !="(":
                output.append(topToken)
                topToken=opstack.pop()
        #else if it is an operator
        else:
            #while the opstack is NOT empty and and the operator's precident in the stack
            #is GREATER than the operator currently being iterated on
            #pop that operator into the stack
            while (not opstack.isEmpty()) and (prec[opstack.peek()]) >=prec[i]:
                output.append(opstack.pop())
            #otherwise, just push the current operator into the stack
            opstack.push(i)
    #and this last while loop is to get out the remaining operators at the end
    while not opstack.isEmpty():
        output.append(opstack.pop())
    return " ".join(output)
 def __init__(self):
     self.stringToCheck = None
     self.stringStack = Stack()
     self.isPalindrome = False
Beispiel #22
0
# This program displays the first 50 prime numbers
# And ses a stack to store the prime numbers

# Import Stack class
from StackClass import Stack

# Create stack to store prime numbers
stack = Stack()


# Define isPrime with num as a parameter
# This function returns True if the number is prime and false is not
def isPrime(num):
    for i in range(2, num // 2 + 1):
        if num % i == 0:
            return False
    return True


# Define primeNum function
# Set accumalator name to 'num' with a value of 2
# Create while statement that calls the getSize method from the Stack class
# only if the numbers are below 50
# Create if statement within while statement that if num == 2 or isPrime == True
# then push num to the stack by calling the push method
# Have num increment by 1 so that each number can be checked if isPrime or not
# Print the stack while size of the stack if below 50
def primeNum():
    num = 2
    while stack.getSize() < 50:
        if num == 2 or isPrime(num) == True:
Beispiel #23
0
    def postfix_from(self, infix):
        infix = self.__prepare(infix)
        prec = {}
        prec["^"] = 4
        prec["*"] = 3
        prec["/"] = 3
        prec["+"] = 2
        prec["-"] = 2
        prec["("] = 1
        opStack = Stack()
        postfixList = []
        tokenList = infix.split()

        for token in tokenList:
            if self.__is_number(token) or token == "pi" or token == "e":
                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)
def stackCards(a_list):
  the_stack = Stack()
  for i in a_list:
    the_stack.push(i)
  return the_stack
 def __init__(self):
     self.stringToCheck = None
     self.stringStack = Stack()
     self.isPalindrome = False
Beispiel #26
0
def postfix_converter(infixstring):
    op_stack = Stack()
    output_list = []
    infix_list = infixstring.split(' ')
    operators = '*/+-'

    for char in infix_list:
        if char == '(':
            op_stack.push(char)
        elif char == ')':
            prior_op = op_stack.pop()
            while prior_op != '(':
                output_list.append(prior_op)
                prior_op = op_stack.pop()
        elif char in operators:
            if op_stack.contains_items() and op_stack.peek() in '*/':
                output_list.append(op_stack.pop())
                op_stack.push(char)
            else:
                op_stack.push(char)
        else:
            output_list.append(char)

    while op_stack.contains_items():
        output_list.append(op_stack.pop())

    return " ".join(output_list)
Beispiel #27
0
"""Qustions. A Python programm to perform various 
operations on a stack using Stack Class"""
#Using the Stack Class of Stack.py Program
from StackClass import Stack
# Create empty stack object
s = Stack()
#Display Menu
Choice = 0
while Choice < 5:
    print('_______Stack Operation_______')
    print('1. Push Element')
    print('2. Pop Element')
    print('3. Peep Element')
    print('4. Search for Element')
    print('5. Exit')
    Choice = int(input('Enter your Choice:'))

    # Perform a task depending on user choice
    if Choice == 1:
        element = int(input('Enter Element:'))
        s.__push__(element)
    elif Choice == 2:
        element = s.pop()
        if element == -1:
            print('The Stack Is Empty')
        else:
            print('Popped element=', element)
    elif Choice == 3:
        element = s.peep()
        print('Topmost Element=', element)
    elif Choice == 4:
##############################################
#
# Programmer: Stanley Wong
# File: StackDriver.py
# Description: Python Stack Driver
#
##############################################
from StackClass import Stack

myStack = Stack()

myStack.push(22)
myStack.push(33)
myStack.push(44)
myStack.pop()
myStack.push(99)
myStack.push(55)
myStack.push(88)
myStack.pop()
myStack.push(77)
myStack.push(11)
myStack.pop()
myStack.push(88)

myStack.printStack()