简体   繁体   中英

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. 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. Tried list methods for this, but I failed to work it properly at all range(1<=n<=30). Any ideas?

PS I have to do it without using itertools. Avoiding itertools is a part of the task.

Just add two next if-s into the loop.

These if-s literally mean next things:

  1. Don't prepend next 0 if your current number already starts with 0, otherwise you'll get two or more adjacent 0s in the beginning, which is against the task.
  2. Don't prepend next 1 if your current number already starts with 11, otherwise you'll get three or more adjacent 1s in the beginning, which is also against the task.

Try it online!

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:

0101
0110
1010
1011
1101

output for input 5:

01010
01011
01101
10101
10110
11010
11011

@Arty has the answer as asked. 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:

Bits? 8
01010101
01010110
01011010
01011011
01101010
01101011
01101101
10101010
10101011
10101101
10110101
10110110
11010101
11010110
11011010
11011011

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM