简体   繁体   中英

Recursive function in class error: “global name 'XXX' is not defined” in python 2.7 but works in python 3

I wrote a recursion function in Class, it works well in python 3 but does not work in python 2. I wonder how should I fix it in python 2

class Solution:
def jumpFloor(self, number):
    # write code here
    if number == 1 or number == 2:
        ways = number
        return ways
    elif number > 2:
        return jumpFloor(number-1) + jumpFloor(number-2)

test = Solution()
for i in range(8):
    print(test.jumpFloor(i))


#In python 3, the results are shown like:    
None
1
2
3
5
8
13
21

#But running the same code in python 2, it says:
global name 'jumpFloor' is not defined

Try calling self.jumpFloor() instead of simply jumpFloor() (and make sure your indentation is correct):

class Solution:

    def jumpFloor(self, number):

        if 1 <= number <= 2:
            return number

        if number > 2:
            return self.jumpFloor(number - 1) + self.jumpFloor(number - 2)

test = Solution()

for i in range(8):
    print(test.jumpFloor(i))

This works for me in both Python 2 and Python 3. The recursive routine seems incomplete in that it doesn't handle 0 (at least) let alone filter out negative numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM