Adding different information in a python linked list and printing it - python

I am trying to add different information in a python linked list and printing it, but there seems to be an error. I want to print the ID, the Music and the artist name. This is my error.
Traceback (most recent call last):
File "d:\DSAG\DSAG coding\tempCodeRunnerFile.py", line 101, in <module>
for i in range (0,LinkedList.len_link()):
TypeError: len_link() missing 1 required positional argument: 'list'
This is my code:
class Node :
def __init__(self, newData=None, nextNode=None):
self.data = newData
self.next = nextNode
def getData(self):
return self.data
def setData(self,newData):
self.data = newData
def getNext(self):
return self.next
def setNext(self,newNode):
self.next = newNode
class music :
def __init__(self, ID, musicname, artistname):
self.ID = ID
self.musicname = musicname
self.artistname = artistname
def printlist(self):
print("ID : " + format(self.ID))
print("Music : " + format(self.musicname))
print("Artist : " + format(self.artistname))
class LinkedList :
def __init__(self):
self.head = None
self.size=0
def next(self,newNode):
self.head = newNode
def len_link(list):
temp=list.head
count=0
while(temp):
count+=1
temp=temp.next
return count
def printAll(self):
node = None
if self.head is not None:
node = self.head
print(node.getData())
while(node.getNext() is not None):
node = node.getNext()
print(node.getData())
def AddMusicToTheFront(self,data):
if(self.head==None):
newnode=Node(data)
self.head=newnode
else:
current=self.head
while(current.next!=None):
current=current.next
current.next=Node(data)
self.size=self.size+1
def AddMusicAtPosition (self, data, position):
if(position==0):
newnode=Node(data)
newnode.next=self.head
self.head=newnode
elif(position>self.size):
print("\nOut of Range\n")
elif(position==self.size):
self.AddMusicToTheFront(data)
else:
current=self.head
count=0
while(current!=None):
if(count==position-2):
break
else:
count+=1
current=current.next
newnode=Node(data)
newnode.next=current.next
current.next=newnode
list = LinkedList()
list.AddMusicToTheFront(music(1, "Lauv", "Chasing Fire"))
list.AddMusicToTheFront(music(2, "Panic! At The Disco", "High Hopes"))
list.AddMusicToTheFront(music(3, "Bishop Briggs", "River"))
list.AddMusicAtPosition(music(4,"Why Don't We", "Hooked"),2)
for i in range (0,LinkedList.len_link()):
music.printlist()
This is my desired outcome :
ID:1
Artist : Lauv
Music : Chasing Fire
^This code will be the same for the rest of the information that I will include later

You probably need to define len_link like this:
def len_link(self):
temp=self.head
count=0
while(temp):
count+=1
temp=temp.next
return count
Then you can instantiate a LinkedList object (ll=LinkedList()) and then call len_link() like this ll.len_link().
So your code would look like this:
ll = LinkedList()
ll.AddMusicToTheFront(music(1, "Lauv", "Chasing Fire"))
ll.AddMusicToTheFront(music(2, "Panic! At The Disco", "High Hopes"))
ll.AddMusicToTheFront(music(3, "Bishop Briggs", "River"))
ll.AddMusicAtPosition(music(4,"Why Don't We", "Hooked"),2)
for i in range (0,ll.len_link()):
music.printlist()

for i in range (0,LinkedList.len_link(list)): music.printlist() #pass list in the len_link finction
And music is not set. it might get error because music never initiated and has no attributes, so when it'll try to print, error will occur.
what you need to do is extract an element fromt he list which is a music object then on that obj call printlist()

Related

I have a problem with syntax in nodes (data Structure)

This code should create a node but I have a problem with it I tried to fix it but I couldn`t
I want to know why there is a problem at in the Linked_List (Next_Node)
that is what show in the error "(Cannot assign member "next_node" for type "node"
Expression of type "node | None" cannot be assigned to member "next_node" of class "node"
Type "node | None" cannot be assigned to type "None"
Type cannot be assigned to type "None")"
class node :
data = None
next_node = None
def __init__(self , data) :
self.data = data
def __repr__(self) :
return "<node data: %s>" % self.data
class linked_list :
def __init__(self ):
self.head = None
def add (self , data):
new_node = node(data)
new_node.next_node = self.head
self.head = new_node
def __repr__ (self):
nodes =[]
current = self.head
while current :
if current is self.head:
nodes.append ("[:head %s ]" % current.data)
elif current.next.node is None :
nodes.append ("[tail: %s ]" % current.data)
else :
nodes.append ("[:%s ]" % current.data)
current = current.next_node
return "->".join(nodes)
There are several problems with current attempt:
The Node class as pointed by John Gordon is wrongly constructed. The data and next_node should be in __init__ method.
The add method is not adding new node in correct position.
The __repr__ is not looping through all the nodes in the linked list because of wrong indentation.
Updated code:
class node:
def __init__(self, data):
self.data = data
self.next_node = None
def __repr__(self):
return "<node data: %s>" % self.data
class linked_list:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def size(self):
current = self.head
count = 0
while current:
count += 1
current = current.next_node
return count
def add(self, data):
new_node = node(data)
if self.head == None:
self.head = new_node
else:
current = self.head
while current.next_node != None:
current = current.next_node
current.next_node = new_node
def __repr__(self):
nodes = []
current = self.head
while current:
if current is self.head:
nodes.append("[:head %s ]" % current.data)
elif current.next_node is None:
nodes.append("[tail: %s ]" % current.data)
else:
nodes.append("[:%s ]" % current.data)
current = current.next_node
return "->".join(nodes)
l = linked_list()
l.add(1)
l.add(2)
l.add(3)
print(l)
Output:
[:head 1 ]->[:2 ]->[tail: 3 ]
class node :
data = None
next_node = None
def __init__(self , data):
self.data = data
I think the problem is because of the node class definition.
The way you've defined the next_node variable, it is a direct attribute of the class, so it is shared among all instances of the class.
I think you intended that attribute to be inside the __init__ method, so that each instance would have its own separate copy of that variable:
class node :
def __init__(self , data) :
self.data = data
self.next_node = None

Node object isn't callable. Please resolve

#Linked List
class Node:
def __init__(self,item):
self.item = None
self.next = item
class Linked:
def __init__(self):
self.head = None
def printlist(self):
printval = self.head
while printval is not None:
printval(printval.item)
printval = printval.next
def insertion(self,newitem):
NewNode = Node(newitem)
NewNode.next = self.head
self.head = NewNode
def InsertBetween(self,Middle_Node,newitem):
if Middle_Node is None:
print("Value doesn't exist in node")
return
NewNode = Node(newitem)
NewNode.next = Middle_Node.next
Middle_Node.next = NewNode
listy = Linked()
listy.head = Node(20)
p2 = Node(21)
p3 = Node(22)
listy.head.next = p2
p2.next = p3
listy.InsertBetween(listy.head.next,40)
listy.insertion(45)
listy.printlist()
I'm getting this error:
Traceback (most recent call last):
File "c:\Users\Tanishq\Desktop\Python Practice SORTS\LList.py", line 41, in <module>
listy.printlist()
File "c:\Users\Tanishq\Desktop\Python Practice SORTS\LList.py", line 15, in printlist
printval(printval.item)
TypeError: 'Node' object is not callable
I think there are two mistakes in your code:
You are setting the variable item to None for every node and next to an int value.
The correct way would be the other way around
class Node:
def __init__(self,item):
self.item = item
self.next = None
In printlist there seems to be a typo printval should be print
print(printval.item)
I am assuming you are trying to implement a linked list and the above changes should get you the desired result

Why is the print show() showing not defined?

I used my pydroid to create a linkedlist, but the show() is outputting "nameError: name show not defined". Please any answer to why the error. The show() is to help me print out my added data from the add()
class Node:
next=None
data=None
def __init__(self,data):
self.data=data
class LinkedList:
def __init__(self):
self.head=None
def Empty(self):
return self.head==None
def size(self):
current = self.head
count=0
while current:
count +=1
current = current.next
return count
"""i want to be able to show data i add to the list wit the add()"""
def Show(self):
n= self.head
while n:
print(n.data)
n = n.next
else:
print("empty")
#the add()
def add(self, data):
new_node=Node(data)
new_node.next = self.head
self.head =new_node
b=LinkedList()
#a = Node(10)
#b.head=a
b.add(3)
b.add(3)
b.add(3)
print(b.size())
print(Show())
Print is unnecessary, just use what is listed below:
b.show()
credit #quamerana

How do I call a method from my outer class in an inner class of my custom-made linked list?

I'm learning python and challenging myself by writing my own linked list from scratch. I'm using a tradition structure of an inner node class which holds a piece of data and a reference to the next node. Right now I'm trying to create a __repr__ method that returns a string representation of a node. The string it returns looks like this: "This node contains {0}. The next node is {1}." .format(self.data, self.next.data)
It works fine unless there's only 1 node in the list, which gave me the following error: AttributeError: 'NoneType' object has no attribute 'data'.
To get around this, I check first to see if there's only one node in the list, and I return the following string: "This node contains {0}. There is no next node." .format(self.data)
This is what my __repr__ method looks like right now:
def __repr__(self):
if MyLinkedList.get_size() == 1:
return "This node contains {0}. There is no next node." . format(self.data)
return "This node contains {0}. The next node is {1}." .format(self.data, self.next.data)
This is what the whole linked list class looks like so far:
class MyLinkedList(object):
head = None
size = None
def __init__(self):
self.size = 0
def get_head(self):
return self.head
def get_size(self):
return self.size
def is_empty(self):
if self.size == 0:
return True
else:
return False
def __repr__(self):
result = "["
curr = self.head
while curr != None:
if curr.next == None:
result += curr.data
break
result += curr.data
result += ", "
curr = curr.next
result += "]"
return result
def add_to_head(self, data):
new_node = MyLinkedList.Node(data)
if self.size == 0:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
self.size += 1
def delete_from_head(self):
if (self.size == 0):
self.head = None
else:
new_head = self.head.next
self.head = new_head
self.size =- 1
class Node():
next = None
def __init__(self, data):
self.data = data
def get_data(self):
return self.data
def get_next(self):
return self.next
def __repr__(self):
if MyLinkedList.get_size() == 1:
return "This node contains {0}. There is no next node." . format(self.data)
return "This node contains {0}. The next node is {1}." .format(self.data, self.next.data)
But now when I try to print the string representation of any node, it gives me the following error: TypeError: get_size() missing 1 required positional argument: 'self'
Is there any way to fix this issue? All I'm trying to do is to call my outer class's get_size() method in my inner node class, and check if that value is 1. Is there any other way to make it so my node's __repr__ method returns the string I want it to return when there's only one node in the list?
Also, if you spot other improvements you could make to my code, I would be glad to hear them.
You can only invoke get_size() on an instance of your MyLinkedList class. A node shouldn't know anything about the linked list class anyway. Just take advantage of the node's next pointer instead:
def __repr__(self):
suffix = "There is not next node" if self.next is None else "The next node is {}".format(self.next.data)
return "This node contains {}. {}.".format(self.data, suffix)
I believe you need to add a self argument into the get_size() method. Such as:
def __repr__(self):
if MyLinkedList.get_size(self) == 1:
return "This node contains {0}. There is no next node." . format(self.data)
return "This node contains {0}. The next node is {1}." .format(self.data, self.next.data)

adding link in link list- python

I tried to add link to link list but program is taking Nodes as an integer and not Node plz help me out in it
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def add_link(self, new_link, after_link):
new_link = Node(new_link)
new_link.next = after_link.next
after_link.next = new_link
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print "Given Linked List"
llist.printList()
llist.add_link(35, 4)
print "\nAfter adding Link new Linked List"
llist.printList()
The Error is on new_link.next = after_link.next
AttributeError: 'int' object has no attribute 'next'
You have to just make a slight change in the add link function.
def add_link(self, new_link, after_link):
new_link = Node(new_link)
after_link=Node(after_link)
new_link.next = after_link.next
after_link.next = new_link
This is because you are passing an integer(after_link) to the function and then using after_link.next which is not possible because after_link is an integer .So first you have to make a Node with its data as the after_link integer
You have to create the object of type Node in which you will pass data and next
sample code
node_obj = Node(34,4)
moreover in function add_link(self, new_link, after_link),both parameters of new_link and after_link are of type Node

Categories