簡體   English   中英

Pyschools:編寫一個遞歸函數,將參數a到b的數字返回

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM