我试图从函数返回一个字符串列表,该函数计算没有连续 0 的所有可能排列。
为此,我正在运行一个有效的递归函数,但我需要创建一个包含结果的列表。
# Function to print all n–digit binary strings without any consecutive 0's
def countStrings(n, out="", last_digit=0):
# if the number becomes n–digit, print it
if n == 0:
print(out)
return
# append 0 to the result and recur with one less digit
countStrings(n - 1, out + '1', 0)
# append 1 to the result and recur with one less digit
# only if the last digit is 0
if last_digit == 0:
countStrings(n - 1, out + '0', 1)
当我运行它时,例如:a = countStrings(3)
,它打印所有可能性,但变量“a”返回为“None”:
results:
111
110
101
011
010
type(a): Nonetype
我尝试在某些地方插入附加,但没有结果
我不知道我错过了什么
这是您正在寻找的吗?
# Function to print all n–digit binary strings without any consecutive 0's
def countStrings(n, out="", last_digit=0, acc=[]):
# if the number becomes n–digit, print it
if n == 0:
print(out)
acc.append(out)
return acc
# append 0 to the result and recur with one less digit
countStrings(n - 1, out + '1', 0, acc)
# append 1 to the result and recur with one less digit
# only if the last digit is 0
if last_digit == 0:
countStrings(n - 1, out + '0', 1, acc)
return acc
acc = countStrings(3)
print('acc', acc)
Output:
111
110
101
011
010
('acc', ['111', '110', '101', '011', '010'])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)