对于N次迭代,在位字符串的前面加0,在位字符串的末尾加1

时间:2018-10-10 09:58:53

标签: python bit

当前,我有一个由

表示的位串
1 #for n = 0

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

对于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 个答案:

答案 0 :(得分:2)

好吧,问题出在以下方面:

正在进行以下求和

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)代替了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

答案 1 :(得分:1)

这应该有帮助-

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

输出-

011
00111
0001111

答案 2 :(得分:1)

尝试以下代码:

JObject jObject = JObject.Parse(json);

var result = jObject["Configurations"]["Tr984"]["Operations"].Children().Children().ToList();

foreach (JToken token in result)
{
    JObject jObject1 = token.ToObject<JObject>();

    foreach (JProperty property in jObject1.Properties())
    {
        //comboBox1.Items.Add(property.Value);  
        Console.WriteLine(property.Name + ": " + property.Value);
    }
}

Console.ReadLine();

答案 3 :(得分:0)

尝试以下代码:

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