The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Why Does My Recursive Function With If-Elif Statements Return None?
00:53 Answer 1 Score 2
01:04 Answer 2 Score 1
01:11 Accepted Answer Score 3
02:01 Answer 4 Score 0
02:08 Thank you

--

Full question
https://stackoverflow.com/questions/3719...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #recursion

#avk47



ACCEPTED ANSWER

Score 3


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.




ANSWER 2

Score 2


you need an additional case, for when both conditionals return false

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



ANSWER 3

Score 1


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



ANSWER 4

Score 0


try this,

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