I have to set a method that returns a string from the content of a given object. I am able to make the string of the list of numbers but my professor wants the separator between each element to be a semicolon instead of a comma, which I am having trouble doing. I tried using the join function but I then realized that my professor does not want to use any list operations like len
or in
besides append and reading and writing to an index .
I have already tried to concatenate the semicolon to the string but of course, that only concatenates the semicolon at the end of the string and doesn't separates each element with a semicolon.
Here is my code
class LinkedList:
def __init__(self, lst=[], size = 0):
self.L = lst
self.size = size
def addLast(self, x):
self.L.append(x)
self.size += 1
def removeFirst(self):
L = self.L
p = L[1:]
return p
def __str__(self):
result = ''
result += str(self.L)
return result
Using this as a test case, you can see that it prints out as [1, 2, 3] instead of "[1;2;3]"
lst = LinkedList()
print(lst) # prints []
print(lst.size) # prints 0
lst.addLast(1)
lst.addLast(2)
print(lst.size) # prints 2
lst.addLast(3)
print(lst) # this should print "[1;2;3]"
Use a loop to concatenate the list elements, appending ;
between each.
def __str__(self):
result = '['
if self.size > 0:
result += str(self.L[0]) # print first element normally
for item in self.L[1:]: # print the rest, preceding each with ';'
result += ';' + str(item)
result += ']'
return result
If you're not allowed to use for-in
, you can use a while
loop.
def __str__(self):
result = '['
if self.size > 0:
result += str(self.L[0]) # print first element normally
i = 1
while i < self.size
result += ';' + str(self.L[i])
i += 1
result += ']'
return result
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments