Simple 5-line python with a rule to remember


  • 0
    Z
    def swapPairs(self, head):
        cur = dummy = ListNode(0)
        cur.next = head
        while cur.next and cur.next.next:
            cur.next.next.next, cur.next.next, cur.next, cur = \
                cur.next, cur.next.next.next, cur.next.next, cur.next
        return dummy.next
    

    [updated thanks to Stefan!]

    "A,B,C = X,Y,Z" is very powerful in linked list problem. Notice that in this solution, the order has to be "cur.next.next.next, cur.next.next, cur.next, cur". It would be nice to evaluate the farest variable first, while the path to that variable hasn't been changed.

    [old post]

    "A,B,C = X,Y,Z" is very powerful in linked list problem. Notice that in this solution, the order has to be "cur.next.next.next, cur.next.next, cur.next, cur"

    I am not an expert in python, my understanding of python's processing of "A,B,C = X,Y,Z" is

    1. Freeze A, B, C. If X, Y, Z depend on A, B, C, they are processed with frozen A, B, C
    2. Process sequentially, A, B, then C
    3. If B depends on A, then change of A will affect B -- a easy way is to put B ahead of A

    Based on (3), "cur.next.next.next, cur.next.next, cur.next, cur" is the right order to process.


  • 0
    This post is deleted!

  • 0

    I think "Freeze A, B, C" might give the wrong impression. It's probably better to explain what really happens. The right side of the assignment gets evaluated, and it's simply a tuple with three values. Why would A,B,C change during that evaluation? Would you mention A,B,C getting frozen in the following code?

    tmp = X, Y, Z
    A, B, C = tmp

  • 0
    Z

    I agree with you Stefan, thank you for pointing it out!


  • 0

    Btw, have you tried other orders than cur.next.next.next, cur.next.next, cur.next, cur? It's certainly possible, and you can save two .next that way. Ok, it's probably less clear, but I think it's a good exercise :-)


  • 0
    Z

    I did try some at that time, and concluded that, well, it was easiest that way not to mess my brain up. :)


  • 0

    Yeah, I did it with pen and paper, drawing and redrawing arrows between boxes. Totally worth it, though :-). Helps to get more familiar with such multi-assignments.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.