[英]Python: fail to swap two elements in a list
Is there anyone can help me to have a look at this code. 有没有人可以帮助我看看这段代码。 I am trying to solve the first missing positive question in leetcode.
我正在尝试解决leetcode中第一个缺少的肯定问题。 But this code cause an endless loop as I found I fail to swap the A[i] and A[A[i]-1].
但是此代码导致一个无限循环,因为我发现我无法交换A [i]和A [A [i] -1]。 But I have test to swap to elements in list using this simple code:
但是我已经测试过使用以下简单代码交换到列表中的元素:
A = [2,1]
A[0], A[1] = A[1], A[0]
print A # A = [1,2]
I do not know what the mistake is :( 我不知道这是什么错误:(
def firstMissingPositive(self, A):
i = 0
length = len(A)
while i < length:
if A[i] >= 1 and A[i] <= length:
if A[i] != i+1 and A[A[i]-1] != A[i]:
A[i], A[A[i]-1] = A[A[i]-1], A[i]
else:
i += 1
else:
i += 1
for i in range(length):
if A[i] != i+1:
return i+1
return length + 1
You're modifying A[i]
during the execution of the assignment statement, and so the evaluation of A[A[i]-1]
on the left-hand side of the =
won't evaluate the way you're expecting it to. 您正在执行赋值语句期间修改
A[i]
,因此=
左侧的A[A[i]-1]
评估将不会评估您期望的方式至。 You need to change this: 您需要更改此:
A[i], A[A[i]-1] = A[A[i]-1], A[i]
to this: 对此:
tmp = A[i]-1
A[i], A[tmp] = A[tmp], A[i]
This phenomenon is addressed by a note in the Python Language Reference : Python语言参考中的注释解决了这种现象:
WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are 'safe' (for example
a, b = b, a
swaps two variables), overlaps within the collection of assigned-to variables are not safe!警告:尽管赋值的定义暗示左侧和右侧之间的重叠是“安全的”(例如
a, b = b, a
交换两个变量),但在赋值变量的集合内重叠不安全! For instance, the following program prints[0, 2]
:例如,以下程序打印
[0, 2]
:x = [0, 1] i = 0 i, x[i] = 1, 2 print x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.