我在Class中编写了一个递归函数,它在python 3中很好用,但在python 2中不起作用。我想知道如何在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
答案 0 :(得分:0)
尝试调用self.jumpFloor()
而不是简单地调用jumpFloor()
(并确保缩进正确):
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))
这对我在Python 2和Python 3中都有效。递归例程似乎不完整,因为它不能处理0(至少),更不用说过滤掉负数了。