class Node(object):
def __init__(self, data = None, next = None):
self.data = data
self.next_node = next
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList(object):
def __init__(self, head = None):
self.head = head
def insert(self, data):
new_node = Node(data, None)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def print_list(self):
temp = self.head
while temp!=None:
print(temp.data)
if temp.next != None:
temp = temp.next
s = LinkedList()
s.insert(3)
s.insert(4)
s.insert(5)
s.insert(6)
s.print_list()
I always get this Node object has no attribute next in the console. It prints the linkedlist but how do I get rid of that warning. What extra condition should I put?
In LinkedList, you keep accessing the node’s next node using the property name next but in the Node type, you actually defined the next pointer to be called next_node.
So either change the Node definition so the pointer is just called next, or change the usages in LinkedList to refer to node.next_node instead of just node.next
Related
Intuitively, using __iter__ and __next__ seems likely to be significantly for efficient, but I curious of the technical specifics of why, and how one maybe go about benchmarking to measure and compare the space and runtime of these?
A common case I can think of is a Linked List,
The following is an implementation illustration the use of __iter__ and __next__:
I have tried various benchmarking tools without much success being able to generate data to more closely analyze they're internals; specifically, how exactly the magic methods function, and if they're truly as significantly more efficient as I surmise they are.
class Node(object):
def __init__(self, value: int, next_node):
self.value = value
self.next = next_node
def __repr__(self):
return str(self.value)
class LinkedList(object):
def __init__(self, head=None):
self.head = None
self._current = None
def __repr__(self):
return '<{} {}>'.format(type(self).__name__, self.head)
def __iter__(self):
self._current = self.head
return self
def __next__(self):
if self._current is None:
raise StopIteration
current, self._current = self._current, self._current.next
return current
#property
def is_empty(self):
return self.head is None
def prepend_node(self, valuetoadd: int):
self.head = IntNode(valuetoadd, self.head)
Compared to the following:
class ListNode:
"""
A node in a singly-linked list.
"""
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __repr__(self):
return repr(self.data)
class SinglyLinkedList:
def __init__(self):
"""
Create a new singly-linked list.
Takes O(1) time.
"""
self.head = None
def prepend(self, data):
"""
Insert a new element at the beginning of the list.
Takes O(1) time.
"""
self.head = ListNode(data=data, next=self.head)
def find(self, key):
"""
Search for the first element with `data` matching
`key`. Return the element or `None` if not found.
Takes O(n) time.
"""
curr = self.head
while curr and curr.data != key:
curr = curr.next
return curr # Will be None if not found
def remove(self, key):
"""
Remove the first occurrence of `key` in the list.
Takes O(n) time.
"""
# Find the element and keep a
# reference to the element preceding it
curr = self.head
prev = None
while curr and curr.data != key:
prev = curr
curr = curr.next
# Unlink it from the list
if prev is None:
self.head = curr.next
elif curr:
prev.next = curr.next
curr.next = None
Can someone explain how are we able to access value in class DoublyLinkedList even when it is an attribute of class Node.
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self, value):
new_node = Node(value)
self.head = new_node
self.tail = new_node
self.length = 1
def print_list(self):
temp = self.head
while temp is not None:
print(temp.value)
temp = temp.next
Pls look temp.value of print_list function
I have used a class for a program I have been working on. Unfortunately, I am struggling to return the value instead of the object memory location.
class Node:
def __init__(self, data):
self.data = data
class BinaryTree:
root = None
#classmethod
def InsertNode(cls, data):
newNode = Node(data)
if cls.root == None:
cls.root = newNode
return cls.root
else:
queue = []
queue.append(cls.root)
print(BinaryTree().InsertNode(4))
would return -> <__main__.Node object at 0x000001A8478CAE60>
I have a LinkedList class that has close to 200 lines of code. I would like to make a new class LLCircular(LinkedList) by always making sure that any myLL.tail.next is myLL.head. I believe I would need to update append(), push(), remove(), etc. accordingly. Is there a way I can do this to keep the original LinkedList class intact? Maybe a decorator or some dunder method?
For brevity's sake, if reading the code, my push() method is just the inverse of append(). I also have a pop() and remove() method, which would need to be updated, if I just rewrite those methods. As I am trying to avoid that approach, I am not posting that part of the code.
class LinkedListNode:
def __init__(self, value, nextNode=None, prevNode=None):
self.value = value
self.next = nextNode
self.prev = prevNode
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self, values=None):
self.head = None
self.tail = None
if values is not None:
self.append(values)
def __str__(self):
values = [str(x) for x in self]
return ' -> '.join(values)
def append(self, value=None):
if value is None:
raise ValueError('ERROR: LinkedList.py: append() `value` PARAMETER MISSING')
if isinstance(value, list):
for v in value:
self.append(v)
return
elif self.head is None:
self.head = LinkedListNode(value)
self.tail = self.head
else:
''' We have existing nodes '''
''' Head.next is same '''
''' Tail is new node '''
self.tail.next = LinkedListNode(value, None, self.tail)
self.tail = self.tail.next
if self.head.next is None:
self.head.next = self.tail.prev
return self.tail
'''class LLCircular(LinkedList):'''
''' ??? '''
Test Code:
foo = LinkedList([1,2,3])
foo.tail.next = foo.head #My LL is now circular
cur = foo.head
i = 0
while cur:
print(cur)
cur = cur.next
i +=1
if i>9:
break
What you want is to call your LinkedList base class functions using the super keyword, and then add the slight modifications to the LLCircular class function, i.e:
class LLCircular(LinkedList):
def append(self, value=None):
super(LLCircular, self).append(value)
# In addition to having called the LinkedList append, now you want
# to make sure the tail is pointing at the head
self.tail.next = self.head
self.head.prev = self.tail
If it is "circular" it won't need a tail or head, would it?
Nor "append" makes sense - insert_after and insert_before methods should be enough - also, any node is a reference to the complete circular list, no need for different objects:
class Circular:
def __init__(self, value=None):
self.value = value
self.next = self
self.previous = self
def insert_after(self, value):
node = Circular(value)
node.next = self.next
node.previous = self
self.next.previous = node
self.next = node
def insert_before(self, value):
node = Circular(value)
node.next = self
node.previous = self.previous
self.previous.next = node
self.previous = node
def del_next(self):
self.next = self.next.next
self.next.previous = self
def __iter__(self):
cursor = self.next
yield self
while cursor != self:
yield cursor
cursor = cursor.next
def __len__(self):
return sum(1 for _ in self)
I have the following Linked List implementation. There is a problem with the printlist() function. The while loop is turning an error that there is no attribute next for self. Is there a better way to write this function? Thank you!!!
class Node:
def __init__(self, data, next=None):
self.data=data
def _insert(self, data):
self.next=Node(data)
def _find(self, data):
if self.data==data:
return self
if self.next is None:
return None
while self.next is not None:
if self.next.data==data:
return self.next
return None
def _delete(self, data):
if self.next.data == data:
temp=self.next
self.next =self.next.next
temp=None
def _printtree(self):
while self:
print self.data,
self=self.next
class LinkedList:
def __init__(self):
self.head=None
def insert(self, data):
if self.head:
self.head._insert(data)
else:
self.head=Node(data)
def find(self, data):
if self.head.data==data:
return self.head
return self.head._find(data)
def delete(self, data):
if self.head.data==data:
head=None
return
self.head._delete(data)
def printtree(self):
self.head._printtree()
add next attribute to Node's ini method
you should define printtree of LinkedList this way:
def printree(self):
current_node = self.head
print current_node.data
while current_node.next is not None:
print current_node.next.data
current_node = current_node.next
adding a repr method will make your code nicer