Home > OS >  Python variable references
Python variable references

Time:12-17

New to Python and picking up some practice on DSA problems though I have previously only worked in Java. Why does option 2 work and option 1 does not? I have seen Python passes by object reference and suspect the answer is to do with using references of references.

Option 1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        current = head
        fastp = current
        slowp = current

        while (current and current.next):
            fastp = fastp.next.next
            slowp = slowp.next
            current = current.next                 
        return slowp

Option 2

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fastp = head
        slowp = head

        while (fastp and fastp.next):
            fastp = fastp.next.next
            slowp = slowp.next                    
        return slowp

Shown 2 example solutions above, one working and one incorrect but unsure why.

CodePudding user response:

In option 1, current is a reference that does not change in the loop.

Actually, it is not clear which line of the loop (assignment to fastp or assignment to slowp) was expected to change current. Maybe something else was meant, and option 1 is just buggy?

  • Related