I wrote the program below in Python for question 509 on LeetCode, which asks the user to write a program to find the value of the nth number in the Fibonacci sequence:
class Solution(object):
def fib(self, n):
output = 0
if n == 0:
output = 0
elif n == 1:
output = 1
else:
output = fib(n-1) + fib(n-2)
return(output)
I was then met with this error:
NameError: global name 'fib' is not defined
output = fib(n-1) + fib(n-2)
Line 9 in fib (Solution.py)
ret = Solution().fib(param_1)
Line 30 in _driver (Solution.py)
_driver()
Line 40 in <module> (Solution.py)
I then took a look at all the solutions posted and I noticed that all the solutions that utilized linear recursion had one thing in common: They all used self.
as a prefix before calling the fib()
function in the body of the initial function. As such, I changed my solution to:
class Solution(object):
def fib(self, n):
output = 0
if n == 0:
output = 0
elif n == 1:
output = 1
else:
output = self.fib(n-1) + self.fib(n-2)
return(output)
The error was gone and LeetCode accepted my submission.
The weird thing is that I ran the initial code without self.
in an IDE, and there was no runtime error; the program was working.
Why did I have to use .self
in order to get rid of the runtime error on LeetCode?
Ryan Gosling is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.