+ -
当前位置:首页 → 问答吧 → new pythoner

new pythoner

时间:2011-07-20

来源:互联网

Check expression for correct brackets order. You can use all brackets types {},[],()
Input data: Brackets expression.
Output data: Sentence with solution is expression correct or not.
Example: checkio('({(asda)sd[s]d})') == True
  checkio('({[a]((s)})') == False
Python code

def checkio(Expression):
    'Check expression for correct brackets order'
    pa = '([{'
    pb = ')]}'
    t = []
    for a in Expression:
        if pa.find(a):
            t.append(a)
        if pb.find(a):
            if (len(t)!=0) and (pb.index(a)==pa.index(t[-1])):
                t.pop()
            else:
                return False
    if len(t) == 0:
        return True
    else:
        return False
            

if __name__ == '__main__':
    assert checkio('({(asda)sd[s]d})') == True, 'First'
    assert checkio('({[a]((s)})') == False, 'Second'
    print 'All ok'


debuger了半天没查出bug,望高手指点下~

作者: pangguanzhe1314   发布时间: 2011-07-20

find失败返回-1,所以判断语句写法应该是if pa.find(a) != -1:或者 if a in pa:

作者: angel_su   发布时间: 2011-07-20