Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python variable references

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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.

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading