首页 > 解决方案 > 一个数组或大小未知,全零和一找到以 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]

但它不适用于这两种情况。请在这方面帮助我

标签: pythonpython-3.xalgorithm

解决方案


如果您的代码在数组以 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方法:listtuple

index = input_arr.index(1)

推荐阅读