为什么我的带有 if-elif 语句的递归函数返回 None? [英] Why does my recursive function with if-elif statements return None?

查看:43
本文介绍了为什么我的带有 if-elif 语句的递归函数返回 None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在努力学习 Python,但在递归函数方面遇到了一些障碍.在 Think Python 中,练习之一是编写一个函数来确定数字 a 是使用以下定义的数 b 的幂:

I'm currently trying to wrap my head around learning Python and I've come to a bit of a stall on recursive functions. In Think Python, one of the exercises is to write a function that determines if number a is a power of number b using the following definition:

"一个数 a 是 b 的幂,如果它可以被 b 整除,a/b 是 b 的幂.编写一个名为 is_power 的函数,它接受参数 a 和 b,如果 a 是 a 的幂,则返回 Trueb."

"A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b."

我函数的当前状态是:

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

print isPower(num1,num2)

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

As it is, this produces the result I expect. However the chapter is focused on writing recursive functions to reduce redundancy and I'm not quite sure how I can turn the final "(a/b) % b == 0" into a recursion. I've attempted:

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

但这只会返回 None.

But that just returns None.

递归这个函数的正确方法是什么?

What is the proper way to recurse this function?

推荐答案

当 a == 1 时,您忘记了基本情况:

You are forgetting a base case, when 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,则您将得到除以零.

However this has some other problems - if a is 0 then it will never finish and if b is 0 then you will get a divide-by-zero.

这是一个详细的解决方案,据我所知适用于所有整数组合:

Here is a verbose solution that as far as I can tell will work for all integer combinations:

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 均为负数的情况.我现在正在比较它们的绝对值.

My code didn't work for cases when both a and b are negative. I'm now comparing their absolute values.

我傻了,x^0 == 1,所以 a == 1 应该总是返回 true.这也意味着我不必在递归之前将 a 与 b 进行比较.谢谢@Javier.

Silly me, x^0 == 1, so a == 1 should ALWAYS return true. That also means I don't have to compare a to b before the recursion. Thanks @Javier.

这篇关于为什么我的带有 if-elif 语句的递归函数返回 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆