1

如果我有两个列表,每个列表的元素可以是两个可能值之一,并且两个列表除了一个值之外是相同的,我应该使用哪种方法来查找该值的索引?我将在 Python 中将其编码为背景信息

方法一:

1. represent both lists as a binary literals  
2. use XOR on the two binary literals to give a value "v" that is a power of 2  
3. finally, use math.log(v, 2) to get the index

或方法 B:

just iterate through both lists until a different element is found and 
get the index

或使用Python的另一种方式?

4

3 回答 3

2

将您的列表转换为另一种表示形式将涉及对它们进行迭代——不妨迭代以找出差异本身。

于 2013-07-06T06:08:42.797 回答
1

我不知道“最好”的方式,但你可以使用 python 来获取两组的差异,然后返回索引:

xs= [1, 2, 3, 4, 5]
ys = [1, 2, 3, 4, 6] # i.e. xs(5) and ys(6) are different


xs.index( list(set(xs) - set(ys))[0] )
ys.index( list(set(ys) - set(xs))[0] )
于 2013-07-06T06:15:32.750 回答
0

我认为第一种方法更好。您可以进一步修改它。

xor这两个列表并将结果存储在变量 sayk中。在 k 中找到一个设置位。现在xor该位设置为的所有元素1。你会得到一个号码。xor这个号码用k得到另一个。

找到列表中的两个数字以了解每个列表属于哪个列表以及数字的索引。

于 2013-07-06T06:11:53.033 回答