예제 #1
0
def is_breces_sequence_correct(s: str):
    """
    checks the correctness of the breces sequence 
    of parentheses and square brackets () []

    >>> is_breces_sequence_correct("(([()]))[]")
    True
    >>> is_breces_sequence_correct("([)]")
    False
    >>> is_breces_sequence_correct("(")
    False
    >>> is_breces_sequence_correct("]")
    False
    """
    for brace in s:
        if brace not in "()[]":
            continue
        if brace in "([":
            stack.push(brace)
        else:
            assert brace in ")]", "Closing braces expected: " + str(brace)
            if stack.is_empty():
                return False
            left = stack.pop()
            assert left in "([", "Opening braces expected: " + str(brace)
            if left == "(":
                right = ")"
            elif left == "[":
                right = "]"
            if right != brace:
                return False
    return stack.is_empty()            
def is_braces_sequences_correct(s):
    """
    Проверяет корректность скобочной последовательности из куглых и квадратных скобок.
    >>> is_braces_sequences_correct('(([()]))[]')
    True
    >>> is_braces_sequences_correct('[(])')
    False
    >>> is_braces_sequences_correct('(')
    False
    >>> is_braces_sequences_correct(']')
    False
    """
    braces = '()[]'
    for brace in s:
        if brace not in braces:
            continue
        if brace in '([':
            stack.push(brace)
        else:
            assert brace in ')]', 'Oups! I expect close brace: ' + str(brace)
            if stack.is_empty():
                return False
            left = stack.pop()
            assert left in '([', 'Oups! I expect open brace: ' + str(brace)
            if left == "(":
                right = ")"
            if left == "[":
                right = "]"
            if right != brace:
                return False
    return stack.is_empty()
예제 #3
0
def is_braces_sequenct_correct(seq: str) -> bool:
    """
    Check correctness of braces sequence in statement
    >>> is_braces_sequenct_correct('() (())')
    True
    >>> is_braces_sequenct_correct('()[()]')
    True
    >>> is_braces_sequenct_correct(')')
    False
    >>> is_braces_sequenct_correct('[()')
    False
    >>> is_braces_sequenct_correct('[()])')
    False
    """
    correspondent = dict(zip('([{', ')]}'))
    for brace in seq:
        if brace in '([{':
            stack.push(brace)
            continue
        elif brace in ')]}':
            if stack.is_empty():
                return False
            left = stack.pop()
            if correspondent[left] != brace:
                return False

        return stack.is_empty()
예제 #4
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.")
예제 #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
예제 #6
0
def is_braces_sequence_correct(seq: str) -> bool:
    """
    Check correctness of braces sequence in statement
    >>> is_braces_sequence_correct("()(())")
    True
    >>> is_braces_sequence_correct("()[()]")
    True
    >>> is_braces_sequence_correct(")")
    False
    >>> is_braces_sequence_correct("[()")
    False
    >>> is_braces_sequence_correct("[(])")
    False
    """
    correspondent = dict(zip("([{", ")]}"))
    for brace in seq:
        if brace in "([{":
            stack.push(brace)
            continue
        elif brace in ")]}":
            if stack.is_empty():
                return False
            left = stack.pop()
            if correspondent[left] != brace:
                return False
        return stack.is_empty()
예제 #7
0
def is_braces_sequence_correct(s: str):
    """Проверяет является ли корректной скобочная последовательность,
       содержащая скобки вида: () [].

       >>> is_braces_sequence_correct("(([()]))[]")
       True
       >>> is_braces_sequence_correct("([)]")
       False
       >>> is_braces_sequence_correct("(")
       False
       >>> is_braces_sequence_correct("]")
       False
       
    """

    for brace in s:
        if brace not in "[]()":
            continue
        if brace in "[(":
            stack.push(brace)
        else:
            assert brace in ")]", "Ожидалась закрывющая скобка, получена: " + str(
                brace)
            if stack.is_empty():
                return False
            left = stack.pop()
            assert left in "([" "Ожидалась открывающая скобка, получена: " + str(
                brace)
            if left == "(":
                right = ")"
            else:
                right = "]"
            if brace != right:
                return False
    return stack.is_empty()
예제 #8
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
예제 #9
0
def ic(x: str):
    stack.clear()
    if x == '':
        return False
    for brace in x:
        if brace in '()':
            if brace in '(':
                stack.push(brace)
            else:
                if stack.is_empty():
                    return False
                left = stack.pop()
                if left == '(':
                    right = ')'
                if brace != right:
                    return False
    return stack.is_empty()
예제 #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
예제 #11
0
def remove(s):
    if stack.is_empty(s[0]):  # check is there are no states in the stack
        if s[3]:  # check if there is a reason to search deeper
            s[1] += 1  # increase search depth
            s[3] = False  # meanwhile there is no evidence to need to search deeper
            #print(s[1])         # print what level we finished searching
            return s[2]  # return the initial state
        else:
            return 0
    return stack.remove(s[0])  # if there are items in the stack ...
예제 #12
0
def stack_list(list, stack):
    '''
    (list,Stack)--> NoneType
    
    Adds each element of the list to the stack.
    Removes the top element from the stack. If the element is a non-list, it prints it. If the element is a list, it stores each of its elements on the stack.
    Continue the previous step until the stack is empty. Check for an empty stack, rather than causing an exception to be raised!
    '''
    for i in list:
        stack.push(i)

    while not stack.is_empty():
        first = stack.pop()
        if not isinstance(first, list):
            print(first)
        else:
            stack_list(first, stack)
예제 #13
0
import stack

string = "Mr Owl Ate My Metal Worm"
reversed_string = ""

#WITH STACK CLASS
stack = stack.Stack()
for char in string:
    stack.push(char)
while not stack.is_empty():
    reversed_string += stack.pop()
print(reversed_string)

string = "mroW lateM yM etA lwO rM"
reversed_string = ""

# WITHOUT STACK CLASS
for x in range(len(string)):
    reversed_string += string[-1]
    string = string[0:-1]

print(reversed_string)
예제 #14
0
    new_queue = q.create()

    for j in range(0, 3):

        val = i * 3 + j

        print("Enqueueing value : " + str(val))
        q.enqueue(new_queue, val)

    print("Pushing the queue containing those past 3 values onto the stack!\n")
    s.push(stack, new_queue)

print("\nPopping the stack!\n")

# empty the stack
while not s.is_empty(stack):

    print("Popping a queue!")
    current_popped_queue = s.pop(stack)

    while not q.is_empty(current_popped_queue):
        print("De-queued value from popped queue: " +
              str(q.dequeue(current_popped_queue)))

    print()  # Aesthetic

print("***********************************************")

##################################################################################
#
# A stack that pushes stacks!  ###################################################
예제 #15
0
def is_empty(s):
    return stack.is_empty(
        s[0]) and not s[3]  # stack is empty and try next level is false