LinkedLists in python recursion
In Python default arguments are not expressions that are evaluated at runtime. These are expressions that are evaluated when the def
itself is evaluated. So for a class
usually when the file is read for the first time.
As a result, at that moment, there is no self
. self
is a parameter. So that is only available when you call the function.
You can resolve that problem by using for instance None
as default and perform a check. But here we can not use None
, since you already attached a special meaning to it. We can however construct a dummy
object, and use that one:
dummy = object()
def count(self, ptr=dummy):
if ptr is dummy:
ptr = self.head
if ptr == None:
return '0'
else:
return 1 + self.count(ptr.next)
Another problem with your code is that you return a string for zero. Since you can not simply add an integer and a string, this will error. So you should return an integer instead:
dummy = object()
def count(self, ptr=dummy):
if ptr is dummy:
ptr = self.head
if ptr == None:
return 0 # use an integer
else:
return 1 + self.count(ptr.next)