2

I am trying to run the below code, I expect the code to return a list called head which would contain sum of (first and second) where first and second is linked lists passed as an argument.

As you see at the end I have created two linked List l1 and l2. I am assuming this linked lists will inherit from the Node class.

But it gives an attribute error. I can't seem to figure out the problem. I am a novice in programming, self learner. What might be causing this error? How do we go about solving it?

class Node:                                  
    def __init__(self,data=None):            
        self.data = data                     
        self.next = None                     
                                             
class LinkedList:                            
    def __init__(self):                      
        self.head = None                     
                                             
    def display(self):                       
        elems = []                           
        current = self.head                  
        while current != None:               
            elems.append(current.data)       
            current = current.next           
        return elems                         
                                             
    def append(self, data):                  
        elem = Node(data)                    
        if self.head == None:                
            self.head = elem                 
        else:                                
            current = self.head              
            while current.next != None:      
                current = current.next       
            current.next = elem              
                                             
    def addTwoLists(self, first, second):    
        head = third = Node(0)               
        carry = 0                            
                                             
        while first or second or carry:      
            if first:                        
                carry += first.data          
                first = first.next           
            if second:                       
                carry += second.data         
                second = second.next         
                                             
            third.data = carry % 10          
            carry = carry // 10              
                                             
            if first or second or carry:     
                third.next = Node(0)         
                third = third.next           
        return head
                             
ll = LinkedList()             
list1 = LinkedList()          
list2 = LinkedList()          
list1.append(7)               
list1.append(1)               
list1.append(6)               
print(list1.display())        
list2.append(5)               
list2.append(9)               
list2.append(2)               
print(list2.display())        
ll.addTwoLists(list1,list2)   
print(ll.display())    

And the error I get it:

  carry += first.data
AttributeError: 'LinkedList' object has no attribute 'data'    
  • I think you meant `first.head.data`... `first` is a `LinkedList` which only has one attribute `head`. On the other hand, `head` is a `Node` object which has a `data` attribute – Tomerikoo Nov 05 '20 at 15:42
  • @Tomerikoo I have edited the code, I am new to stackoverflow, it gives me sofeedbacks from the users. Didn't what protocol to follow. Thank you –  Nov 05 '20 at 16:15
  • And what about my first comment? Did you try it? – Tomerikoo Nov 05 '20 at 16:16
  • [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) | [What is a debugger and how can it help me diagnose problems?](//stackoverflow.com/q/25385173/843953) – Pranav Hosangadi Nov 05 '20 at 16:18
  • @Tomerikoo This is what I did as far I understood carry += first.head.data first = first.head.next, it gives another error, Node object has not attribute head. –  Nov 05 '20 at 16:21
  • Note that you never use the return value of `addTwoLists` and it also not modifying the instance so it basically does nothing... – Tomerikoo Nov 05 '20 at 16:35
  • @Tomerikoo Are you saying I don't need return statement here? That doesn't seem to affect my code, I still get same error Node Object has no attribute error. Thank you –  Nov 05 '20 at 19:12
  • I didn't say it will solve your error. It's something that makes it hard to help you because it's not clear what the code is supposed to do and you didn't give any details except *I am trying to run the below code*. You are calling the `addTwoLists` method from an empty list instance (`l1`) but you never really change it. Do you expect the method to return a new list (in that case why is it inside the class) or do you expect it to modify the instance (in that case why it doesn't use the `self`)? – Tomerikoo Nov 05 '20 at 19:14
  • @Tomerikoo I appreciate you taking time to follow up . I have edited my question again. Hope I have clarified. –  Nov 05 '20 at 19:55

3 Answers3

2

You need to make the distinction between a LinkedList and a Node.

I am assuming this linked lists will inherit from the Node class.

While they have a relation, it is not inheritance. The only connection between them is that LinkedList contains Nodes. Inheritance is achieved syntactically by doing something like: class LinkedList(Node):, but that seems logically improper in your case (LinkedList is not a Node, but it does contain a Node, as your current code does).

Using meaningful names to your variables can help with this confusions. Note that the arguments to addTwoLists are lists, but you treat them as if they were nodes with a data attribute.

Another thing you need to decide is if your function returns a new list or mutates one. I understand that you want to return a new one, in that case the method can either be static, or not inside the class at all (because you never really use self). Currently your method doesn't mutate any object and you also don't use its return value.

You can define it outside of the class and make it return a new list:

def addTwoLists(first_list, second_list):
    third_list = LinkedList()
    carry = 0

    first_node = first_list.head
    second_node = second_list.head
    while first_node or second_node or carry:      
        if first_node:                        
            carry += first_node.data          
            first_node = first_node.next           
        if second_node:                       
            carry += second_node.data         
            second_node = second_node.next         
                                         
        third_list.append(carry % 10)
        carry = carry // 10              
                                                   
    return third_list

Then in your main code, just do ll = addTwoLists(list1, list2)

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

First is a linkedList object so it can not have attributes from the Node Class. If you want to make First a Node Object you have to use

First = Node()
Seaver Olson
  • 450
  • 3
  • 16
  • I have added first = Node() and second = Node(), inside addTwoLists method, Now it throws error carry += first.data TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType' –  Nov 05 '20 at 15:59
  • What do you mean? `first` is a method's argument... – Tomerikoo Nov 05 '20 at 16:37
  • @Tomerikoo thats what i'm saying, its a argument in this code but their trying to use it as an object, they have to define it as an object – Seaver Olson Nov 05 '20 at 19:53
0

if you want to acces the data then do this it will reolve your current error. Let me know if you didnt understand what i mean

first_node = first.head
print(first_node.data)
Sachin Rajput
  • 238
  • 7
  • 26
  • While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. From [answer]: _"Brevity is acceptable, but fuller explanations are better."_ – Pranav Hosangadi Nov 05 '20 at 16:18
  • @SachinRajput I don't understand what you are saying –  Nov 05 '20 at 21:29
  • @samanthaCannon Refer this link https://stackoverflow.com/questions/39585740/how-can-i-print-all-of-the-values-of-the-nodes-in-my-singly-linked-list-using-a – Sachin Rajput Nov 06 '20 at 03:04