我编写了一个函数来生成从给定列表开始的s
二进制字符串(所有二进制字符串都以一个s
项目结尾):
def binary_strings(s):
yield from s
while True:
s = [b + x for x in s for b in "01"]
yield from s
从输出中可以看到它的工作原理:
>>> for i in binary_strings(["10", "01"]): print(i)
10
01
010
110
001
101
0010
1010
0110
1110
0001
1001
0101
1101
00010
10010
01010
11010
00110
10110
01110
11110
00001
10001
01001
11001
00101
10101
01101
11101
000010
100010
... # Output is infinite so I must truncate it.
现在我修改s
并使用生成器表达式而不是列表:
def binary_strings(s):
yield from s
while True:
s = (b + x for x in s for b in "01")
yield from s
现在执行在用尽 3 长度的可能性后突然停止:
>>> for i in binary_strings(["10","01"]): print(i)
10
01
010
110
001
101
# Output is not truncated, the function freezes at this points
# and yield no more output
我希望第二个版本和第一个版本一样好,因为我从不使用列表方法s
,我只是迭代它,为什么第二个版本不工作?