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

后端 未结 7 977
小蘑菇
小蘑菇 2020-12-07 03:23

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 f

相关标签:
7条回答
  • 2020-12-07 03:30

    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.

    0 讨论(0)
  • 2020-12-07 03:34
    def isPower (a,b):
        return a==1 or (a!=0 and b!=0 and b!=1 and isPower((a/b),b))
    
    0 讨论(0)
  • 2020-12-07 03:35
    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
    
    0 讨论(0)
  • 2020-12-07 03:39

    try this,

    def ispower(a,b):
      if b==a:
        return True
      elif a<b:
        return False
      else:
        return ispower(a*1.0/b, b)
    
    0 讨论(0)
  • 2020-12-07 03:41

    Here is my code. From what I tested, it works:

    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)
    
    0 讨论(0)
  • 2020-12-07 03:42

    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
    
    0 讨论(0)
提交回复
热议问题