-2

我正在解决一个问题,给定一个字符串,任何给定数量的 'a' 必须后跟两倍数量的 'b'。这必须是递归的。例如:

abb("aabbbbabb")
>>>True
abb("aabbabbb")
>>>False

我的直觉是做一个堆栈并将字母'a'压入堆栈,每次看到两个'b'时,从堆栈中弹出'a'。相反,我决定将 'b' 的位置和数量更新为变量。假设第一个字母总是“a”,应该出现的“b”的数量由 i + 2 表示。

到目前为止,我有这个花絮:

def aabb(string, postion=None, i=None):
    if position is None:
        position = 0
    if i is None:
        i = 0
    if position != len(string):
        if string[position] == "a":
            i = i +2
            position = position +1
            return aabb(string[position], position, i)
        if string[position] =="b" and i >0:
            i = i - 1
            position = position +1
            return aabb(string[position], position, i)
        if string[position] == "a" and i != 0:
            print "False"
        if string[position] == "b" and i == 0:
            print "False"
    else:
        print "True"

我遇到的问题如下:

if position is None:
UnboundLocalError: local variable 'position' referenced before assignment

如果它是可选参数,我不确定如何引用它?否则,我会以一种完全错误的方式来解决这个问题吗?谢谢。

4

1 回答 1

0

这是一个伪代码版本:

def abb(s):
    if s is empty:
        return True    # base case
    else:
        get number of leading "a"s                    # itertools.takewhile
        if number is 0:
            return False
        else:
            get twice that number of characters       # itertools.islice
            if they are all bs
                return abb(remainder of string)
于 2014-05-04T23:11:39.710 回答