递归后函数返回无 [英] Function returns None after recursion
问题描述
我已经写了一个函数来确定显示器的高度,给定宽度和格式。该函数递归运行,如果它在尝试出一行高度值时找不到给定宽度和格式的匹配。如果函数在进入递归之前发现匹配,那么该函数将起作用,但在此之后,它始终返回无,而不是匹配的值对。对于这是为什么我很困惑。
def getDisplayDimensions(width,FormatX,FormatY):
Format = float(FormatX )/ FormatY
如果FormatX<格式Y:
返回非法格式。
为范围内的高度(1,int(width)+1):
如果float(width)/ height == float(格式):
返回宽度,高度
break
elif height == width:
getDisplayDimensions(float(width)-1,FormatX,FormatY)
#示例调用:
print getDisplayDimensions(801,16, 9)
您实际上并没有返回递归调用结果:
elif height == width:
getDisplayDimensions(float(width)-1,FormatX,FormatY)
添加返回
there:
elif height == width:
return getDisplayDimensions(float(width)-1,FormatX,FormatY)
$ c如果没有 return
,外部调用只会结束,并返回默认的<$ c $>
<$ c $ C>>>> def getDisplayDimensions(width,FormatX,FormatY):
... Format = float(FormatX)/ FormatY
... if FormatX<格式Y:
...返回非法格式。
...为范围内的高度(1,int(width)+1):
... if float(width)/ height == float(Format):
...返回宽度,高度
... break
... elif height == width:
... return getDisplayDimensions(float(width)-1,FormatX,FormatY)
...
>>> print getDisplayDimensions(801,16,9)
(800.0,450)
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)
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)
这篇关于递归后函数返回无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!