pythonpython-2.7

pop() empty deque() in logic


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)

Solution

  • If you just want to pop() an empty deque without problems:

    from collections import deque
    
    d = deque()
    try:
        d.pop()
    except IndexError:
        pass  # do whatever you want in the case that there is nothing there
        return False # is this what you want?
    else:
        pass  # do whatever you want in the case that there is something there
    

    Just a warning in case you don't know: keep the amount of code inside any of try/except/else/finally as short and focused as possible. It's easy to end up with errors popping up inside error handlers and leading to surprises.

    If that's not what you need, please clarify what in your code is not working.