6

In the line (l1 = sortList(head)) for recursion, I get NameError: global name 'sortList' is not defined. Could anyone point out where I did wrong?

class Solution:
    # @param head, a ListNode
    # @return a ListNode

    def sortList(self, head):
        if head == None or head.next == None:
            return head

        slow = head
        fast = head

        while fast != None and fast.next != None:
            slow = slow.next
            fast = fast.next.next
        fast = slow
        slow = slow.next
        fast.next = None
        l1 = sortList(head)
        l2 = sortList(slow)
        l = mergeTwoLists(l1, l2)
        return l
4
  • Welcome to SO. I've edited your code a bit - usually displaying a more minimal coding example (not the entire code, but just the relevant part) helps with the readability of the question. Commented Jun 18, 2014 at 17:53
  • It's also generally a good practice to accept the answer that answered your question. Commented Jun 18, 2014 at 18:30
  • Should I accept an answer by voting up or other method? Since I just entered Stackoverflow and my reputation hasn't reached 15, I could not vote up currently. I will definitely do so after I can. Thanks again. Commented Jun 18, 2014 at 19:04
  • There's a green V mark under the voting. see here: stackoverflow.com/tour Commented Jun 18, 2014 at 19:37

3 Answers 3

10

sortList is a method of Solution, and doesn't exist independently. Use:

self.sortList(head)

and it would work.

Sign up to request clarification or add additional context in comments.

Comments

1

Change l1 = sortList(head) to l1 = self.sortList(head), and l2 = sortList(slow) to l2 = self.sortList(slow). sortList is defined in the Solution class and does not exist globally, that's why you need self to refer to the current Solution object.

Comments

0

You have not imported any function named sortList, so there only exists a sortList that can be called on a Solution object.

Use self.sortList. self is a variable used in python to refer to the current object. Much like this in other languages.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.