Example #1
0
def main(fichier):

     s=stack.create()
     ind_char=stack.create()
     ind_ligne=stack.create()
     nb_ligne=0
     in_channel = open(fichier, 'r')
    
     chaine="debut"

     while(chaine != ''):
           chaine=in_channel.readline()
           nb_ligne=nb_ligne+1

           for i in range(len(chaine)):

               if(chaine[i]=="(" or chaine[i]=="[" or chaine[i]=="{") :
                   stack.push(chaine[i],s)
                   stack.push(i,ind_char)
                   stack.push(nb_ligne,ind_ligne)

               elif(chaine[i]==")" or chaine[i]=="]" or chaine[i]=="}"):
                    if(not (stack.is_empty(s))):
                          if (stack.top(s)==getOpening(chaine[i])):
                                 stack.pop(s)
                          else:
                                 print("Closed parenthese",chaine[i]," at line ",nb_ligne," char ",i," don't match the open parenthese ",stack.top(s)," at line ",stack.top(ind_ligne)," char ",stack.top(ind_char))
                    else:
                                 print("No open parenthese matching parenthese ",chaine[i]," at line ",nb_ligne," char ",i)
           
           chaine=in_channel.readline()
     if(not stack.is_empty(s)):
          print("Parenthese ",stack.top(s)," at line ",stack.top(nb_ligne)," char ",stack.top(nb_char)," has no matching closed parenthese.")
Example #2
0
def solve_puzzle(red, green, blue):
    """
    Takes in three stacks and then sorts them based on ball color.
    First it checks each ball in the red can. If the ball is green it
    goes in green, if the ball is red or blue it goes in blue. Then it
    looks at the blue can. If the ball is red it goes in the red, if it
    is blue it goes in the green. Lastly all the blue balls in the green
    can move back to the blue can and the stacks of balls will be sorted.
    The function also tracks the amount of moves the sorting process takes
    and returns it.
    Pre-Conditions: It is assumed that all balls will begin in the red can and
    that the green and blue cans are empty.
    :param red: Red Can
    :param green: Green Can
    :param blue: Blue Can
    :return: moves
    """
    moves = 0
    stack_list = [red, green, blue]
    while stack.is_empty(red) != True:
        top_val = stack.top(red)
        if top_val == "R" or top_val == "B":
            stack.pop(red)
            stack.push(blue, top_val)
            animate.animate_move(stack_list, 0, 2)
        else:
            stack.pop(red)
            stack.push(green, top_val)
            animate.animate_move(stack_list, 0, 1)
        moves += 1
    while stack.is_empty(blue) != True:
        top_val = stack.top(blue)
        if top_val == "R":
            stack.pop(blue)
            stack.push(red, top_val)
            animate.animate_move(stack_list, 2, 0)
        else:
            stack.pop(blue)
            stack.push(green, top_val)
            animate.animate_move(stack_list, 2, 1)
        moves += 1
    while stack.top(green) != "G":
        top_val = stack.top(green)
        stack.pop(green)
        stack.push(blue, top_val)
        animate.animate_move(stack_list, 1, 2)
        moves += 1
    return moves
Example #3
0
    def moveOneValid(self):
        #after moveing the smallest left, there should
        #only be one valid move to make other than moving the 1. Make it!
        print "Move the smallest disk to the left"
        self.moveSmallestLeft()
        self.toString()
        print ""
        self.generateMoves()
        moves = self.validMoves

        #remove all moves that involve moving the 1 disk
        theonestack = None
        for stack in self.stacks:
            if stack.top() == 1:
                theonestack = self.stacks.index(stack)

        removeAll = [(theonestack, 0), (theonestack, 1), (theonestack, 2)]
        r = removeAll

        for move in r:
            if move[0] == move[1]:
                removeAll.remove(move)

        for move in removeAll:
            if move in self.validMoves:
                moves.remove(move)

        if (len(moves) > 1):
            print "error"
        elif self.validMoves:
            self.move(self.validMoves[0])
Example #4
0
	def moveOneValid(self):
		#after moveing the smallest left, there should
		#only be one valid move to make other than moving the 1. Make it!
		print "Move the smallest disk to the left"
		self.moveSmallestLeft()
		self.toString()
		print ""
		self.generateMoves()
		moves = self.validMoves
		
		#remove all moves that involve moving the 1 disk
		theonestack = None
		for stack in self.stacks:
			if stack.top() == 1:
				theonestack = self.stacks.index(stack)
				
			
		removeAll = [(theonestack,0),(theonestack,1),(theonestack,2)]
		r = removeAll
		
		for move in r:
			if move[0] == move[1]:
				removeAll.remove(move)
		
		for move in removeAll:
			if move in self.validMoves:
				moves.remove(move)
		
		if(len(moves) > 1):
			print "error"
		elif self.validMoves:
			self.move(self.validMoves[0])
Example #5
0
def minimum_bracket_reversals(input_string):
    """
    Calculate the number of reversals to fix the brackets

    Args:
       input_string(string): Strings to be used for bracket reversal calculation
    Returns:
       int: Number of breacket reversals needed
    """
    if len(input_string) % 2 == 1:
        return -1

    stack = Stack()
    count = 0
    for bracket in input_string:
        if stack.is_empty():
            stack.push(bracket)
        else:
            top = stack.top()
            if top != bracket:
                if top == "{":
                    stack.pop()
            stack.push(bracket)
    
    while not stack.is_empty():
        first = stack.pop()
        second = stack.pop()
        if first == "}" and second == "}":
            count += 1
        elif first == '{' and second == '}':
            count += 2
        elif first == '{' and second == '{':
            count += 1
    return count
Example #6
0
def validateEquation(valueStack, opStack):
    validChar = "+-*/%^("
    topOp = stack.top(opStack)
    topValue = stack.top(valueStack)
    # Pop topValue
    stack.pop(valueStack)
    # This determines whether an equation can be solved or not
    if topOp in validChar:
        try:
            secValue = stack.top(valueStack)
            secValue = float(secValue)
            stack.push(valueStack, topValue)
            return True
        except ValueError:
            return False
    else:
        stack.push(valueStack, topValue)
        return True
def deliminate(cmd):
    op = cmd[0]
    if op == 'push':
        stack.push(num=int(cmd[1]))
    if op == 'pop':
        print(stack.pop())
    if op == 'size':
        print(stack.size())
    if op == 'empty':
        print(stack.empty())
    if op == 'top':
        print(stack.top())
Example #8
0
	def moveSmallestLeft(self):
		fromstack = None
		tostack = None
		for stack in self.stacks:
			if stack.top() == 1:
				fromstack = self.stacks.index(stack)
				tostack = fromstack - 1
				if tostack == -1:
					tostack = 2
				print "One is on: %d and one left of that is %d" %(fromstack,tostack)
		
		self.move((fromstack, tostack))
Example #9
0
    def moveSmallestLeft(self):
        fromstack = None
        tostack = None
        for stack in self.stacks:
            if stack.top() == 1:
                fromstack = self.stacks.index(stack)
                tostack = fromstack - 1
                if tostack == -1:
                    tostack = 2
                print "One is on: %d and one left of that is %d" % (fromstack,
                                                                    tostack)

        self.move((fromstack, tostack))
Example #10
0
def verif_parentheses(chaine):
    s=stack.create()

    for i in range(len(chaine)):
        """        
        print(s)
        """        
        if(chaine[i]=="(" or chaine[i]=="[" or chaine[i]=="{") :
              stack.push(chaine[i],s)
        elif(chaine[i]==")" or chaine[i]=="]" or chaine[i]=="}"):
              if(not (stack.is_empty(s)) and stack.top(s)==getOpening(chaine[i])):
                   stack.pop(s)
              else:
                  return -1
    if(stack.is_empty(s)):
        return 1
    else:
        return 0
Example #11
0
def inOrder(node):
  stack = stack.stack()
  stack.push(node)
  finished = False
  while not stack.empty():
    top = stack.top()
    if finished:
      print('{}'.format(top.data))
      stack.pop()
      if top.right != None:
        stack.push(top.right)
        finished = False
    elif top.left != None:
      stack.push(top.left)
    else:
      print('{}'.format(top.data))
      if top.right != None:
        stack.push(top.right)
        finished = False
      else:
        finished = True # leaf
        stack.pop()
Example #12
0
def postOrder(node):
  stack = stack.stack()
  stack.push(node)
  lastest = None
  while not stack.empty():
    top = stack.top()
    if top.left == lastest and top.right == None:
      print('{}'.format(top.data))
      lastest = top
      stack.pop()
    elif top.right == lastest:
      print('{}'.format(top.data))
      lastest = top
      stack.pop()
    else:
      if top.right != None:
        stack.push(top.right)
      if top.left != None:
        stack.push(top.left)
      if top.left == None and top.right == None:
        print('{}'.format(top.data))
        lastest = top
        stack.pop()
Example #13
0
import stack
""" Ask the user to enter a series of braces and parentheses,
    then indicate if they are properly nested
"""

char = input('Enter parentheses and/or braces: ')

sequence = stack.getStack()

#for every element in the received string checks the type and pushes/pops in/from the stack
for el in char:
    if el == '(' or el == '{':
        stack.push(sequence, el)
    elif not stack.isEmpty(sequence):
        if el == ')' and stack.top(sequence) == '(':
            stack.pop(sequence)
        elif el == '}' and stack.top(sequence) == '{':
            stack.pop(sequence)

#Final check if the stack is empty
#If it's empty the string is proper
if stack.isEmpty(sequence):
    print('Nested properly.')
else:
    print('Not properly nested.')
Example #14
0
def stackPush(listEquation, inputPriority, stackPriority):
    valueStack = stack.stack()
    opStack = stack.stack()
    inputStack = stack.stack()
    stack.push(valueStack, "$")
    stack.push(opStack, "$")
    stack.push(inputStack, -1)
    # To count the number of elements in the equation list
    count = 0
    for i in listEquation:
        count += 1
        print("Looking at", i, "in the equation")
        if i in "123456789":
            stack.push(valueStack, i)
            print("Adding", i, "to valueStack")
        elif i in "+-*/%^(":
            # This solves the part of the equation before this, until the new
            #  input priority can be put in
            while inputPriority [i] <= stack.top(inputStack):
                print("STACK VALUE >= the new INPUT PRIORITY.", end = " ") 
                print("So pop and process, and recheck.")
                newValue = getValues(valueStack, inputStack, opStack)
                newValue = float(newValue)
                print("New answer being placed into the VALUE", end = " ")
                print("stack is: ", newValue)
                stack.push(valueStack, newValue)
            stack.push(opStack, i)
            print(i, "was just added to opStack")
            stack.push(inputStack, stackPriority [i])
            print(stackPriority [i], "was just added to inputStack")
        elif i == ")":
            print("Pop and process, found a )")
            while stack.top(opStack) != "(" and stack.top(opStack) != "$":
                newValue = getValues(valueStack, inputStack, opStack)
                newValue = float(newValue)
                print("New answer being placed into the VALUE", end = " ")
                print("stack is: ", newValue)
                stack.push(valueStack, newValue)
            # This makes sure that there is a '(' in the equation   
            if stack.top(opStack) == "$":
                print("ERROR: unable to solve equation")
                return
            else:
                stack.pop(opStack)
                stack.pop(inputStack)
        if len(listEquation) == count:
            boolean = False
            # This determines if the equation has been solved or not
            if stack.top(valueStack) == "$" and stack.top(opStack) == "$":
                try:
                    stack.push(valueStack, newValue)
                    boolean = True
                except UnboundLocalError:
                    print("ERROR: unable to solve equation")
                    return
            while boolean == False:
                print("END OF EQUATION, so pop and process until", end = " ")
                print("opStack is only a '$'")
                topValue = stack.top(valueStack)
                # Solves for errors
                if stack.top(valueStack) == "$" and stack.top(opStack) != "$":
                    print("ERROR: unable to solve equation")
                    return
                stack.pop(valueStack)
                topValue = float(topValue)
                if stack.top(valueStack) == "$" and stack.top(opStack) == "$":
                    print("The answer is ", topValue)
                    return
                stack.push(valueStack, topValue)
                bool2 = validateEquation(valueStack, opStack)
                if bool2 == False:
                    print("ERROR: unable to solve equation")
                    return
                newValue = getValues(valueStack, inputStack, opStack)
                # Catches this error
                if newValue == "???":
                    print("ERROR: unable to solve equation")
                    return
                newValue = float(newValue)
                print("New answer being placed into the VALUE", end = " ")
                print("stack is: ", newValue)
                if stack.top(valueStack) == "$" and stack.top(opStack) == "$":
                    stack.push(valueStack, newValue)
                    boolean = True
                else:
                    stack.push(valueStack, newValue)
    newValue = stack.pop(valueStack)
    print("The answer is ", float(newValue))
Example #15
0
# import stack module
import stack

# user input
pa = input("Enter parentheses and/or braces: ")

# define pa_stack
pa_stack = stack.getStack()

for i in range(0, len(pa)):

# when character is left parentheses or braces push to the stack
    if pa[i] == "(" or pa[i] == "{":
        stack.push(pa_stack, pa[i])

# when character is right parentheses or braces pop the stack
# if the value of the stack for top is left parentheses or braces
    else:
        if stack.top(pa_stack) == "(" and pa[i] == ")":
            stack.pop(pa_stack)
        elif stack.top(pa_stack) == "{" and pa[i] == "}":
            stack.pop(pa_stack)

# output "Nested properly." when stack is empty
if stack.isEmpty(pa_stack):
    print("Nested properly.")
else:
    print("Not properly nested.")
Example #16
0
        if item in operator:
            operand_last = stack.pop(oper_stack)
            operand_second_last = stack.pop(oper_stack)
            if operand_second_last == None:
                # print('stack underflow')
                termination()
            else:
                stack.push(oper_stack,
                           operation(item, operand_last, operand_second_last))
        elif item == '=':
            right_most_position = False
        else:
            stack.push(oper_stack, int(item))

    # The result will be stored on the last of oper_stack
    result = stack.top(oper_stack)

    # If result is None, it means the input is only one =
    # If oper_stack have more than 1 arguments, it means operator is not sufficient
    if result == None:
        # print('one =')
        termination()
    if len(oper_stack) > 1:
        # print('two or more')
        termination()
    if stack.top(slot) != '=':
        # print('no =')
        termination()

    if type(result) == float:
        if float.is_integer(result):
s = stack.getStack()
proper = True

# Make times to run while loop
i = 0
i_limit = len(inp)

while proper and i < i_limit:
    item = inp[i]

    # Left things will be had push
    if item == '(' or item == '{' or item == '[':
        stack.push(s, item)
    # Right things will be had pop and be found that it is matched properly
    else:
        top_stack = stack.top(s)
        if item == ')' and top_stack == '(':
            stack.pop(s)
        elif item == '}' and top_stack == '{':
            stack.pop(s)
        elif item == ']' and top_stack == '[':
            stack.pop(s)
        else:
            proper = False
    #
    # for item in inp:
    #     if item == '(' or item == '{' or item == '[':
    #         stack.push(s, item)
    #     elif item == ')' or item == '}' or item == ']':
    #         if item == stack.top(s):
    #             stack.pop(s)
Example #18
0
import stack

""" Ask the user to enter a series of braces and parentheses,
    then indicate if they are properly nested
"""

char = input('Enter parentheses and/or braces: ')

sequence = stack.getStack()

#for every element in the received string checks the type and pushes/pops in/from the stack
for el in char:
    if el == '(' or el == '{':
        stack.push(sequence, el)
    elif not stack.isEmpty(sequence):
        if el == ')' and stack.top(sequence) == '(':
            stack.pop(sequence)
        elif el == '}' and stack.top(sequence) == '{':
            stack.pop(sequence)

#Final check if the stack is empty
#If it's empty the string is proper
if stack.isEmpty(sequence):
    print('Nested properly.')
else:
    print('Not properly nested.')