为什么我的递归函数返回None?

时间:2010-09-15 16:46:50

标签: python recursion

我目前正在尝试围绕学习Python,并且我在递归函数上有点拖延。在Think Python中,其中一个练习是编写一个函数,使用以下定义确定数字 a 是否为数字 b 的幂:

  

“数字a是b的幂,如果它可以被b整除,而a / b是b的幂。写一个名为is_power的函数,它接受参数a和b,如果a是一个幂,则返回True b“。

我的功能的当前状态是:

def isPower(a,b):
    return a % b == 0 and (a/b) % b == 0

print isPower(num1,num2)

实际上,这会产生我期望的结果。然而本章的重点是编写递归函数以减少冗余,我不太确定如何将最终的“(a / b)%b == 0”转换为递归。我试过了:

def isPower(a,b):
    if a % b != 0:
        return False
    elif isPower((a/b),b):
        return True

但这只是返回无。

递归此功能的正确方法是什么?

7 个答案:

答案 0 :(得分:3)

当a == 1:

时,您忘记了基本情况
def isPower(a,b):
    if a == 1:
        return True
    if a % b != 0:
        return False
    elif isPower((a/b),b):
        return True
    else
        return False

然而,这有一些其他问题 - 如果a为0则它永远不会完成,如果b为0则会得到除以零。

这是一个冗长的解决方案,据我所知,它将适用于所有整数组合:

def isPower(a,b):
    if a == 0 or b == 0:
        return False
    def realIsPower(a, b):
        if a == 1:
            return True
        elif a%b != 0:
            return False
        elif realIsPower((a/b), b):
            return True
        else:
            return False
    return realIsPower(a, b)

编辑:我的代码不适用于a和b均为负数的情况。我现在正在比较它们的绝对值。

EDIT2:傻我,x ^ 0 == 1,所以a == 1应该总是返回true。这也意味着我不必在递归之前比较a到b。谢谢@Javier。

答案 1 :(得分:2)

当两个条件都返回false时,你需要一个额外的案例

def isPower(a,b):
    if a % b != 0:
        return False
    elif isPower((a/b),b):
        return True
    else
        return False

答案 2 :(得分:1)

def isPower (a,b):
    return a==1 or (a!=0 and b!=0 and b!=1 and isPower((a/b),b))

答案 3 :(得分:1)

这是我的代码。从我测试的,它的工作原理:

def ispower(a, b):

    if b == 1 or b == 0:
        return False
    if b <= 0 or a <= 0:
        return False
    if a % b == 0:
        if ((a / b) / b) == 1:
            return True
        else:
            return ispower(a / b, b)
    else:
        return False
        print ispower(-10, 2)

答案 4 :(得分:0)

试试这个,

def ispower(a,b):
  if b==a:
    return True
  elif a<b:
    return False
  else:
    return ispower(a*1.0/b, b)

答案 5 :(得分:0)

def is_power (a, b):

    if a == 1:
        return True
    if a == 0 and b == 0:
        return True
    if a == 0 or b == 0:
        return False
    if a%b != 0:
        return False
    elif is_power ((a/b), b):
        return True

答案 6 :(得分:0)

这是我的答案,它有点清洁:

def is_power(a, b):
    if a == 1:
        return True
    if a == 0 or b == 0:
        return False
    if a % b == 0 and is_power(a/b, b):
        return True
    else:
        return False
相关问题