[英]Generate binary sequence without 2 zeros OR 3 1's in the row
My task for homework is to generate binary sequence (sample input in range 1<=n<=30) without two zeros or three ones together.我的作业任务是生成二进制序列(样本输入在 1<=n<=30 范围内),没有两个零或三个一起。 I made simple binary generator, which works as shown below.
我制作了简单的二进制生成器,其工作原理如下所示。 I need to modify it to obtain this output(and according outputs also):
我需要修改它以获得此输出(并且还根据输出):
n = int(input())
def gen(n):
if n == 0:
return ['']
l = gen(n-1)
start0 = []
start1 = []
for seq in l:
start0.append('0' + seq)
start1.append('1' + seq)
return start0 + start1
l1 = gen(n)
for elem in l1:
print(elem)
Sample Input
4
Sample Output(which I have right now)
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Sample Output I need to obtain:
0101
0110
1010
1011
1101
To put in simple, sequences like 1000, 1110, 1100, 0011, 0111 and so on(without two zeros OR three 1s in a row) should be excluded.简而言之,应该排除 1000、1110、1100、0011、0111 等序列(连续没有两个零或三个 1)。 Tried list methods for this, but I failed to work it properly at all range(1<=n<=30).
为此尝试了列表方法,但我未能在所有范围内正常工作(1<=n<=30)。 Any ideas?
有任何想法吗?
PS I have to do it without using itertools. PS 我必须在不使用 itertools 的情况下完成它。 Avoiding itertools is a part of the task.
避免 itertools 是任务的一部分。
Just add two next if-s into the loop.只需在循环中添加两个下一个 if-s。
These if-s literally mean next things:这些 if-s 的字面意思是接下来的事情:
n = int(input())
def gen(n):
if n == 0:
return ['']
l = gen(n-1)
start0 = []
start1 = []
for seq in l:
if not seq.startswith('0'):
start0.append('0' + seq)
if not seq.startswith('11'):
start1.append('1' + seq)
return start0 + start1
l1 = gen(n)
for elem in l1:
print(elem)
output for input 4:输入 4 为 output:
0101
0110
1010
1011
1101
output for input 5:输入 5 为 output:
01010
01011
01101
10101
10110
11010
11011
@Arty has the answer as asked. @Arty 有所问的答案。 Here's a generator example for another solution:
这是另一个解决方案的生成器示例:
def gen(n):
if n == 1:
yield from '01'
else:
for seq in gen(n-1):
if not seq.endswith('0'):
yield seq + '0'
if not seq.endswith('11'):
yield seq + '1'
n = int(input('Bits? '))
for elem in gen(n):
print(elem)
Output: Output:
Bits? 8
01010101
01010110
01011010
01011011
01101010
01101011
01101101
10101010
10101011
10101101
10110101
10110110
11010101
11010110
11011010
11011011
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.