我想生成一组随机生成的具有一定长度N的位串,但我想确保每个位串的和加起来等于一定的数字,比如$k$。如果不生成所有可能的位字符串并删除不等于k的位字符串,我该如何在Python中完成这项工作?
示例:假设我们想要生成10个不同的位串,每个位串的长度为96,但我们必须确保每个位串恰好有60个位串。我们如何才能做到这一点?
感谢
创建一个k
前导1,后跟N - k
零的列表,然后随机打乱该列表。使用bitstring
,其实现可能如下所示:
import random
import bitstring
def make_rnd_bitstring(N: int, k: int) -> bitstring.BitArray:
assert N >= k >= 0
bits = ['1'] * k + ['0'] * (N - k)
random.shuffle(bits)
return bitstring.BitArray(bin="".join(bits))
您可以根据随机生成的位字符串的需要多次调用此函数。
如果设置/取消设置适当位的整数就足够了,则此代码将执行问题所要求的操作:
(注意:更新以消除不必要的列表列表(
import random
bitstrings, toShuffle = [], [1]*60 + [0]*(96-60)
for _ in range(10):
bitstring, L = 0, random.sample(toShuffle, len(toShuffle))
for bit in L:
bitstring = (bitstring << 1) | bit
bitstrings.append(bitstring)
[print(f"{b:>100b}") for b in bitstrings]
样本输出:
111110101111011101010101111010010100011011100111101000010101001111110001111011111111011001010101
111101111011011111101111011011011101011010111110111100111101011000010001100101011000001001001111
111000101100101111111111100001011001111110010101011111110110101011001111100101101011111101100000
10101111011001010110111011111110101101001111100100000110101111100111111101111001110100001111010
101110100010101110111100101011101101001010100111011011010110100110110011011110110111111010110111
110101010111011101110111010011011010110110100110000110001001110101101101101101111111011110111001
1111101101100111011111100011000100101001111011010011000111110010011011001111101011111111010111
110111101111101011011011001010111110111111110011100100001110010101001100111101011010001100111110
11011011011101001001111111100011000011010111011101111110010101101110011001110101110011110110101
110001001010001111010111011001011011011011111011000010110001111011101111100111011011101110111101
更新#2:只是为了好玩。。。
这里有一句话可以做同样的事情:
import random
def generateBitStrings(nStrings, n, k):
return [(([bitstring:=0] + [(bitstring := (bitstring << 1) | bit) for bit in random.sample([1]*k + [0]*(n - k), n)])[-1]) for _ in range(nStrings)]
[print(f"{b:>100b}") for b in generateBitStrings(10, 96, 60)]