使用递归来查找哪个数字更大

时间:2017-11-08 22:31:17

标签: python

大家好,我试图找出使用递归而不使用>的两个数字中哪一个更大?或者<符号。这甚至可能吗?我只允许使用+或 - 提前谢谢

2 个答案:

答案 0 :(得分:1)

我将在Haskell中向您展示一个可以解决问题的测试实现。这不是最好的解决方案,但是你的教练似乎并没有寻求效率,只是对这个问题进行深入思考。

-- |'myMax' takes two strictly positive ints and returns
-- the larger of the two.
myMax :: Int -> Int -> Int
myMax 0 y = y
myMax x 0 = x
myMax x y = myMax (x-1) (y-1)

答案 1 :(得分:0)

当然有可能,使用递归你必须考虑正整数(0)可以表示为0或下一个正数。考虑到,如果数字不是0,你可以退后一步,并询问它是否为0,并继续,代码将是:

def greater_than(a,b):
  if(a == 0):
    return b!=0
  elsif(b == 0):
    return True
  else:
    return greater_than(a-1,b-1)
相关问题