python递归函数,需要两个输入

时间:2012-03-13 15:43:28

标签: python recursion

我是python的新手,我遇到了问题。我想编写一个递归函数,它接受两个输入(整数)并从第一个减去第二个,直到第一个小于第二个,并计算它在减去之前减去的时间。

这是我到目前为止所做的,但是我在使函数重复从第一个减去第二个函数时遇到了问题;

def div(first,sec):
    if first > sec:
        return div((first - sec),sec) + first

    else:
        return 0

4 个答案:

答案 0 :(得分:1)

你的意思是什么?

def div(first,second):
    if (first >= second):
        return div(first-second,second) + 1
    else: return 0

但是在尝试div(100000,3)时你会遇到问题,因为递归我太深了。为避免这种情况,您只需执行以下操作:

first/second

答案 1 :(得分:1)

我相信这应该做你想做的事情:

def div(first, sec):
    if first >= sec:
        return div(first - sec, sec) + 1
    else:
        return 0

>>> div(6, 2)
3
>>> div(8, 4)
2
>>> div(12, 2)
6

以下是div(6, 2)的调用链,可以帮助您了解其工作原理:

div(6, 2) == 1 + div(4, 2)
          == 1 + 1 + div(2, 2)
          == 1 + 1 + 1 + div(0, 2)
          == 1 + 1 + 1 + 0                          

答案 2 :(得分:0)

这就是你想要的。您不需要if函数,只需while个函数!

# function:
def div(a,b):
    count = 0
    while a > b:
        a = a - b
        count = count + 1
return count

# now we'll use the function:
a = div(565,34)
b = div(34,565)

a将为16,b将为0!

答案 3 :(得分:0)

## naive recursion
def div(a, b):
    if (a >= b):
        return div(a - b, b) + 1
    else: return 0

try:
    print div(5678, 3)
except Exception as e:
    print e  ## maximum recursion depth exceeded


## less naive recursion with trampolines
## see https://gist.github.com/802557 for details/explanations
def trampoline(f):
    def _(*args):
        result = f(*args)
        while callable(result):
            result = result()
        return result
    return _

def div_func(a, b, acc=0):
    if (a >= b):
        return lambda: div_func(a - b, b, acc + 1)
    else: return acc

div2 = trampoline(div_func)

## ok
print div2(5678, 3)