0

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)
lo tolmencre
  • 3,804
  • 3
  • 30
  • 60

1 Answers1

0

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Oh, thanks. Then there is indeed a fundamental lack of understanding for me here... Because, I don't understand, why the call needs the return statement, if the return is within the function that is being called. – lo tolmencre Oct 11 '14 at 18:12
  • 1
    @user3578468: imagine calling a *different function* at that point; say you called `set([float(width)-1,FormatX,FormatY])` there instead. What do you think would happen then if you missed out the `return`? Calling a recursive function is no different here, you still need to return the result. – Martijn Pieters Oct 11 '14 at 20:00