[Python] pop() empty deque() in logic

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    I want to be able to validate parenthesis so they enclose and ignore any type of characters. As long as there is the valid use of enclosure of strings with parenthesis then True else `False.

    I am still new to python so I'm not sure how to properly create an if statement for this certain condition. I am trying to create an fi statement such that when I .pop() an empty deque() I will be able to return False instead of receiving the error message:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IndexError: pop from an empty deque


    Perhaps there is another better method around solving this problem. If so I would be glad to see how someone else would solve it

    For example:

    a = 'sdf(sadf(sdf)sdf)sdfsd0sdf)sdf(sdf0)' # false
    b = 'dsf))))(((((dsfsdf' # false
    c = '()()()()' # true
    d = '((((asd(asd)asd)()()asd))' # true


    my code:

    # any letter is ignored
    # jsut make sure that the parenthesis are equal

    from collections import *

    def str_valid(stringy):
    param_stack = deque()
    for n in stringy:
    if n ==')':
    param_stack.pop()
    if n == '(':
    param_stack.append('(')
    if param_stack == []:
    return True
    else:
    return False

    a = 'sdf(sadf(sdf)sdf)sdfsd0sdf)sdf(sdf0)' # false
    b = 'dsf))))(((((dsfsdf' # false
    c = '()()()()' # true
    d = '((((asd(asd)asd)()()asd))' # true

    print str_valid(a)

    print str_valid(b)

    print str_valid(c)

    print str_valid(d)

    Continue reading...

Compartilhe esta Página