2012-03-13 43 views
-1

我是新來的python,我遇到了問題。我想寫一個遞歸函數,它接受兩個輸入(整數),並從第一個減去第二個,直到第一個小於第二個,並計算它在減去之前減去的時間。需要兩個輸入的python遞歸函數

這就是我到目前爲止,但我有問題得到的功能重複從第一個第二的減法;

+3

我在該函數中看不到遞歸調用。取消'while'循環,並進行遞歸調用。 – 2012-03-13 15:47:39

+0

這裏沒有遞歸。 – Marcin 2012-03-13 15:48:01

+0

我不明白爲什麼這已被評級下來... – Rexxo 2012-03-13 15:49:51

回答

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) 
+0

最後幾個我不明白,因爲我是新手,但是第一個工作正常。如果你不能簡單地解釋代碼的工作原理嗎? @ thg435 – 2012-03-13 16:59:14

+0

第一個片段與已發佈的其他片段相同。第二個使用[trampoline](http://en.wikipedia.org/wiki/Trampoline_%28computers%29)消除[尾遞歸](http://en.wikipedia.org/wiki/Tail_call)。這種方法的主要思想是遞歸函數不是直接調用它,而是在臨時函數中將此調用返回爲「關閉」。 – georg 2012-03-13 18:32:34

1

你的意思是這樣的嗎?

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

但是,試圖div(100000,3)例如,當你會碰到的問題,因爲我的遞歸太深。爲了避免這種情況,你可以簡單地做:

first/second 
+0

如果你嘗試我的方法,在嘗試'div(100000,3)'時沒有任何問題! +1因爲你的解決方案'first/second':是的,它很簡單(如果'first'和'second'是'int')! – carla 2012-03-13 16:23:54

+0

但它不是遞歸@india_dourada。我但它更有用,雖然。 – 2012-03-13 16:34:36

+0

@zenpoy如果不是返回它被減去的次數,我想返回第一個減去第二個之後的值,直到它小於第一個爲止,那麼我該如何去做呢? – 2012-03-13 16:35:41

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       
+0

是的,它完美的作品,謝謝。我可以簡單解釋它的工作原理嗎? – 2012-03-13 16:20:51

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!

+0

對不起,這不是遞歸的! – carla 2012-03-13 16:26:06