![](/img/trans.png)
[英]write a function (recursive) that will calculate the sum of even numbers from 1 to n
[英]Pyschools: Write a recursive function returning a sting of numbers from arguments a to b
編寫一個遞歸函數NumbersInbetween(start,end),該函數接受兩個數字並返回一個公共分隔的字符串,其中所有數字都在開始和結束數字之間,包括兩個數字。
我的嘗試:
def numbersInbetween(a, b):
if b == 0:
return "Invalid"
if a == b:
return '%d' % (a)
else:
return '%s,%s' % (a, numbersInbetween(a+1,b))
所有輸入均返回預期結果,但是pyschools返回“私人測試用例失敗”。
您能否在這里指出我的錯誤,我嘗試了許多變種,但收效甚微。 謝謝
看這里 ,似乎您的問題在這里:
if b == 0:
如果輸入b作為小於a
的非零值:
...
File "<stdin>", line 7, in numbersInbetween
File "<stdin>", line 7, in numbersInbetween
File "<stdin>", line 7, in numbersInbetween
RuntimeError: maximum recursion depth exceeded
因此,將if b == 0
更改為if b < a
:
def numbersInbetween(a, b):
if b < a:
return "Invalid"
if a == b:
return '%d' % (a)
else:
return '%s,%s' % (a, numbersInbetween(a+1,b))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.