younameit01
younameit01

Reputation: 23

What's wrong with the code although i have defined the function already?

this code gives NameError showing i havenot defined the function but i actually defined the function in a class.

I tried alot but couldnot resolve it.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList(object):
    def __init__(self):
        self.head = None

    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next

    def append(self, new_data):
        new_node = Node(new_data)
        if self.head is None:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
            last.next = new_node

    def merge(self, head1, head2):
        temp = None
        if head1 is None:
            return head2

        if head2 is None:
            return head1

        if head1.data <= head2.data:
            temp = head1
            temp.next = merge(head1.next, head2)

        else:
            temp = head2
            temp.next = merge(head1, head2.next)

        return temp

list1 = LinkedList()
list1.append(10)
list1.append(20)
list1.append(30)
list1.append(40)
list1.append(50)

list2 = LinkedList()
list2.append(5)
list2.append(15)
list2.append(18)
list2.append(35)
list2.append(60)

list3 = LinkedList()
list3.head = merge(list1.head, list2.head)

print("Merged Linked List is : ")
list3.printList()
NameError                                 Traceback (most recent call last)
<ipython-input-11-22fca0a2d24d> in <module>()
     57 
     58 list3 = LinkedList()
---> 59 list3.head = merge(list1.head, list2.head)
     60 
     61 print("Merged Linked List is : ")

NameError: name 'merge' is not defined

Upvotes: 0

Views: 46

Answers (1)

Blckknght
Blckknght

Reputation: 104842

You have defined merge as a method of the LinkedList class. That means you need to call it on an instance of the class, not just by itself. For instance, you could replace the merge(...) call causing your current exception with list3.merge(...), and the recursive call inside the method with self.merge(...).

But I'm not really sure it needs to be a method, so you could instead move the function definition out of the class (and remove its self parameter). It would work just fine as a stand-alone function.

Upvotes: 1

Related Questions