minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 2. Minimum bracket reversals #19

Open minimanimoh opened 3 years ago

minimanimoh commented 3 years ago
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
    """

    # TODO: Write function here
    if len(input_string) // 2 != 0:
        return -1

    open_bracket = Stack()
    close_bracket = Stack()

    for char in input_string:
        if char =='{':
            open_bracket.push(char)
        elif char == '}':
            close_bracket.push(char)

    if open_bracket.size() == close_bracket.size():
        return 0
    else:
        return abs(open_bracket.size - close_bracket.size) / 2
minimanimoh commented 3 years ago

Question: why this code doesn't work?

minimanimoh commented 3 years ago
def minimum_bracket_reversals(input_string):
    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()
                    countinue
            stack.push(bracket)

    ls = list()
    while not stack.is_empty():
        first = stack.pop()
        second = stack.pop()
        ls.append(first)
        ls.append(second)

        if first == '}' and second == '}':
            count += 1
        elif first == '{' and second == '}':
            count += 2
        elif first == '{' and second == '{':
            count += 1
    return count
minimanimoh commented 3 years ago

What does 'if top! = bracket' indicate?

  for bracket in input_String:
        if stack.is_empty():
            stack.push(bracket)
        else:
            top == stack.top()
            if top != bracket:
                if top == '{':
                    stack.pop()
                    countinue
            stack.push(bracket)