python - 一个数组或大小未知,全零和一找到以 XOR 函数 python 开头
问题描述
我们有一个问题,我们正在寻找如下元素的开头
input_arr = [ 0, 0, 0,1,1,1,1]
在这里,我有兴趣通过 XOR 函数找到第一次出现
def find_0_1_sep(self,arr):
i=0
result=0
while(arr[i]!=1):
result = 1 - result
result=arr[i+1]^result
if(result==1):
print(i)
i=i+1
如果输入从 0 开始并且在它之后出现 1,则上述函数运行良好。
我已尝试更改代码,以便如果数组以 1 或零任何数字开头,它将适用于两者
arr = [ 1, 1,1,0,0,0]
下面的代码
def find_0_1_sep_genric(self,arr):
i=0
result=arr[i] # initializing the first element 1 or 0
result = 1-result # invert the value
while(arr[i]!=result): # traversing the array untill other element
result = 1 - result # This step not sure ??
result=arr[i+1]^result # xor to find the result
if(result==1):
print(i)
i=i+1
在这里我使用第一个元素来查找数字
结果=arr[i]
但它不适用于这两种情况。请在这方面帮助我
解决方案
如果您的代码在数组以 a0
但不是 a开头时有效1
,您可以简单地明确检查:
if arr[0] == 1:
# The first element is a 1, set output accordingly
else:
# Your original code here
如果您不坚持使用 XOR,我建议使用带有显式调用的生成器表达式来解决整个问题next
,如下所示:
index = next(i for i, el in enumerate(input_arr) if el == 1)
您还可以在s(和s)上使用内置index
方法:list
tuple
index = input_arr.index(1)
推荐阅读
- java - 在arraylist中生成两次字符串元素
- string - golang中的100阶乘
- java - Hibernate 5.2 在我的表 postgres 上级联删除
- html - 在打字稿中将字符串解析为 HTML
- angular - 在 Angular 6 模板中使用之前解析 for key 的 json 内容
- android - Android Google Vision API 问题
- python - 将视频加载到帧中时的内存问题
- php - 如何摆脱在 fpdf 中找不到的“dbObject”?
- c# - 如何从数据网格突出显示的行中删除缩进?
- python - 正则表达式与组引用的最后一个匹配项到底是什么(在 Python 正则表达式中)?