代码之家  ›  专栏  ›  技术社区  ›  Maxxx

在一个位串的前面加0,在n次迭代的位串的末尾加1

  •  0
  • Maxxx  · 技术社区  · 8 年前

    目前,我有一个位串,由

    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,希望能得到一些帮助。

    4 回复  |  直到 8 年前
        1
  •  3
  •   Sheldore    8 年前

    好的,问题在下面的总结中:

    你 是 做以下总结

    full_b_tree += inc_zero
    

    这意味着什么 full_b_tree = full_b_tree + inc_zero 这将增加 0 到最后。

    你 应该 做

    full_b_tree = inc_zero + full_b_tree
    

    它将附加 零 前面,这就是你想要的。我也换了 range(n) 通过 range(n+1) 因为 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
    
        2
  •  1
  •   jar    8 年前

    这应该有帮助-

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

    输出-

    011
    00111
    0001111
    
        3
  •  1
  •   Wazaki    8 年前

    试试这个代码:

    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)
    
        4
  •  0
  •   laros    8 年前

    尝试以下代码:

    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