问题描述
我有一个整数列表,例如i=[1,7,3,1,5]
,我首先将其转换为长度为L
的相应二进制表示形式的列表,例如b=["001","111","011","001","101"]
与L=3
。
现在,我要计算二进制表示中的L
个位置中有一个1
和一个零0
。在我的示例中,结果将为return=2
,因为这些条目的第三(最后)位置始终有1
。我很乐意提出任何意见。我认为,理想情况下,我应该同时执行许多Xor操作。但是,我不确定如何有效地做到这一点。
编辑:感谢您的回答!!我必须检查哪一个最快。
解决方法
一种观察结果是,如果您对所有数字进行“与”运算,并且对所有数字进行“或”运算,那么满足条件的那两个结果的异或将为1。
所以:
from functools import reduce
from operator import and_,or_
def count_mixed_bits(lst):
xor = reduce(and_,lst) ^ reduce(or_,lst)
return bin(xor).count("1")
count_mixed_bits([1,7,3,1,5]) # 2
,
这是一个解决方案,我怀疑它不是很有效,但是很容易理解。
我遍历数字并找到唯一的集合,然后计算集合长度为2的条目数:
# create a binary list of 3 elements from input list of integers
i=[1,5]
b=['{0:03b}'.format(x) for x in i]
# loop over the digit position (1,2,3)
cnt=[]
for pos in range(3):
cnt.append(len(set([c[pos] for c in b])))
# cnt now contains a list of either 2(=both 1 and 0 present) or 1 (unique)
# so now we count the number of entries with "2"
result=cnt.count(2)
print (result)
answer:
2
,
首先,您的问题用numpy标记,但您的数组不是numpy数组。 这是使用numpy的解决方案:
import numpy as np
def has_zeroes_and_ones_at_index(arr,index_from_right):
shifted_arr = np.right_shift(arr,index_from_right)
has_one_at_index = shifted_arr % 2 == 1
return(True in has_one_at_index and False in has_one_at_index)
arr = np.array([1,5])
res= has_zeroes_and_ones_at_index(arr,1)
print(res)
由于数字存储在二进制中,因此我们可以使用移位将数字的所有位向右移动,然后查看最后一位。在此之前,我们不必将其转换为二进制格式。 5(101)右移一-> 2(010)
然后我们创建一个掩码以查看哪些数字的最后一位为1,并在掩码中至少有一个True元素和一个false元素时返回True。
,有一个numpy.binary_repr
方法接受长度。不幸的是,它不能处理数组。但是您可以改用np.unravel_index
的功能:
def check(arr,lenght):
positions = np.array(np.unravel_index(i,(2,)*lenght))
return positions,np.sum(np.sum(positions,axis=1) != len(arr))
>>> positions,output = check(i,3)
>>> print(positions)
>>> print(output)
[[0 1 0 0 1]
[0 1 1 0 0]
[1 1 1 1 1]]
2
,
您可以使用python bitwise operators来完成此任务。
def find(aList,nn):
return sum(
filter(
lambda bb: bb > 0,(
( 1 <= (sum( (aa & 1<<kk) > 0 for aa in aList)) < len(aList) )
for kk in range(nn)
)
)
)
>>> find([1,5],3)
2
>>> find([],3)
0
>>> find([7],3)
0
>>> find([7,1],3)
2
>>> find([7,7],3)
2