Python递归不会返回true或false

时间:2020-04-19 02:48:16

标签: python

我有一个问题要解决,那就是当它们以“ {[]}”这样紧挨着的方括号时,删除列表,先删除[],然后删除{}。如果列表为空,则返回true,否则返回false。下面是我的代码。我编写了一个递归,它不会返回True或False,但它打印的是我放在其前面的任何打印语句。我很困惑为什么有什么想法?

类解决方案:

def isValid(self, s: str) -> bool: 
    old_string = s
    print(old_string)
    test_str=[]
    for each_item in old_string:
        test_str.append(each_item)
        print(test_str)
    print (len(test_str))

    #recursion program
    def recursion_function(new_str):
        number=0
        time = 0
        did_something = 0
        if len(new_str) ==0:
            print ("yes")

        for each_string in new_str:
                print (each_string)
                if each_string == ")" and new_str[number-1]=="(":
                    new_str.pop()
                    new_str.pop()
                    print (new_str)
                    did_something = did_something+1
                elif each_string == "]" and new_str[number-1]=="[":
                    new_str.pop()
                    new_str.pop()
                    print (new_str)
                    did_something = did_something+1
                elif each_string == "}" and new_str[number+1]=="{":
                    new_str.pop()
                    new_str.pop()
                    print (new_str)
                    did_something = did_something +1
                number=number+1
        print (did_something)
        if did_something == 0 and len(new_str)!=0: 
            print (new_str)
            print ("hello, why did it get here")
            return False
        elif did_something == 0 and len(new_str)==0: 
            print (new_str)
            print ("did you get here?")
            return True
        else:
            print(new_str)
            print ("see you again this time")
            recursion_function(new_str)

    return recursion_function(test_str)

感谢任何指针。

0 个答案:

没有答案