我试图从函数返回一个字符串列表,该函数计算所有可能的排列,而不连续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”:
结果:
111
110
101
011
010
type(a): Nonetype
我试图在某些地方插入一个附加,但没有结果
我不知道我错过了什么
如果不想使用
return
,可以创建global
参数,并在函数完成后调用它以执行:调用
print(res)
将为您提供:这就是你要找的吗
输出:
解决方案A
我建议将该计划的关注点分为多个功能:
现在我们可以写
pairwise
,它在一个iterable上成对迭代-现在很容易将
solution
实现为所有binaries
大小n
的组合,其中pairwise
对任何特定二进制的分析不包含两个相邻的零-如果所有人都只需要一个解决方案的计数,我们可以将
count_solutions
写为solutions
-让我们来看一个更大的例子,
n
=8-解决方案B
我一直在思考这个问题,我不喜欢上面的解决方案中的数字在比较之前如何转换成字符串
首先我们写
bitwise
-然后
pairwise
-最后
solution
-和
n
=8-建议阅读
如果您从未在Python中看到过
for..else
循环,请read the docs了解这个奇妙的构造相关问题 更多 >
编程相关推荐