Оператор присваивания в python, дающий различные результаты после изменения позиции вызовов функций - PullRequest
0 голосов
/ 27 марта 2020

Почему

is_correct =  list(llist) == list(reverse(flipped))

is_correct выводит False, но

is_correct =  list(reverse(flipped)) == list(llist)

is_correct выводит True

Я пишу код для обращения к связанному списку, чтобы

  1. reverse () - это функция для обратного связывания списка.
  2. flipped и list - объекты LinkedList, показанные ниже.

Полный код

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
       self.head = None

    def __init__(self):
        self.head = None

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)

    def __iter__(self):
        node = self.head
        while node:
            yield node.value
            node = node.next

    def __repr__(self):
        return str([v for v in self])

def reverse(linked_list):

    head = linked_list.head
    nh = head.next
    head.next = None
    while nh:
        temp = nh.next
        nh.next = head
        head = nh
        nh = temp
    linked_list.head = head
    return linked_list

llist = LinkedList()
li = [4,2,5,1,-3,0]
for value in li:
    llist.append(value)

flipped = reverse(llist)
is_correct =  list(llist) == list(reverse(flipped))
print("Pass" if is_correct else "Fail")

llist = LinkedList()
li = [4,2,5,1,-3,0]
for value in li:
    llist.append(value)

flipped = reverse(llist)
is_correct =  list(reverse(flipped)) == list(llist) 
print("Pass" if is_correct else "Fail")

Заранее спасибо !!!

1 Ответ

1 голос
/ 27 марта 2020

Учитывая, что reverse является операцией на месте, ваш код эквивалентен

flipped = reverse(llist)  # two names for the same reversed list
t1 = list(llist)  # a copy of the reversed list
t2 = list(reverse(flipped)) # a copy of the re-reversed list, identical to the original
is_correct = t1 == t2  # False; one is in the original order, the other reverse order

flipped = reverse(llist)  # two names for the same reversed list
t1 = list(reverse(flipped)) # a copy of the re-reversed list
t2 = list(llist) # another copy of the re-reversed list
is_correct = t1 == t2  # True; both lists are in the original non-reversed order

Операнды к == оцениваются слева направо, поэтому сначала вызывается reverse или секунда определяет, какие объекты создаются list.

...