Why is the print show() showing not defined? - python

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

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

Reversed double linked list by python

why can't print reversed this double linked list by python?
always print 6 or None
please can anyone help me fast to pass this task
///////////////////////////////////////////////////////////////////////////
class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.previous = prev
sample methods==>
def set_data(self, newData):
self.data = newData
def get_data(self):
return self.data
def set_next(self, newNext):
self.next = newNext
def get_next(self):
return self.next
def hasNext(self):
return self.next is not None
def set_previous(self, newprev):
self.previous = newprev
def get_previous(self):
return self.previous
def hasPrevious(self):
return self.previous is not None
class double===>
class DoubleLinkedList:
def __init__(self):
self.head = None
self.tail = None
def addAtStart(self, item):
newNode = Node(item)
if self.head is None:
self.head = self.tail = newNode
else:
newNode.set_next(self.head)
newNode.set_previous(None)
self.head.set_previous(newNode)
self.head = newNode
def size(self):
current = self.head
count = 0
while current is not None:
count += 1
current = current.get_next()
return count
here is the wrong method ==>
try to fix it without more changes
def printReverse(self):
current = self.head
while current:
temp = current.next
current.next = current.previous
current.previous = temp
current = current.previous
temp = self.head
self.head = self.tail
self.tail = temp
print("Nodes of doubly linked list reversed: ")
while current is not None:
print(current.data),
current = current.get_next()
call methods==>
new = DoubleLinkedList()
new.addAtStart(1)
new.addAtStart(2)
new.addAtStart(3)
new.printReverse()
Your printReverse seems to do something else than what its name suggests. I would think that this function would just iterate the list nodes in reversed order and print the values, but it actually reverses the list, and doesn't print the result because of a bug.
The error in your code is that the final loop has a condition that is guaranteed to be false. current is always None when it reaches that loop, so nothing gets printed there. This is easily fixed by initialising current just before the loop with:
current = self.head
That fixes your issue, but it is not nice to have a function that both reverses the list, and prints it. It is better practice to separate these two tasks. The method that reverses the list could be named reverse. Then add another method that allows iteration of the values in the list. This is done by defining __iter__. The caller can then easily print the list with that iterator.
Here is how that looks:
def reverse(self):
current = self.head
while current:
current.previous, current.next = current.next, current.previous
current = current.previous
self.head, self.tail = self.tail, self.head
def __iter__(self):
node = self.head
while node:
yield node.data
node = node.next
def __repr__(self):
return "->".join(map(repr, self))
The main program can then be:
lst = DoubleLinkedList()
lst.addAtStart(1)
lst.addAtStart(2)
lst.addAtStart(3)
print(lst)
lst.reverse()
print(lst)

Insert an item at the begining of linked list by Python3

How to modify the following code? so that the item can be inserted to the begining of a linked list with add()? why None shows up at the beginning of the linked list? is there anything wrong? I tried several times. It just does not work. What heppened? Any suggestions to change? Is ther any good suggestion when writing a linked list?
class Node:
def __init__(self, data=None):
self.data= data
self.next = None
class linkedlist:
def __init__(self):
self.head=Node()
def append(self,data):
cur_node = self.head
new_node=Node(data)
while cur_node.next != None:
cur_node = cur_node.next
cur_node.next=new_node
def display(self):
lst=[]
cur_node=self.head
while cur_node.next!=None:
cur_node = cur_node.next
lst.append(cur_node.data)
return lst
def length(self):
cur_node=self.head
c=0
while cur_node.next!=None:
cur_node = cur_node.next
c+=1
return c
def get(self,index):
if index >=self.length():
print('out of bond!')
return None
cur_index=0
cur_node=self.head
while True:
cur_node=cur_node.next
if cur_index==index: return cur_node.data
cur_index+=1
def erase(self,index):
if index>=self.length():
print('out of bound')
return None
cur_index=0
cur_node=self.head
while True:
temp=cur_node
cur_node=cur_node.next
if cur_index==index:
temp.next=cur_node.next
print('erase',index)
return
cur_index+=1
def add(self,data):
cur_node=Node(data)
cur_node.next=self.head
self.head=cur_node
LL=linkedlist()
LL.append(1)
LL.append(2)
LL.append(3)
LL.append(4)
print(LL.add(999))
print(LL.display())
None
[None, 1, 2, 3, 4]
Why there is no 999 and How to remove None at the begining?
Since the Linked List is created with a dummy node as head, and all other methods depend on that assumption, add should never replace it. The idea behind this dummy node, is that it will always be there and never change. It helps to keep code simple (at the cost of the memory for one extra node).
So avoid that add changes the head attribute. The new node should be inserted just after that head:
def add(self,data):
cur_node=Node(data)
cur_node.next=self.head.next
self.head.next=cur_node

Adding different information in a python linked list and printing it

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()

Linked-list node delete function

I've been asked to implement a Node delete function where i delete 1 node
why is my Node delete deleting entire list?.
class Node(object):
def __init__(self, value):
self.value=value
self.next=None
self.prev=None
class List(object):
def __init__(self):
self.head=None # start of list
self.tail=None # end of list
def insert(self,n,x):
if n!=None:
x.next=n.next
n.next=x
x.prev=n
if x.next!=None:
x.next.prev=x
if self.head==None:
self.head=self.tail=x
x.prev=x.next=None
elif self.tail==n:
self.tail=x
def display(self):
values=[]
n=self.head
while n!=None:
values.append(str(n.value))
n=n.next
print ("List: ",",".join(values))
def deleteNode (self,n):
if n.prev!=None:
n.prev.next = n.next
else:
self.head = n.next
if n.next != None:
n.next.prev = n.prev
else:
self.tail = n.prev
if __name__ == '__main__':
listofnodes=List()
listofnodes.insert(None, Node(4))
listofnodes.insert(l.tail,Node(6))
listofnodes.insert(l.head,Node(8))
listofnodes.insert(l.head,Node(5))
listofnodes.insert(l.head,Node(9))
listofnodes.insert(l.head,Node(10))
listofnodes.deleteNode(Node(8)) # I want to delete Node 8 from listofnodes
listofnodes.display()
before the node delete is called the whole list displays, after i run it shows no elements
Any ideas?
In
listofnodes.deleteNode(l,Node(8))
you are passing 2 argument, with a third one (the self in the declaration) passed implicitly
You declare the method as
def deleteNode (self,n):
so it accept only one parameter (n)

Categories