Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

python - Why does my recursive function with if-elif statements return None?

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 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."

The current state of my function is:

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

print isPower(num1,num2)

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

But that just returns None.

What is the proper way to recurse this function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

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

EDIT2: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...