90.0 Python for C/C++ programmers

Pass by assignment

Python 3 faq on call by reference

Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways, e,g, by returning a tuple of the results, etc.

An example

Translate the C++ solution for EPI 4.1 to Python for LC 21. Merge Two Sorted Lists

# refer to EPI 4.1
class Solution(object):

    def append_node(self, head, tail, node):

        # tail.next = node if head is not None else head = node
        # SyntaxError: can't assign to conditional expression
        # http://stackoverflow.com/questions/14474168/using-statements-on-either-side-of-a-python-ternary-conditional
        if head:
            tail.next = node
        else:
            head = node
        tail = node  # reset tail to the last node
        return head, tail

    def append_node_and_advance(self, head, tail, node):
        head, tail = self.append_node(head, tail, node)
        node = node.next  # advance the node

        return head, tail, node

    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        sorted_head = None
        sorted_tail = None

        # Compare the contents of pointers and the pointer with the lesser contents is
        # to be added to the end of the result and advanced.
        while l1 and l2:
            if l1.val < l2.val:
                sorted_head, sorted_tail, l1 = self.append_node_and_advance(sorted_head, sorted_tail, l1)
            else:
                sorted_head, sorted_tail, l2 = self.append_node_and_advance(sorted_head, sorted_tail, l2)

        # Append the remaining nodes of l1
        if l1:
            sorted_head, sorted_tail = self.append_node(sorted_head, sorted_tail, l1)

        # Append the remaining nodes of l2
        if l2:
            sorted_head, sorted_tail = self.append_node(sorted_head, sorted_tail, l2)

        return sorted_head

results matching ""

    No results matching ""