本文整理汇总了Python中bitstring.BitArray.set方法的典型用法代码示例。如果您正苦于以下问题:Python BitArray.set方法的具体用法?Python BitArray.set怎么用?Python BitArray.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bitstring.BitArray
的用法示例。
在下文中一共展示了BitArray.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prime_sieve
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def prime_sieve(top=10005):
b = BitArray(top) # bitstring of ’0’ bits
for i in range(2, top):
if not b[i]:
yield i
# i is prime, so set all its multiples to ’1’.
b.set(True, range(i * i, top, i))
示例2: get_bits
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def get_bits(length, mode=-1):
"""生成指定长度的位串.
length -- 位串长度
mode -- 0 返回全0
1 返回全1
-1 返回随机位串
"""
# 生成指定长度的位串的最大值
bits = BitArray(length)
bits.set(1)
bin_str = ''
if mode == 0:
bits.set(0)
bin_str = '0b' + bits.bin
elif mode == 1:
bin_str = '0b' + bits.bin
else:
# print 'all_1_bit:bin:' + bits.bin
# print 'all_1_bit:uint:' + bits.uint.__str__()
# 生成随机数,0到最大值
random_num = random.randint(0, bits.uint)
# print 'random_num:' + random_num.__str__()
bin_str = bin(random_num)
# print 'created bit:' + bin_str[2:]
return bin_str
示例3: init_prime_bitarray
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def init_prime_bitarray(maxnum):
"""Initialize a bitarray with the supplied length, and find primes with
a prime sieve."""
global primes_ba
maxnum += 1
primes_ba = BitArray(maxnum)
primes_ba.set(1)
primes_ba[0], primes_ba[1] = [0, 0]
for i in [2] + list(range(3, maxnum, 2)):
if primes_ba[i]:
for j in range(i + i, maxnum, i):
primes_ba[j] = 0
示例4: __init__
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
class BloomFilter:
def __init__(self, size, hash_count):
self.array = BitArray(length=size)
self.hash_list = [md5() in range(hash_count)]
def load(self, items):
for item in items:
self.array.set(1, [h.real for h in self.hash_list])
def __contains__(self, item):
a = [h.real for h in self.hash_list]
return self.array[a]
示例5: answer
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def answer():
ba = BitArray(2000000)
ba.set(1)
for i in range(4, 2000000, 2):
ba[i] = 0
for i in range(3, 2000000, 2):
if ba[i]:
for j in range(i + i, 2000000, i):
ba[j] = 0
return sum(i for i in range(3, 2000000, 2) if ba[i]) + 2
示例6: evaluate
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def evaluate(target):
good = BitArray(len(target)) # all characters that are part of a meaningful word
bestLength = 0 # length of the longest word
bestPattern = BitArray(len(target)) # characters that form the longest word
for i in range(len(target)):
match = t.longest_prefix(key=target[i:], default="")
if len(match)>0:
temp = BitArray(len(target))
temp.set(1, range(i, i+len(match))) # set mathcing character positions to 1
good.set(1, range(i, i+len(match))) # set mathcing character positions to 1
if len(match)>bestLength:
bestLength = len(match)
bestPattern = temp
return bestPattern, good
示例7: get_bitstring
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def get_bitstring(descriptors):
d = {}
result = []
for i in descriptors.columns:
a = md5(i.encode()).digest()
xx = BitArray(a)
l = []
for j in range(ACTIVE_BITS):
s = xx[j*bs_slice:(j+1)*bs_slice].uint
l.append(s)
d[i] = l
for _, i in descriptors.iterrows():
hfp = BitArray(2 ** bs_slice)
for k, v in i.items():
if v:
hfp.set(True, d[k])
result.append(hfp)
return result
示例8: analyze
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def analyze(self):
numbers = BitArray(2**32)
numbers.set(False, xrange(0, 2**32))
f = open('integers', 'rb')
for line in f:
data = ''
if len(line) < 2:
data, = struct.unpack('B', line[:1])
elif len(line) < 4:
data, = struct.unpack('H', line[:2])
else:
data, = struct.unpack('I', line[:4])
numbers[data] = True
f.close()
self.missing = []
for i in xrange(2**32):
if not numbers[i]:
self.missing.append(numbers[i])
示例9: BitArray
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
MAXN = 1000000005
isHappy = BitArray(MAXN)
unHappy = BitArray(MAXN)
isHappy[1] = True
for case in range(1, 1 + int(input())):
try:
n = int(input())
except:
break
path = set()
curr = n
flag = True
while not isHappy[curr] and not unHappy[curr]:
if isHappy[curr]:
break
if unHappy[curr]:
flag = False
break
path.add(curr)
curr = sum(map(lambda x: x ** 2, map(int, str(curr))))
if curr in path:
flag = False
break
if flag:
isHappy.set(True, path)
print 'Case #%d: %d is a Happy number.' % (case, n)
else:
unHappy.set(True, path)
print 'Case #%d: %d is an Unhappy number.' % (case, n)
示例10: set
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
import sys
import bisect
from bitstring import BitArray
top = 100000
primes = set()
digitPrimes = []
b = BitArray(top) # bitstring of ’0’ bits
for i in range(2, top):
if not b[i]:
primes.add(i)
if sum(map(int, str(i))) in primes:
digitPrimes.append(i)
# i is prime, so set all its multiples to ’1’.
b.set(True, range(i * i, top, i))
sys.stdin = open('input.txt')
cases = int(input())
for x in range(cases):
t1, t2 = map(int, raw_input().split())
print bisect.bisect(digitPrimes, t2) - bisect.bisect(digitPrimes, t1)
示例11: int
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
modValue = 1000000
#read each line, split to remove extra chars.
for line in file.readlines():
data = line.split()
for line in data:
#hash with the md5 hashfunction.
hash = hashlib.md5(line.lower().encode('utf-8')).digest()
#extract parts of the hash and convert to integer inside array index span
h1 = int(hash[0:3].encode("hex"),16)%modValue
h2 = int(hash[4:7].encode("hex"),16)%modValue
h3 = int(hash[8:11].encode("hex"),16)%modValue
h4 = int(hash[12:15].encode("hex"),16)%modValue
#set the bits in the array. use the set function for speed.
hashTable.set(True,h1)
hashTable.set(True,h2)
hashTable.set(True,h3)
hashTable.set(True,h4)
file.close()
#open file as binary file and write to it.
with open('data', 'wb') as outfile:
hashTable.tofile(outfile)
#print execution time. ~20 seconds on my system
end = time.time()
print(end-start)
示例12: sample_sequences
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def sample_sequences(positions, buildname, basedir, options):
"""
"""
rpt_err = options.rpt_err
gc_err = options.gc_err
max_trys = options.max_trys
norpt = options.norpt
nogc = options.nogc
chrnames = sorted(set(map(lambda p: p[0], positions)))
profiles = make_profile(positions, buildname, basedir)
excluded = []
if options.skipfile:
excluded = read_bed_file(options.skipfile, chr)
f = open(options.output,"w")
for chrom in chrnames:
print chrom
idxf_na = os.path.join(basedir, '.'.join([buildname, chrom, 'na', 'out']))
idxf_gc = os.path.join(basedir, '.'.join([buildname, chrom, 'gc', 'out']))
idxf_rpt = os.path.join(basedir, '.'.join([buildname, chrom, 'rpt', 'out']))
bits_gc = Bits(filename=idxf_gc)
bits_rpt = Bits(filename=idxf_rpt)
#this bit array is used to mark positions that are excluded from sampling
#this will be updated as we sample more sequences in order to prevent sampled sequences from overlapping
bits_na = BitArray(filename=idxf_na)
#mark excluded regions
for pos in excluded:
if pos[0] != chrom:
continue
bits_na.set(True, range(pos[1], pos[2]))
npos+=1
npos = 0
#mark positive regions
for pos in positions:
if pos[0] != chrom:
continue
bits_na.set(True, range(pos[1], pos[2]))
npos+=1
if options.count == 0:
count = options.fold*npos
sampled_cnt = 0
while sampled_cnt < count:
sampled_prof = random.choice(profiles)
sampled_len = sampled_prof[1]
sampled_gc = sampled_prof[2]
sampled_rpt = sampled_prof[3]
rpt_err_allowed = int(rpt_err*sampled_len)
gc_err_allowed = int(gc_err*sampled_len)
trys = 0
while trys < max_trys:
trys += 1
pos = random.randint(1, bits_na.length - sampled_len)
pos_e = pos+sampled_len
#if bits_na.any(True, range(pos, pos_e)):
# continue
if bits_na[pos:pos_e].count(True) > 0:
continue
if not norpt:
pos_rpt = bits_rpt[pos:pos_e].count(True)
if abs(sampled_rpt - pos_rpt) > rpt_err_allowed:
continue
if not nogc:
pos_gc = bits_gc[pos:pos_e].count(True)
if abs(sampled_gc - pos_gc) > gc_err_allowed:
continue
#accept the sampled position
#mark the sampled regions
bits_na.set(True, range(pos, pos_e))
f.write('\t'.join([chrom, str(pos), str(pos_e)]) + '\n')
sampled_cnt += 1
print trys, chrom, pos, pos_e, sampled_len, pos_rpt, sampled_rpt, pos_gc, sampled_gc
break
else:
print "maximum trys reached"
f.close()
示例13: hash
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
return hash(seqid) & 0x7FFFFFFF
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Pair fastq files, writing all the pairs to separate files and the unmapped reads to separate files")
parser.add_argument('-l', help='Pair #1 reads file', required=True)
parser.add_argument('-r', help='Pair #2 reads file', required=True)
parser.add_argument('-n', help='Number of sequences in the file. This is used to determine the size of the bloom filter. The default is 500,000,000', type=int, default=500000000)
args = parser.parse_args()
# define the bloom filter to be of size N. This should be at least 1.3x the number of reads.
sys.stderr.write("Initializing the bloom filter\n")
lbf = BitArray(args.n)
lbf.set(0)
sys.stderr.write("Completed initializing the bloom filter\n")
counter = 0
# read and populate the bloom filter
if args.l.endswith('.gz'):
qin = gzip.open(args.l, 'rb')
else:
qin = open(args.l, 'r')
while True:
l = qin.readline()
if not l:
break
counter += 1
示例14: layer2
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def layer2(Message):
global L3_SC
global L2Frame
scramble_table = BitArray('0b10101111101010101000000101001010111100101110111000000111001110100100111101011101010001001000011001110000101111011011001101000011101111000011111111100000111101111100010111001100100000100101001110110100011110011111001101100010101001000111000110110101011100010011000100010000')
crc = Crc()
if L3_SC == 0:
L2Frame = []
print("Create Frame: " + str(FrameCnt) + "...this will take a while")
#print(L3_SC)
if L3_SC < 190:
if L3_SC < 60: #BIC 1
L2_BIC = BitArray('0xA791', length = 16)
else:
if L3_SC >= 60 and L3_SC < 130:
L2_BIC = BitArray('0x74A6', length = 16)
else:
L2_BIC = BitArray('0x135E', length = 16)
L2_CRC = crc.crc14(Message)
L2_MSGCRC = Message + L2_CRC
L2_Parity = crc.crc82(L2_MSGCRC)
L2Block = L2_BIC + Message + L2_CRC + L2_Parity
#print(L3_SC)
L2Frame.insert(L3_SC,L2Block)
#print(str(L2Block))
#print(str(L2Frame[L3_SC]))
if L3_SC == 189:
k = 0
while k < 82:
L2Frame.append(BitArray('0xc875', length = 16))
L2Frame[190+k].append(BitArray(length = 272))
k+=1
i = 0
j = 0
while i < 272:
VerticalBlock = BitArray(length=190)
while j < 190:
Block = L2Frame[j]
VerticalBlock.set(Block[i+16],j)
j+=1
j = 0
VerticalCRC = crc.crc82(VerticalBlock)
k = 0
while k < 82:
L2Frame[190+k].set(VerticalCRC[k],i+16)
k+=1
i+=1
l = 0
####SCRAMBLE HERE
i = 0
while i < 272:
Scramble = L2Frame[i][16:288] ^ scramble_table
L2Frame[i] = L2Frame[i][0:16]+Scramble
i+=1
#################
fh = open('frame_output','a')
msg = ''
while l < len(L2Frame):
#print(str(L2Frame[l]))
m = 0
while m < len(L2Frame[l]):
if (m%8 == 0):
msg += chr(L2Frame[l][m:m+8].uint)
m+=1
l+=1
fh.write(msg)
fh.close()
示例15: layer3
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import set [as 别名]
def layer3(Message, type, ServiceType = BitArray('0x0110',length=4)):
global L3_SC
global L3_SUP
crc = Crc()
if '0xA' == type: ## Long Message
#print(str(Message))
L3_Fragment = (len(Message)/160)+1
data = BitArray(length = L3_Fragment*160)
data.set(0)
for pos in range(len(Message)):
data[pos] = Message[pos] #fill data
#print(str(data))
#print(str(L3_Fragment) + ' ' + str(len(data)))
i = 0
while i < L3_Fragment:
L3Hdr_LCh = BitArray('0b1010', length = 4) # Long Message
L3Hdr_DI= BitArray('0b0', length = 1) # No Decode Indicator
if i < L3_Fragment -1:
L3Hdr_LF = BitArray('0b0', length = 1) # Not the End
else:
L3Hdr_LF = BitArray('0b1', length = 1) # the End
L3Hdr_SC = BitArray(uint = L3_SC%16, length=4) # Counter
L3Hdr_LCh = L3Hdr_LCh[::-1] #Flip LSB/MSB
L3Hdr_SC = L3Hdr_SC[::-1] #Flip LSB/MSB
L3Hdr_PreCRC = L3Hdr_LCh + L3Hdr_DI + L3Hdr_LF + L3Hdr_SC
L3Hdr_CRC = crc.crc6(L3Hdr_PreCRC)
L3Hdr = L3Hdr_LCh + L3Hdr_DI + L3Hdr_LF + L3Hdr_SC +L3Hdr_CRC
dataFragment = data[0+(160*i):160+(160*i)]
# Marshalling of l3_body
# TODO beautify and pack into function
# 2 byte L3 Header, 20 Byte L3 data
#data_ = BitArray(length=160)
for pos in range(len(dataFragment)):
if not (pos % 8):
word = dataFragment[pos:pos+8]
word = word[::-1]
dataFragment[pos:pos+8] = word
#print(str(dataFragment))
L3Packet = L3Hdr + dataFragment
i+=1
#print(str(L3Packet))
layer2(L3Packet)
L3_SC+=1
if '0xB' == type: ## Block Message
L3Hdr_LCh = BitArray('0b1011', length = 4) # Bloc Message
L3Hdr_DI= BitArray('0b0', length = 1) # No Decode Indicator
L3Hdr_SCh = BitArray('0b100', length = 3) # Not the End
L3Hdr_LCh = L3Hdr_LCh[::-1] #Flip LSB/MSB
L3Hdr_SCh = L3Hdr_SCh[::-1] #Flip LSB/MSB
L3Hdr = L3Hdr_LCh + L3Hdr_DI + L3Hdr_SCh
data = BitArray(length = 168)
data.set(0)
for pos in range(len(Message)):
data[pos] = Message[pos] #fill data
dataFragment = data[0:168]
# Marshalling of l3_body
# TODO beautify and pack into function
# 2 byte L3 Header, 20 Byte L3 data
#data_ = BitArray(length=160)
for pos in range(len(dataFragment)):
if not (pos % 8):
word = dataFragment[pos:pos+8]
word = word[::-1]
dataFragment[pos:pos+8] = word
L3Packet = L3Hdr + dataFragment
#print(str(L3Packet))
layer2(L3Packet)
L3_SC+=1
if '0x8' == type: ## Service Message
L3_Fragment = (len(Message)/152)+1
data = BitArray(length = L3_Fragment*152)
data.set(0)
for pos in range(len(Message)):
data[pos] = Message[pos] #fill data
#print(str(data))
#print(str(L3_Fragment) + ' ' + str(len(data)))
i = 0
while i < L3_Fragment:
L3Hdr_LCh = BitArray('0b1000', length = 4) # Service Message
L3Hdr_LCh = L3Hdr_LCh[::-1]
L3Hdr_RFA= BitArray('0b0', length = 1) # No Future
if i < L3_Fragment -1:
L3Hdr_LF = BitArray('0b0', length = 1) # Not the End
else:
L3Hdr_LF = BitArray('0b1', length = 1) # the End
L3Hdr_DUP = BitArray(uint = L3_SUP%4, length=2) # Counter
L3Hdr_CID = BitArray('0xD', length=4) # Germany
L3Hdr_CID = L3Hdr_CID[::-1]
L3Hdr_Type = ServiceType
L3Hdr_Type = L3Hdr_Type[::-1]
L3Hdr_NID = BitArray('0xC', length=4) #MVG
L3Hdr_NID = L3Hdr_NID[::-1]
L3Hdr_BLN = BitArray(uint=(L3_Fragment-1)%16, length=4) #Blocknumber
L3Hdr_BLN = L3Hdr_BLN[::-1]
L3Hdr = L3Hdr_LCh + L3Hdr_RFA + L3Hdr_LF + L3Hdr_DUP + L3Hdr_CID + L3Hdr_Type + L3Hdr_NID + L3Hdr_BLN
#.........这里部分代码省略.........