This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 3 years ago.
can anybody explain why it is showing me and how to print it?
what am I doing wrong and how to print this object reference?
i have also tried printing new_list(inside sort() ) but still the same
I am printing list then why it is not showing
I know some of the people asked before about related to this...but still I didn't get it.
class node(object):
def __init__(self, d, n=None):
self.data=d
self.next_node=n
def get_data(self):
return self.data
def set_data(self,d):
self.data=d
def get_next(self):
return self.next_node
def set_next(self, n):
self.next_node=n
def has_next(self):
if self.get_next() is not None:
return True
else:
False
class LinkedList(object):
def __init__(self, r=None):
self.root=r
self.size=0
def get_size(self):
return self.size
def add(self,d):
new_node = node(d, self.root)
self.root = new_node
self.size+=1
def sort(self):
if self.size>2:
newlist = []
this_node = self.root
newlist.append(this_node)
while this_node.has_next():
this_node = this_node.get_next()
newlist.append(this_node)
newlist = sorted(newlist ,key = lambda node: node.data,reverse=True)
newLinkedList = LinkedList()
for element in newlist:
newLinkedList.add(element)
return newLinkedList
return self
new_list=LinkedList()
new_list.add(10)
new_list.add(20)
new_list.add(30)
new_list.sort()
i expected that it will print list print a list
but it is showing <main.LinkedList object at 0x00E20BB0>
how to print this object ?
You are not printing out node values of the linked list instead you are printing out the return value of the sort() function which is an object of the class LinkedList.
If you want to print the linked list, you have to traverse the list and print out each node value individually.
Here is the recursive solution of how you can print a linked list.
def print_list(head):
if head != null:
print(head.val)
print_list(head.next)
You can call this method after calling the sort function
Related
So I was trying to make a Linked List in python, but I'm getting this error:
If currentNode.nextNode is None:
AttributeError: 'str' object has no attribute 'nextNode'
Not sure why I get that as currentNode.nextNode should have a .nextNode attribute just like every other node.
Here's the code:
class linkedListNode:
def __init__(self, value, nextNode=None):
self.value=value
self.nextNode=nextNode
class linkedList():
def __init__(self, head=None):
self.head=head
def insert(self, value):
node=linkedListNode(value)
if self.head==None:
self.head=node
return
currentNode = self.head
while True:
if currentNode.nextNode is None:
currentNode.nextNode=node
break
currentNode = currentNode.nextNode
def printLinkedList (self):
curNode=self.head
while curNode!=None:
print(curNode.value)
curNode=curNode.nextNode
#Just testing out the linked list below to see if it works:
ll=linkedList("10")
ll.insert("50")
ll.insert(4)
ll.insert(6)
ll.insert(3)
ll.insert(1)
ll.printLinkedList()
The way you defined linkedList, it expects an instance of linkListNode as an argument, not a value.
ll = linkedList(linkedListNode("10"))
When you initialize the linkedList object you are passing a string as a parameter:
ll=linkedList("10")
As a result self.head will be equal to string "10"
Python 3 - I am new to coding and am finding recursion difficult. I'm making a linked list class with recursive methods for adding and removing items from the list. Right now, I am unable to remove an item if it happens to be the first item in my list. I wrote some alternative code which could remove the first item from the list if I included another parameter (previous) and another base case, but then I could only remove the first item and spent way too long trying to figure out why so I scrapped that entirely. I would appreciate a hint!
Also, I am already aware that I have getters and am not using them properly.
class Node:
"""
Represents a node in a linked list
"""
def __init__(self, data):
self._data = data
self._next = None
def get_data(self):
"""getter method for data in Node class"""
return self._data
def get_next(self):
"""getter method for next in Node class"""
return self._next
class LinkedList:
"""
A linked list implementation of the List ADT
"""
def __init__(self):
self._head = None
def get_head(self):
"""getter function for head of list"""
return self._head
def add(self, val):
""" Adds a node containing val to the linked list - helper function"""
self._head = self.recursive_add(self._head, val)
def recursive_add(self, node1, val):
""" Adds a node containing val to the linked list """
if node1 is None:
return Node(val)
else:
node1._next = self.recursive_add(node1._next, val)
return node1
def remove(self, val):
"""removed the node containing val from the linked list - helper function"""
self.recursive_remove(self._head, val)
def recursive_remove(self, node1, val):
"""
Removes the node containing val from the linked list
"""
if node1 is None:
return node1
elif node1._data == val:
return node1._next
else:
node1._next = self.recursive_remove(node1._next, val)
return node1
def main():
my_list = LinkedList()
my_list.add(13)
my_list.add(9)
my_list.add(5)
my_list.remove(9)
if __name__ == '__main__':
main()
def remove(self, val):
"""removed the node containing val from the linked list - helper function"""
if self._head and self._head._data == val:
self._head = self._head._next
return
self.recursive_remove(self._head, val)
if its at the start, the head needs to be changed.
In remove you call recursive_remove, but ignore its return value. You should use it as the (potentially different) _head reference, must like is done in the recursive method itself, where you have:
node1._next = self.recursive_remove(node1._next, val)
# ^ │
# └───────────────────────────────────┘
Note how node1._next is passed as argument, and the method's return value is the (potentially different) reference that node1._next should end up with. The same pattern should be applied in the initial call in remove:
def remove(self, val):
self._head = self.recursive_remove(self._head, val)
# ^ │
# └──────────────────────────────────┘
NB: the same pattern is used in add, where you do it correctly.
I have stack code:
class Stack:
def __init__(self):
self.__data = []
def empty(self):
return len(self.__data) == 0
def size(self):
return len(self.__data)
def push(self, x):
self.__data.append(x)
def pop(self):
return self.__data.pop()
and adds numbers 1, 2:
stack = Stack()
stack.push(1)
stack.push(2)
and I don't know how to print __data list?
so that it shows 1,2 in the list?
[1,2]
As __data is a private attribute of stack object, it cannot be accessed outside the class. Instead define an instance method to print the stack list as shown below.
class Stack:
def print_stack(self):
print(self.__data)
Now if you call print_stack() on an instance. It will print the __data list.
You can use __str__ method to print the values using print() or __repr__ for direct representation.
class Stack:
def __init__(self):
self.data = []
def empty(self):
return len(self.data) == 0
def size(self):
return len(self.data)
def push(self, x):
self.data.append(x)
def pop(self):
return self.data.pop()
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self.data)
>>> stack = Stack()
>>> stack.push(1)
>>> stack.push(2)
>>> print(stack) ## using __str__
# [1, 2]
>>> stack ## using __repr__
# [1, 2]
I have one more question. My code:
class Stack:
def __init__(self):
self.data = []
def empty(self):
return len(self.data) == 0
def size(self):
return len(self.data)
def push(self, x):
self.data.append(x)
def pop(self):
if len(self.data) == 0:
print("underflow")
else:
return self.data.pop()
def __str__(self):
return str(self.data)
stack = Stack()
stack.push(1)
stack.push(2)
print(stack)
I print the list as I wanted:
[1,2]
Now i wonder if i can work on this list? That is, as always on the lists:
In this case:
list = stack
list[0]
1
Can you recommend some simple courses where do Class is explained? I feel confused and my questions seem simple...
I am using two python files, one file in which a class of linked list present and another file is the one in which I am importing first file so that I can use linked list I built in first file. The second file is for reverse file. I have already done reverse using iteration part, now trying to build a code for reverse using recursion and for that I am calling and passing arguments inside function but something did not work out and it is showing TypeError like this function has no arguments.
Please check it out my code followed by error
Second file
from code.linkedlist import *
llist=linkedlist()
llist.appendnodesatbegin(23)
llist.appendnodesatbegin(45)
llist.appendnodesatbegin(67)
llist.appendnodesatbegin(12)
llist.appendnodesatbegin(-11)
llist.appendnodesatbegin(0)
print ("Before reverse")
llist.display()
def reverseiterative():
llist.current = llist.head
llist.prev = None
while (llist.current):
llist.next = llist.current.next
llist.current.next = llist.prev
llist.prev = llist.current
llist.current = llist.next
llist.head = llist.prev
reverseiterative()
print("After the reverse of list using iterative method")
llist.display()
llist.p=llist.head
llist.prev=None
def reverserecursive(p,prev):
next1=llist.p.next
p.next=prev
if llist.next1 is None:
return
else:
reverserecursive(next1,p)
reverserecursive(llist.p,llist.prev)
print("After the reverse of list using recursive method")
llist.display()
first file:
class node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist:
def __init__(self):
self.head=None
self.last_pointer=None
def appendnodesatbegin(self,data):
newnode=node(data)
if(self.head==None):
self.head=newnode
self.last_pointer=newnode
else:
self.last_pointer.next=newnode
self.last_pointer=self.last_pointer.next
def appendnodesatend(self,data):
newnode=node(data)
newnode.next=self.head
self.head=newnode
def appendatmid(self,prev,new):
temp=self.head
newnode=node(new)
while(temp):
if(temp.data==prev):
newnode.next=temp.next
temp.next=newnode
temp=temp.next
def display(self):
temp=self.head
while(temp):
print(temp.data)
temp=temp.next
#def reversedisplay(self):
error is
reverseiterative(llist.p,llist.prev)
TypeError: reverseiterative() takes no arguments (2 given)
reverseiterative as defined:
def reverseiterative():
takes no argument, you are calling it with 2.
You were probably supposed to call reverserecursive given the arguments you passed and the argument's in the function signature:
def reverserecursive(p,prev):
Your function doesn't take any parameters in it's deceleration:
reverseiterative(foo, bar):
This (or whatever values you wish to process) will fix it.
from code.linkedlist import *
llist=linkedlist()
llist.appendnodesatbegin(23)
llist.appendnodesatbegin(45)
llist.appendnodesatbegin(67)
llist.appendnodesatbegin(12)
llist.appendnodesatbegin(-11)
llist.appendnodesatbegin(0)
print ("Before reverse")
llist.display()
def reverseiterative(self):
self.current = self.head
self.prev = None
while (self.current):
self.next = self.current.next
self.current.next = self.prev
self.prev = self.current
self.current = self.next
self.head = self.prev
llist.reverseiterative=reverseiterative
llist.reverseiterative()
print("After the reverse of list using iterative method")
llist.display()
def reverserecursive(self,p,prev):
next=p.next
p.next=prev
if next is None:
return
else:
self.reverserecursive(next,p)
llist.p=llist.head
llist.prev=None
llist.reverserecursive(llist.p,llist.prev)
print("After the reverse of list using recursive method")
llist.display()
Here is the second part to fix your issue:
class node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist:
def __init__(self):
self.head=None
self.last_pointer=None
def appendnodesatbegin(self,data):
newnode=node(data)
if(self.head==None):
self.head=newnode
self.last_pointer=newnode
else:
self.last_pointer.next=newnode
self.last_pointer=self.last_pointer.next
def appendnodesatend(self,data):
newnode=node(data)
newnode.next=self.head
self.head=newnode
def appendatmid(self,prev,new):
Ok so im trying to input a word in a stack and I want to print all of them after I input a string. So I can only print them one at a time. I tried using a for loop outside but Stacks are apparently not iterable. So I iterating it inside the stack. It still is not working.
class Stack:
def __init__(self):
self.items = []
def push(self,items):
self.items.insert(0,items)
def pop(self):
for x in self.items:
print( self.items.pop(0))
def show(self):
print (self.items)
s = Stack()
s.show()
placed = input("enter")
item = s.pop()
print(item, "is on top", s)
Give your Stack class a __len__ method, this will make testing if the stack is empty easier:
class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def show(self):
print (self.items)
def __len__(self):
return len(self.items)
stack = Stack()
stack.push('World!')
stack.push('Hello')
while stack: # tests the length through __len__
print(stack.pop())
Note that I simply .append() to the end of the .items list, then later on .pop() (no arguments) again, removing from the end of the list.
To make your class an iterable type, you'd need to add at least an __iter__ method, optionally together with a .__next__() method:
class Stack:
# rest elided
def __iter__(self):
return self
def next(self):
try:
return self.items.pop()
except IndexError: # empty
raise StopIteration # signal iterator is done