Function returns None after recursion

会有一股神秘感。 提交于 2019-12-31 05:34:10

问题


I have written a function to determine the height of a display, given a width and a format. The function operates recursively, if it cannot find a match for the given width and format while trying out a row of height values. The function works, if it finds a match before going into the recursion, but after that it always returns none and not the matching value pair. I am very confused as to why that is. Am I missing some principle here?

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)

回答1:


You are not actually returning the recursive call result:

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

Add return there:

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

Without the return the outer call just ends and returns the default None instead.

Demo:

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


来源:https://stackoverflow.com/questions/26317027/function-returns-none-after-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!