簡體   English   中英

函數遞歸后返回 None

[英]Function returns None after recursion

我編寫了一個函數來確定顯示器的高度,給定寬度和格式。 如果在嘗試一行高度值時找不到給定寬度和格式的匹配項,則該函數將遞歸運行。 如果在進入遞歸之前找到匹配,則該函數可以工作,但在此之后,它始終返回 none 而不是匹配的值對。 我很困惑為什么會這樣。 我在這里錯過了一些原則嗎?

def getDisplayDimensions(width,FormatX,FormatY):
    Format = float(FormatX)/FormatY
    if FormatX < FormatY:
        return "illegal format."
    for height in range(1,int(width)+1):
        if float(width)/height == float(Format):
            return width,height
            break
        elif height == width:
            getDisplayDimensions(float(width)-1,FormatX,FormatY)

# example call:
print getDisplayDimensions(801,16,9)

您實際上並沒有返回遞歸調用結果:

elif height == width:
    getDisplayDimensions(float(width)-1,FormatX,FormatY)

在那里添加return

elif height == width:
    return getDisplayDimensions(float(width)-1,FormatX,FormatY)

如果沒有return ,外部調用就會結束並返回默認的None

演示:

>>> def getDisplayDimensions(width,FormatX,FormatY):
...     Format = float(FormatX)/FormatY
...     if FormatX < FormatY:
...         return "illegal format."
...     for height in range(1,int(width)+1):
...         if float(width)/height == float(Format):
...             return width,height
...             break
...         elif height == width:
...             return getDisplayDimensions(float(width)-1,FormatX,FormatY)
... 
>>> print getDisplayDimensions(801,16,9)
(800.0, 450)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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