为什么参数类型由不同的比较运算符更改?

时间:2017-01-03 05:20:49

标签: python

当我处理Ackermann function时:

def ackermann(m,n):
   if m == 0:
    return n + 1
   if m > 0 and n == 0:
    return ackermann(m-1,1)
   elif m > 0 and n > 0:
      return ackermann(m-1,ackermann(m,n-1))

我在第二个if语句中写了错误的运算符:

if m == 0 and n == 0:
  return ackermann(m-1,1)

但我收到了一个错误:

File "C:/Users/jacob/Desktop/think python/exercise 6-2.py", line 15, in ackermann
return ackermann(m-1,ackermann(m,n-1))

File "C:/Users/jacob/Desktop/think python/exercise 6-2.py", line 14, in ackermann
 elif int(m) > 0 and int(n) > 0:

TypeError: unorderable types: NoneType() > int()

为什么运算符改变了参数类型?

2 个答案:

答案 0 :(得分:1)

好的,产生错误的代码是

def ackermann(m,n):
   if m == 0:
    return n + 1
   if m == 0 and n == 0:
    return ackermann(m-1,1)
   elif m > 0 and n > 0:
      return ackermann(m-1,ackermann(m,n-1))

我们来看一个例子。

ackermann(2, 1)
  # m = 2, n = 1
  m == 0: False
  m == 0 and n == 0: False
  m > 0 and n > 0: True
  return ackermann(m-1,ackermann(m,n-1))
    ackermann(m,n-1)  # the inner call
    ackermann(2,1-1)
      # m = 2, n = 0
      m == 0: False
      m == 0 and n == 0: False
      m > 0 and n > 0: False
      # None of the conditions matched, so we (implicitly) return None
      # because we didn't execute an explicit return
    ackermann(2-1,None)  # the outer call
      # m = 1, n = None
      m == 0: False
      m == 0 and n == 0: False
      m > 0 and n > 0:
        m > 0: True    # m == 1
        n > 0: error!  # n == None

答案 1 :(得分:0)

我怀疑你没有遇到任何一个条件并且到函数的末尾导致一个隐式返回,即无。

尝试在函数末尾返回一些有效值。

如,

def ackermann(m,n):
   if m == 0:
    return n + 1
   if m > 0 and n == 0:
    return ackermann(m-1,1)
   elif m > 0 and n > 0:
      return ackermann(m-1,ackermann(m,n-1))

   # Writing an explicit return to make sure we always
   #  return some integer and not None. Change this accordingly
   return 1