I'm working on a set of code where I have to turn a loop into a recursive function and the professor has not been able to help nor my friends I've reached out to. The loop function is this:
def __str__(self):
""" Returns a string representation of the list with a space between each item.
Precondition: none
Postcondition: Returns a string representation of the list with a space between each item.
"""
resultStr = "(head)"
current = self._head
while current != None:
resultStr += " " + str(current.getData())
current = current.getNext()
return resultStr + " (tail)"
The recursive function I have typed so far is this:
def __str__(self):
""" Returns a string representation of the list with a space between each item.
Precondition: none
Postcondition: Returns a string representation of the list with a space between each item.
"""
def strHelper(current):
if current != None:
str(current.getData()) + " " + strHelper(current.getNext())
else:
return ""
# Start of __str__ method execution by passing pointer to first node in list
return "(head) " + strHelper(self._head) + "(tail)"
The professor basically said, "This should work!" but I still get a TypeError reading "can only concatenate str (not "NoneType") to str" on the final return line. What do I do?
"something" + None + "some other thing"... check if the things in your stringconcattenation are None and avoid concatting them in that case...ifcase instrHelperdoesn't do anything, since you forgot thereturnkeyword.strHelperreturns eitherNone(after computing and discarding astrvalue) or the empty string.