【发布时间】:2020-01-16 19:31:14
【问题描述】:
我正在反转一个链表,但是多个赋值会破坏这个功能,而单独的赋值不会。有人可以解释这两个代码段之间的执行差异吗?
我知道表达式的右侧是在赋值之前进行评估的,但是据我所知,如果是这种情况,我将无处可访问 None.next。
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def clear():
print("------------------------------------------")
def isPalindrome(A):
if A is None:
return True
# get length
cur, length = A, 1
while cur.next is not None:
cur = cur.next
length += 1
# go to second half
cur, index = A, 0
while index < (length + 1) / 2:
cur = cur.next
index += 1
# start reversing
prev = None
while cur is not None:
# this throws error? what is the difference?
# cur, prev, cur.next = cur.next, cur, prev
temp = cur.next
cur.next = prev
prev = cur
cur = temp
# now prev has reversed second half
secondHalf = prev
firstHalf = A
# traverse both halves, comparing Ll[n] with Ll[length - 1 - n]
while secondHalf is not None and firstHalf is not None:
if firstHalf.val != secondHalf.val:
return False
firstHalf = firstHalf.next
secondHalf = secondHalf.next
return True
# even length simple case
def isPalindromeTest():
A = Node(1, Node(1, Node(1, Node(1))))
clear()
print(isPalindrome(A))
isPalindromeTest()
我希望注释行
# cur, prev, cur.next = cur.next, cur, prev
等价于
temp = cur.next
cur.next = prev
prev = cur
cur = cur.next
如果我使用第一个代码部分,则会出现错误消息:
Traceback (most recent call last):
File "linked_lists.py", line 1089, in <module>
isPalindromeTest()
File "linked_lists.py", line 1052, in isPalindromeTest
print(isPalindrome(A))
File "linked_lists.py", line 1027, in isPalindrome
cur, prev, cur.next = cur.next, cur, prev
AttributeError: 'NoneType' object has no attribute 'next'
Implying that I am accessing None.next, which in this context it would have to be prev.next if anything?
第二段代码:
------------------------------------------
True
有人能解释一下这两个代码段的执行区别吗?
【问题讨论】:
-
如果您不打算使用它,分配给
temp有什么意义?最后一行是访问不正确的cur.next,因为cur.next已经被重新分配。cur = temp会在那里工作。 -
还会报错吗? (错误是什么?)
-
已编辑,意味着结尾有 cur = temp
-
在问题中添加了错误信息
标签: python python-3.x operator-precedence assignment-operator order-of-execution