在位串前面加0,在位串末尾加1,进行N次迭代

adding 0 at the front of a bit string and 1 at the end of the bit string for N iteration

目前,我有一个由

表示的位串
1 #for n = 0

并且对于n次迭代,我想在位串的前面加一个0,在末尾加一个1

对于 n = 1:

011  #added 0 and 1

对于 n = 2:

00111  #added 0 and 1 from previous bit string

对于 n = 3:

0001111  #added 0 and 1 from previous bit string

。 .

我试过了:

bit_str = ""
for i in range(n):
    if i == 0: 
        full_b_tree = "1"
        print(full_b_tree)
    else:
        inc_one = "1"
        bit_str += inc_one
        inc_zero = "0"
        full_b_tree += inc_zero
        print(full_b_tree)

但是对于 n = 3,我得到

1
011
01110
0101110

这是我第一次使用位串,因为我不熟悉在前面添加 0 和在末尾添加 1,希望得到一些帮助。

好的,问题出在总结如下:

正在进行以下求和

full_b_tree += inc_zero

表示 full_b_tree = full_b_tree + inc_zero 会将 0 添加到末尾。

应该

full_b_tree = inc_zero + full_b_tree

这会将 0 附加到前面,这就是您想要的。我还用 range(n+1) 替换了 range(n) 因为 range(3) 只会上升到 2.

n = 3
bit_str = ""
for i in range(n+1): # n replaced by n+1
    if i == 0: 
        full_b_tree = "1"
        print(full_b_tree)
    else:
        inc_one = "1"
        full_b_tree += inc_one
        inc_zero = "0"
        full_b_tree = inc_zero + full_b_tree # The summation corrected
        print(full_b_tree)

1
011
00111
0001111

这应该有帮助-

N=3
bit_string = '1'
for i in range(N):
    bit_string = '0' + bit_string + '1'
    print(bit_string)

输出-

011
00111
0001111

试试这个代码:

bit_str = ""
for i in range(n+1):
    if i == 0: 
        full_b_tree = "1"
        print(full_b_tree)
    else:
        inc_one = "1"
        full_b_tree = full_b_tree+inc_one
        inc_zero = "0"
        full_b_tree = inc_zero + full_b_tree
        print(full_b_tree)

试试下面的代码:

def genBitStr(n):
    """ n: number of iteration"""
    for i in range(n):
        yield '1'.join(map(lambda e:e*i,['0', '1']))

for i, bit_str in enumerate(genBitStr(10)):
    print(i, bit_str)

0 1 1 011 2 00111 3 0001111 4 000011111 5 00000111111 6 0000001111111 7 000000011111111 8 00000000111111111 9 0000000001111111111