Joel Ulens3,101 Points
I am honestly completely stuck. How do i fix this?
So I have tried this on an IDE to see which error it gives and it gives, this error: File "python", line 1, in <module> File "python", line 4, in len File "python", line 4, in len File "python", line 4, in len [Previous line repeated 328 more times] RecursionError: maximum recursion depth exceeded while calling a Python object
I have tried multiple different methods and none of them work
class Liar(list): def __len__(self): super().__len__() self = len(self) return self*2
The biggest issue with your current code is that you call
__len__ method you are currently writing is the method that gets called when
len is called on an object. That means that by calling
len(self) inside of
__len__ you end up with an infinite loop of the
__len__ method calling itself over and over.
You don't really need to do anything to the
self parameter in this method. When you call
super().__len__() you are calling the original
__len__ method, which means that whatever number that method returns is the real length of the object. Once you know the real length you can simply add some random number to that, and you will end up with a lying
Like this for example:
class Liar(list): def __len__(self): return super().__len__() + 2 # Take what the original len functions returns and add 2
It doesn't really matter what number you add to it, as long as it causes your custom
__len__ method to return a different number than the original
It's worth mentioning that while the number you use does not matter you do need to use addition, not subtraction, multiplication or division. This is due to the fact that the challenge sends you a list that is actually empty. That means that the original
__len__ function returns 0. Subtracting from 0 will result in a negative number which is an invalid value for
__len__ to return. And multiplying or dividing with 0 as the starting number always results in 0 being the result, which means the function would not actually be lying about the length.