question : complete an UnorderedList class using the node class below. append: a
ID: 3902969 • Letter: Q
Question
question : complete an UnorderedList class using the node class below.
append: adds data to the list
__len__ : returns the length of the list
__getitem__ : returns the data of the index given
__setitem__ : changes (or sets) the data at the index given
__str__ : returns the list as a string
class Node: def init-data): _init-(self, self.data - init data self, next = None def get_data(self): def get_next(self): def set_data(self, new_data): def set_next (self, new next): return self.data return self.next self.data = new data self.next new next class UnorderedList: def init(self): self.head -None def is_empty(self): return sel f . head : None def append (self, item): # Code Here def-len-(self): # Code Here def getitem (self,key): def setitem (self,key, item): def-str-(self): # Code Here # Code Here # Code HereExplanation / Answer
def append(self,item):
n = Node(item)
p = self.head
if p == None:
self.head = n
else:
while p.get_next() != None:
p = p.get_next()
p.set_next(n)
def __len__(self):
if self.head == None:
return 0
count = 0
p = self.head
while p != None:
p = p.get_next()
count = count + 1
return count
def __getitem__(self,key):
if self.head == None:
return None
count = 0
p = self.head
if key == 0: //index starts with 0
return p.get_data()
while count < key :
p = p.get_next()
count = count + 1
if p != None:
return p.get_data()
return None
def __setitem__(self,key,item):
if self.head == None:
return
count = 0
p = self.head
if key == 0: //index starts with 0
return p.get_data()
while count < key :
p = p.get_next()
count = count + 1
if p != None:
p.set_data(item)
def __str__(self):
p = self.head
str1 = ""
while p != None :
str1 = str1 + p.get_data()
return str1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.