I have a problem with the code. The code gives an error and it says that Node does not have a "previous" in the __add__() operator however it doesnt give an error in the main program
The point of the assignment is to create a long using linked list
class Node():
def __init__(self):
self.next = None
self.prev = None
self.data = None
def getData(self):
return self.data
class LinkedList():
def __init__(self):
self.count = 0
self.last = Node()
self.first = Node()
self.first.next = self.last
self.last.previous = self.first
def append(self, data):
self.last.data = data
self.last.next = Node()
tmp = self.last
self.last = self.last.next
self.last.previous = tmp
self.count += 1
def prepend(self, data):
self.first.data = data
self.first.previous = Node()
tmp = self.first
self.first = self.first.previous
self.first.next = tmp
self.count += 1
def front(self):
if self.count == 0: return None
return self.first.next
def back(self):
if self.count == 0: return None
return self.last.previous
def size(self):
return self.count
def __getitem__(self, node):
count = self.first
while count.data:
if count.data == node:
return count
count = count.next
return None
def __iter__(self):
count = self.first.next
while count.data:
print("here")
yield count.data
count = count.next
class BigInt:
def __init__(self, initValue = "0"):
self.data = LinkedList()
for count in initValue:
self.data.append(count)
self.Neg = False
def __repr__(self):
integer = ""
node = self.data.front()
while node.next:
integer= integer+(node.getData())
node = node.next
return "".join(integer)
def toString(self):
return self.__repr__()
def isNeg(self):
return self.Neg
def __add__(self, rhs):
node1 = self.data.back()
node2 = rhs.data.back()
if self.isNeg() and not rhs.isNeg():
return rhs - self
elif rhs.isNeg() and not self.isNeg():
return self - rhs
summation = LinkedList()
carryOne = 0
print(node1.previous.previous.getData())
while node1.previous.getData() is not None or node2.previous.getData() is not None:
tot = int(node1.getData())+int(node2.getData())+carryOne
summation.prepend((tot)%10)
carryOne = 0
if tot >= 10: carryOne = 1
node1 = node1.previous
node2 = node2.previous
ret = ""
for digit in summation:
ret = ret + digit
print(digit)
print (ret)
def __sub__():
pass
a = LinkedList()
a.prepend(4)
a.prepend(5)
a.append(23)
print (type(a.back()))
print(a.back().previous.previous.getData())
g = BigInt("2")
h = BigInt("3")
(g+h)
print (g.toString())
There's no previous member in a newly-constructed Node, only prev.
Some instances of Node will later acquire a member called previous. This is due to code like:
self.last.previous = self.first
(Thanks to #David Robinson for pointing that out.)
Related
i have created Single Linked List in python and i want to know what '()' mainly functions in def delete_front(self).
Here is my Code.
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class SLinkedList(object):
def __init__(self):
self.head = None
self.size = 0
def size(self):
return self.size
def is_empty(self):
if self.size==0:
return True
else:
return False
def search(self,target):
return
def insert_front(self, data):
nw_node = Node(data)
if self.is_empty():
self.head = nw_node
else:
nw_node.next = self.head.next
self.head.next = nw_node
#p is pointer
def insert_after(self, data, p):
nw_node = Node(data)
if p==self.size:
p.next = nw_node
else:
nw_node.next = p.next
p.next = nw_node
def delete_front(self):
if is_empty():
return None
else:
tmp_node =self.head.next
tmp_node.prev = self.head
self.head.next = tmp_node.next
def delete_after(self, p):
if p==self.size:
return None
else:
tmp_node = p.next
p.next = tmp_node.next
def print_list(self):
node = self.head
while node:
print(node)
node = node.next
So this is the node part of a singly linked list. I am not supposed to change the way it has been coded, but I dont know how this type of structure would work. Self.link cannot event be accessed to point towards another part of the list. Does anyone know how to work with such a Node class?
class Node:
def __init__(self, inval=None):
self.val = inval
if inval==None:
self.link = self
print (self)
def __str__(self):
if self.val == None:
return ''
else:
return str(self.val)
def __repr__(self):
return str(self)
Here is another implementation of the linked list, which has a slightly different styled node.
class LinkedList:
lock = 0
if lock == 0:
tempdata = None
def __init__(self, *args):
self.head = Node() # Node at the head of the list
self.current = None # Node currently pointed to by the iterator
self.count = 0
def insert(self, value):
NewNode =Node(value)
NewNode.link = self.head
self.head = NewNode
self.count += 1
def __iter__(self):
self.current = self.head
return self
def __next__(self):
self.current = LinkedList.tempdata
if LinkedList.lock == 0:
self.current = self.head
LinkedList.lock += 1
else:
pass
if self.current.value == None:
LinkedList.lock = 0
raise StopIteration
previous = self.current
self.current = self.current.link
LinkedList.tempdata = self.current
return previous
def __str__(self):
result = ''
self.current = self.head
while self.current.value is not None:
if self.current.link.value is None:
result += str(self.current.value)
else:
result += str(self.current.value) + ' -> '
self.current = self.current.link
return result
def search(self, value):
found = 0
temp = None
out= False
while found == 0:
try:
temp = LinkedList.__next__(self)
if temp.value == value:
found += 1
out = temp
except StopIteration:
pass
return out
def delete(self, value):
print ("hwta")
found = 0
temp = None
head = self.head
if head.value == value:
print ("Head")
if head.link.value != None:
self.head = head.link
else:
self.head = Node()
else:
while found == 0:
try:
temp = LinkedList.__next__(self)
if temp.link.value == value:
if temp.link.link.value == None:
temp.link = Node()
break
else:
temp.link = temp.link.link
print ("tails")
break
except StopIteration:
pass
def __repr__(self):
return str(self)
#a = Node()
#print(a) # 3
#b = Node("Hullo")
#print(b) # 'Hullo'
#lst = LinkedList()
#lst.insert(2)
#lst.insert(3)
#lst.insert(5)
#lst.insert(6)
#lst.insert(7)
#lst.insert(6)
#print(lst) # 5 -> 3 -> 2
#c = lst.search(2)
#print(c) # 3
#print(c.link) # 5
#lst.insert(2)
#print(lst.head.link.link) # 3
lst.delete(6)
print (lst)
#print(next(lst)) # should print 5, 3, 2 on separate lines
#lst.delete(2)
#print(lst) # 5 -> 3
#print(len(lst)) # 2
#for u in lst:
# print(u)
Nothing in the Node implementation that would prevent you from using it in a List class. Just pretend that the final three lines of Node.__init__() don't exist.
Here is one way to use the professor's Node in your List.
class Node:
def __init__(self, inval=None):
self.val = inval
if inval==None:
self.link = self
print (self)
def __str__(self):
if self.val == None:
return ''
else:
return str(self.val)
def __repr__(self):
return str(self)
class List:
def __init__(self):
self.head = None
def prepend(self, val):
head = Node(val)
head.link = self.head
self.head = head
def append(self, val):
if self.head is None:
self.prepend(val)
else:
p = self.head
while p.link is not None:
p = p.link
p.link = Node(val)
p.link.link = None
def __str__(self):
result = '<'
p = self.head
while p is not None:
result += str(p) + ', '
p = p.link
result += '>'
return result
l = List()
l.append(3)
l.prepend(2)
l.append(4)
l.prepend(1)
l.append(5)
print(str(l))
And here is the result:
<1, 2, 3, 4, 5, >
class UnorderedList:
def __init__(self):
self.head = None
def __str__(self):
item = self.head
items = list()
while item:
items.append(str(item.get_data()))
item = item.get_next()
return '[' + ' '.join(items) + ']'
def add(self, item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
def get(self, index):
item = self.head
length = item.size()
string1 = " "
for index in range[0, length -1, -1]:
string1 += index
And the test is: Will give me 7
my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
my_list.add(x)
print(my_list.get(1))
I need to write my def get(self, index) function so it returns the value of the index starting from the end.
How would I do this?
You could try this:
for index in range[0, length -1, -1]:
string1 += (length - 1) - index
Suppose your class Node:
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self,newdata):
self.data = newdata
def set_next(self,newnext):
self.next = newnext
def __str__(self):
return str(self.data)
Change your class UnorderedList (this is linked list):
1, if you want to get the size of the linked list, add function size
2, your range function is not correct, pls refer to official doc, should be like range(length -1, 0, -1)
3, for linked list, the feature is to get the element not by the index, you can search and get element until you find the specific element, see below function get
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def __str__(self):
item = self.head
items = list()
while item:
items.append(str(item.get_data()))
item = item.get_next()
return '[' + ' '.join(items) + ']'
def add(self,item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def get(self,item):
current = self.head
found = False
string1=""
while current != None and not found:
string1 += str(current)
if current.get_data() == item:
found = True
else:
current = current.get_next()
return string1
Test:
my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
my_list.add(x)
print my_list.get(4)
It will add all element to be a linked list my_list, then you can get all element till 4 is found, the output will be:
8764
I am trying to use BFS to search through a tree with three letter words and find the way in between a given start and end word and print the way in between. The printing is supposed to be done with a recursive function.
I keep getting this error:
RecursionError: maximum recursion depth exceeded while calling a Python object
and an infinite loop with the endword can anyone see whats wrong? (I copied my imported classes as well).
from array import array
class Node1:
#håller koll på värdena
def __init__(self, data, next = None):
self.data = data
self.next = next
def __str__(self):
if self.data.parent == None:
return None
else:
print(self.data.parent)
return str(self.data.parent)
def __str__(self):
return str(self.data.word)
class Queue:
def __init__(self):
self.first = None
self.last = None
def enqueue(self,x):
"""Stoppar in x sist i kön """
x = Node1(x)
if self.first == None: # Om kön är tom
self.first = self.last = x
else: # om kön inte är tom
self.last.next = x
self.last = x
def dequeue(self):
first = self.first
self.first = self.first.next
#if self.first == None:
# self.last=None
return first
def isEmpty(self):
if self.first == None:
xx = True
else:
xx = False
#print('I IsEmpty: Första elementet i listan:',self.first)
#print('I IsEmpty: Sista elementet i listan:',self.last)
return xx
def __str__(self):
node=self.first
node_strang = 'Efter trolleriet får man: '
while node != None:
node_strang += str(node)
node = node.next
return node_strang
class Node:
'''Nodklass med rekursiva metoder som anropas i Bintree-klassen'''
def __init__(self, word):
self.word = word
self.left = None
self.right = None
def insert(self, new_word):
if self.word == new_word:
return False
elif new_word < self.word:
if self.left:
return self.left.insert(new_word)
else:
self.left = Node(new_word)
return True
else:
if self.right:
return self.right.insert(new_word)
else:
self.right = Node(new_word)
return True
def find(self, new_word):
if self.word == new_word:
return True
elif new_word < self.word:
if self.left:
return self.left.find(new_word)
else:
return False
else:
if self.right:
return self.right.find(new_word)
else:
return False
def preorder(self):
if self:
print(self.word)
if self.left:
self.left.preorder()
if self.right:
self.right.preorder()
def postorder(self):
if self:
if self.left:
self.left.postorder()
if self.right:
self.right.postorder()
print(self.word)
def inorder(self):
if self:
if self.left:
self.left.inorder()
print(self.word)
if self.right:
self.right.inorder()
from linkedQFile import Queue,Node1
from bintreeFile import Node
import string
class Bintree:
def __init__(self):
self.root = None
def put(self, new_word):
if self.root:
return self.root.insert(new_word)
else:
self.root = Node(new_word)
return True
def __contains__(self, new_word):
if self.root:
return self.root.find(new_word)
else:
return False
class ParentNode:
def __init__(self, word, parent = None):
self.word = word
self.parent = parent
def maketree():
svenska = Bintree()
gamla = Bintree()
with open('word3.txt', 'r') as ordfil:
for rad in ordfil:
ord = rad.strip()
if ord in svenska:
gamla.put(ord)
svenska.put(ord)
ordfil.close()
return svenska,gamla
def writechain(kidzen, paronen):
if paronen is not None:
print(kidzen)
writechain(kidzen, paronen)
else:
pass
def countchain(barn_obj):
if barn_obj.parent==None:
return 0
else:
return 1+countchain(barn_obj.parent)
def makechildren(nod, q, gamla, svenska):
for i in range(3):
bokstavslista = list(nod.data.word)
alfabetslista = list(string.ascii_lowercase) + ['å', 'ä', 'ö']
for bokstav in alfabetslista:
bokstavslista[i] = bokstav
barn = ''.join(bokstavslista)
if barn in svenska:
barn_obj = ParentNode(barn, nod.data)
#print('parent to', barn, 'is', str(barn_obj.parent))
if barn not in gamla:
#print("i makechildren: barn = ", barn)
q.enqueue(barn_obj)
gamla.put(barn_obj.word)
def main():
(svenska,gamla) = maketree()
q=Queue()
start = input('Startord:')
slut = input('Slutord:')
startord= ParentNode(start, parent=None)
q.enqueue(startord)
while not q.isEmpty():
nod = q.dequeue()
makechildren(nod, q, gamla, svenska)
nod_for=nod.data
kidzen=nod_for.word
paronen=nod_for.parent
#print ('word =', kidzen)
#print ('parent =', paronen)
if q.isEmpty():
print('Det finns ingen väg till', slut)
break
elif kidzen==slut:
writechain(kidzen, paronen)
print('Det finns en väg till', slut)
break
main()
In your writechain function you are not walking a tree.
You keep recursively calling it with the same arguments. That will continue until you reach the recursion limit.
I've created a list using only the Node class
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
def __str__(self):
return str(self.data)
I've intialized the list and the last Node is None.
I'm trying to delete this node but don't know how to?
One good way to do this is to keep track of the previous node and the current node, and then when you reach the end of the list, set the next of the previous to None.
prev = None
cur = head
while cur.next is not None:
prev = cur
cur = cur.next
if prev: #in case the head is the tail
prev.next = None
You'll probably want a List class to manage your nodes.
class List:
def __init__(self):
self._nodes = None
def push(self, node):
node.set_next(self._nodes)
self._nodes = node
return self
def pop(self):
if self._nodes is None:
return None
temp = self._nodes
self._nodes = temp.get_next()
return temp
def __len__(self):
l = 0
n = self._nodes
while n is not None:
n = n.get_next()
l += 1
return l
def remove(self, node):
n = self._nodes
p = None
while n is not None:
if n is node:
p.set_next(n.get_next())
n.set_next(None)
return True
p = n
n = n.get_next()
return False
def del_from_end(self):
if self.head is None:
return "No node to delete"
else:
current = self.head
while current.next.next is not None:
current = current.next
current.next = None
Add this method in your linked list class which would look like
class LinkedList():
def __init__(self, head=None):
if head == "" or head is None:
self.head = None
else:
self.head = Node(head)