jason
jason

Reputation: 2106

why "Function not Defined" error in recursive case?

I want to solve a reverse integer problem.

Here is my recursive function, why Python3 complains my function is not defined? any thoughts?

class Solution:
    def reverse(self, x: int) -> int:
        if x < 0:
            return -1 * reverse(self, x)
        if x // 10 == 0:
            return x
        if x % 10 == 0:
            return reverse(self, x // 10)
        else:
            return (x % 10) * 10 ** (len(str(x//10))) + reverse(self, x // 10)

I just follow the traditional recursive function.

Upvotes: 5

Views: 3605

Answers (4)

manik venkat
manik venkat

Reputation: 39

You should call reverse method by using self. And one more mistake is that you are passing self also as an argument, which is not required. so the correct version of your code is as follows:

class Solution:
def reverse(self, x: int) -> int:
    if x < 0:
        return -1 * self.reverse(x)
    if x // 10 == 0:
        return x
    if x % 10 == 0:
        return self.reverse(x // 10)
    else:
        return (x % 10) * 10 ** (len(str(x//10))) + self.reverse(x // 10)

Alternatively you can solve that without recursion also as follows.This method is very simple and small. all you need to do is convert integer to string and reverse the string and again type cast it to integer.

class Solution:
    def reverse(self, x: int) -> int:
        x = str(x)
        x = x[::-1]
        x = int(x)
        return x

Upvotes: 1

Noor
Noor

Reputation: 187

Your function should look like this:

class Solution:
    def reverse(self, x: int) -> int:
        if x < 0:
            return -1 * self.reverse(x)
        if x // 10 == 0:
            return x
        if x % 10 == 0:
            return self.reverse(x//10)
        else:
            return (x % 10) * 10 ** (len(str(x//10))) + self.reverse(x//10)

Upvotes: 1

T Tse
T Tse

Reputation: 846

Your reverse() is a method inside a class, and so it is not reachable by simply saying reverse in the code. You also do not need to supply the self into the method when you call it.

The answer by ShadowRanger gives instruction to how to fix it.

This answer should give you a closer look about the difference between unbound and bound methods: https://stackoverflow.com/a/11950080/8557739

I also recommend going through some basic tutorial for python classes.

Upvotes: 1

ShadowRanger
ShadowRanger

Reputation: 155505

Methods need to be called recursively via self; the class/instance's scope is only accessible explicitly via self (or the class name itself), not implicitly via nested scope. Change all uses of reverse(self, ...) to self.reverse(...) and it will work.

You could do Solution.reverse(self, ...), but that's needlessly repeating the class name over and over, and it'll be slower than just calling self.reverse directly anyway.

Upvotes: 7

Related Questions