Understanding the "self" in classes for Python - python-3.x

I'm trying to understand the solution provided for reversing a linked list. In particular, I don't get why for the very last line we write:
self.head=prev
and not
current=prev
since
current=self.head
I know my reasoning is flawed, that's why I came here for help. Thank you in advance.
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev

= is not equality like in math, it is the assignment/binding operator.
Therefore, after:
current=self.head
current=prev
current will have the value of prev and self.head will have nothing to do with current nor will be modified.

Related

code should not return any node object(Element)

https://gist.github.com/manaidu-2002/3f7eb60b8521201eba6548ca23cec053
Code returning Node Object(Element), please check the test cases and help me with this
"""Add a couple methods to our LinkedList class,
and use that to implement a Stack.
You have 4 functions below to fill in:
insert_first, delete_first, push, and pop.
Think about this while you're implementing:
why is it easier to add an "insert_first"
function than just use "append"?"""
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def insert_first(self, new_element):
"Insert new element as the head of the LinkedList"
new_element.next = self.head
self.head = e_insert
def delete_first(self):
"Delete the first (head) element in the LinkedList as return it"
temp = self.head
if temp == None:
return None
s= temp
self.head = temp.next
return s
class Stack(object):
def __init__(self,head=None):
self.ll = LinkedList(head)
def push(self, new_element):
"Push (add) a new element onto the top of the stack"
temp = self.ll.head
while temp.next :
temp = temp.next
temp.next = new_element
def pop(self):
"Pop (remove) the first element off the top of the stack and return it"
if self.ll.head.next == None :
temp = self.ll.head
e= temp
temp = None
return e
elif self.ll.head.next:
temp = self.ll.head
while temp.next.next:
temp = temp.next
e= temp.next
temp.next = None
return e
return None
# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
# Start setting up a Stack
stack = Stack(e1)
# Test stack functionality
stack.push(e2)
stack.push(e3)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop())
stack.push(e4)
print(stack.pop().value)
First of all, there is an unused name reference in your code: e_insert. This should read new_element.
The main issue is that your Stack class is not re-using the code you already have in your LinkedList class. In the new code you have written there are several mistakes in how you deal with next, but taking a step back, you are making a critical mistake in thinking that the top of the stack should be at the tail of the linked list, but that is very inefficient. The top of the stack should be at the head of the linked list. It is at that side that you can easily remove and insert elements without having to iterate the list.
So take these points into consideration:
Reuse the code you already have for LinkedList. In other words, call the methods defined on the LinkedList class.
The top of the stack is at the head of the linked list.
That means the Stack class can be as simple as this:
class Stack(LinkedList):
def __init__(self, head=None):
self.ll = LinkedList(head)
def push(self, new_element):
self.ll.insert_first(new_element)
def pop(self):
return self.ll.delete_first()

how to make this code short for reverse circular LL in python

class node:
def __init__(self,data):
self.data = data
self.next = None
class circularLL:
def __init__(self):
self.head = None
self.tail = None
def insertNode(self,data):
newnode = node(data)
if self.head is None:
self.head = newnode
self.tail = newnode
else:
newnode.next = self.head
tail = self.tail
tail.next = newnode
self.tail = tail.next
def printCLL(self):
current = self.head
while current.next is not None and current.next is not self.head:
print(current.data, end="----")
current = current.next
print(current.data)
def reverseCLL(self):
head = self.head
tail = self.tail
if head == tail:
return
else:
count = 0
while head.next is not tail:
count +=1
if count ==1:
next = head.next
prev = head
head.next = tail
newtail = head
head = next
else:
next = head.next
head.next = prev
prev = head
head = next
if count is not 0:
next = head.next
head.next = prev
prev = head
tail.next = prev
self.head = tail
self.tail = newtail
else:
head.next = tail
self.tail.next = head
self.head = tail
self.tail = head
c = circularLL()
c.insertNode(1)
c.printCLL()
c.insertNode(2)
c.insertNode(3)
c.insertNode(4)
c.insertNode(5)
c.insertNode(6)
c.printCLL()
c.reverseCLL()
c.printCLL()
I have written a code for circular linkedlist. but I think the reverse part can be shorter so how to make the reverse part short ? and what are the alternative to do this ???
and can any one tell me when I am using the assignment operator for a object then that variable is pointing to that original object or the object copy is assign to the variable's memory location ??
There are still some issues in your code:
When the first node is added, that node's next reference is left to None, which means the list is not really circular. You should actually never have a node whose next reference is None, so I'd suggest to change the Node constructor so that it doesn't assign that value, but instead makes the node self referencing (self.next = self). That also means you can remove most of the None checks from your code.
The printCLL method fails when the list is empty. It should first check that condition.
You should not use is not when comparing with a literal. So instead do if count != 0: or even if count:
Some other remarks:
It is common practice to use PascalCase for class names, so Node instead of node and CircularLL instead of circularLL.
As in a circular, non-empty list the head node is always the one after the tail node, there is no real need to store a separate reference to the head node. You just need self.tail.
As the class name already clearly indicates that we're dealing with a circular linked list, there is no need to have the CLL suffix in the method names. And for a similar reason I'd call the insert method just insert.
Instead of providing a print method, it is probably better practice to provide a __repr__ method, which the native print function will call when it exists.
Make a linked list instance iterable by defining an __iter__ method. Then the above __repr__ can also rely on that.
As to the core of your question: yes this code for reversing a list can be greatly reduced. There is no need to have a counter.
Proposed code:
class Node:
def __init__(self,data):
self.data = data
self.next = self
class CircularLL:
def __init__(self):
self.tail = None
def insert(self, data):
newnode = Node(data)
if self.tail:
newnode.next = self.tail.next
self.tail.next = newnode
self.tail = newnode
def __iter__(self):
if not self.tail:
return
current = self.tail
while current.next is not self.tail:
current = current.next
yield current.data
yield current.next.data
def __repr__(self):
return "----".join(map(repr, self))
def reverse(self):
tail = self.tail
if not tail:
return
prev = tail
curr = prev.next
self.tail = curr
while curr != tail:
curr.next, prev, curr = prev, curr, curr.next
curr.next = prev
c = CircularLL()
c.insert(1)
print(c)
c.insert(2)
c.insert(3)
c.insert(4)
c.insert(5)
c.insert(6)
print(c)
c.reverse()
print(c)

Wrapper Class in Python for Linked List

I am absolutely new to Wrapper Classes in Python. I was trying to implement it in a program of linked list where multiple linked list are in use. My code is:
def nodewrap(cls):
class Nodewrap:
def __init__(self):
self.head = None
self.tail = None
return Nodewrap
#nodewrap
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Intersection:
def addnode(self,d):
newnode = Node(d)
if head == None:
head = tail = newnode
else:
tail.next = newnode
tail = newnode
obj1 = Intersection()
obj2 = Intersection()
obj3 = Intersection()
s1 = int(input("Enter size of 1st list : \n"))
for i in range(s1):
obj1.addnode(int(input("Enter the data : \n")))
s2 = int(input("Enter size of 1st list : \n"))
for i in range(s2):
obj2.addnode(int(input("Enter the data : \n")))
temp1 = obj1.head
for i in range(s1):
temp2 = obj2.head
for j in range(s2):
if temp1.data == temp2.data:
obj3.addnode(temp1.data)
break
temp2 = temp2.next
temp1 = temp1.next
print("Intersection is :")
temp = obj3.head
while temp!=None:
print(temp.data,end=" ")
temp = temp.next
I thought of using a wrapper class to wrap the class Node instead of using objects of the class Intersection only with data fields as head, tail. But it is giving me some sort of error with regards to init().
Please help.
I was trying to learn it from here:
https://www.geeksforgeeks.org/wrapper-class-in-python/
I think I understand what you want to do, but I think that you don't want to use a decorator, but you want to inherit from NodeWrap class
class Nodewrap:
head = None
tail = None
class Node(NodeWrap):
def __init__(self,data):
self.data = data
self.next = None
But I don't see any reason why to inherit this way. This should be enough, for a linked list. I have added is_first and is_last property
from __future__ import annotations
class Node:
prev_node = None
next_node = None
def __init__(self, data):
self.data = data
def add_node(self, node: Node) -> None:
if self.prev_node is not None:
raise ValueError('Previous node already defined.')
self.next_node = node
node.prev_node = self
#property
def is_first(self) -> bool:
return self.prev_node is None
#property
def is_last(self) -> bool:
return self.next_node is None
You can implement next, iter and create an Iterator class.
I don't recommend using next as the variable name.
from __future__ import annotations reference here. It's just for self reference annotation.

How to define and use a funciton outside a class?

In the following code for linked list implementation in Python3. How do I define and call the functions such as reverse() and display() outside of the class. Like, how should create a function that performs operations like display() and recerse(). How should I pass a LinkedList object and how to access its members, so that I am able to do desired operations?
PS : I removed other functions because I was not able to post this question.
I am not asking about importing the class file to use in other .py files.
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
curr = self.head
while curr != None:
print(curr.data + '->', end = ' ')
curr = curr.next
print('NULL')
def append(self, data):
'''
statements....
'''
def length(self):
ptr = self.head
count = 0
while ptr.next != None:
count += 1
ptr = ptr.next
print(count+1)
def reverse(self):
pre = None
cur = self.head
while cur != None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
self.head = pre
self.display()
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.prepend('E')
l.display()
not sure I'm understanding your question correctly, but if I am it seems that you just want to take all of the code, minus the program code (from "l=LinkedList()" down in your example), and save it to a python file, then at the top of any python code you need to use your class in, import your file.
If your class file is not in the same directory as the code from which you wish to use the class, you'll need to keep the class file in a directory in your path:
import sys
print(sys.path)
and if you wish to add a directory to your path, you can:
sys.path.append('<directory')
At that point, once you
import LinkedList
(assuming your class file is called LinkedList.py) you'll be able to define variables using your class and use it the same as you would in your example, so your code file would look something like:
import LinkedList
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.prepend('E')
l.display()
Or am I just not reading your question correctly?
I added the prepend and append method for you, I'm not sure if this is what you were referring to. Also, if you're looking for static vs class methods, you can check those out here: Class method vs static method in Python
With static methods you can return instances of a specified class by using arguments to the static method. Check out the link above to use class functions outside of their instances.
Here is the Python code:
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
curr = self.head
while curr != None:
print(curr.data + '->', end = ' ')
curr = curr.next
print('NULL')
def append(self, data):
data_node = Node(data)
data_node.next = self.head
self.head = data_node
def prepend(self, data):
ptr = self.head
while ptr.next != None:
ptr = ptr.next
ptr.next = Node(data)
def length(self):
ptr = self.head
count = 0
while ptr.next != None:
count += 1
ptr = ptr.next
print(count+1)
def reverse(self):
pre = None
cur = self.head
while cur != None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
self.head = pre
self.display()
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.prepend('E')
l.display()

Cant insert item at start of linked list - python

I'm currently learning about linked lists for a class and ran into trouble.
I have to be able to insert an item before a specified item so
(Apple,banana,pear)before pear would be (Apple,banana,newItem,pear)
and I managed this with this code:
def insert_before(head,data,location):
current = head
found = False
while not found:
if current.next.data == location:
new_node = Node(data)
new_node.next = current.next
current.next = new_node
found = True
else:
current = current.next
But my issue arose when trying to insert an item before the first item in the list, to try this I thought of doing it as such:
if head.data == location:
new_node = Node(data)
head.next = head.next
new_node.next = head`
But this doesn't seem to work. Any guides I found on here were to add an item AFTER the first item, any tips would be appreciated.
In the provided source code, the use of head.next = head.next do nothing and doesn't change the value of the head node.
To modify the value of the first node in a linked list by inserting a new node before, it is necessary update the head variable.
Solution 1 - assign the head as the returned value of the insert_before() function.
The variable previous is used to modify the node before and when is
= None, the first node must be modified.
def insert_before(head,data,location):
current = head
previous = None
found = False
while not found:
if (current != None):
if (current.data == location):
new_node = Node(data)
if (previous != None):
new_node.next = previous.next
previous.next = new_node
else:
new_node.next = head
head = new_node
found = True
else:
previous = current
current = current.next
else:
print('location ',location,' not found.')
break
return head
The use of the function becomes:
myhead = Node(5)
print(myhead.data) # >> 5
myhead = insert_before(myhead,3,5)
print(myhead.data) # >> 3
print(myhead.next.data) # >> 5
Solution 2 - use the OOP of Python by adding a headattribute in the Node class.
The OOP approach is quite similar, but instead of storing the head
node outside the function, the function insert_before() is added to
the class Node.
Step 1 - add in the class Node the attribute head.
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
self.head = self # store the first node
Step 2 - use the internal self.head instead of the head as parameter
In that case, when the new node shall be inserted before the first
node, the assignment is very simple self.head = new_node.
def Insert_Before(self,data,location):
current = self.head
previous = None
found = False
print('insert ',data,' before ',location)
while not found:
if (current != None):
if (current.data == location):
new_node = Node(data)
if (previous != None):
new_node.next = previous.next
previous.next = new_node
else:
new_node.next = self.head
self.head = new_node # update the first node
found = True
else:
previous = current
current = current.next
else:
print('location ',location,' not found.')
break
return
The use of the function becomes:
myhead = Node(5)
print(myhead.data)
myhead.insert_before(3,5)
print(myhead.head.data)
print(myhead.head.next.data)
Warning: instead of using myhead as the first node, use the
myhead.head attribute.

Resources