returning None instead of value: how to fix?

Neil Cerutti horpner at yahoo.com
Fri Sep 22 15:49:39 EDT 2006


On 2006-09-22, sam <python.sam at googlemail.com> wrote:
> i am starting to experiment with recursion, and decided to
> write a fairly trivial little program which took a float as
> input, then called a function to halve it recursively until it
> was less than 1:
>
> ____________________________________________________________________
> import recursive_halve_module
>
> raw_value = raw_input('please enter the number you would like to halve:
> ')
> value = float(raw_value)
>
> final_value = recursive_halve_module.recursive_halve(value)
>
> print final_value
>
> raw_input('hit enter to close: ')
> _____________________________________________________________________
>
> def recursive_halve(value):
>
>     if value < 1:
> 	print value
> 	return value
>     else:
>     	value = value/2
>     	print value
>     	if value < 1:
> 	    return value
>     	else:
> 	    recursive_halve(value)

Your immediate bug is that you're missing a return statement:

            return recursive_halve(value)

But your recursive routine is overcomplicated with too many base
cases, and you haven't written it functionally. There's no need
to modify value directly in a functional procedure.

Here's another version.

def recursive_halve(value):
  if value < 1.0:
    return value
  else:
    return recursive_halve(value / 2.0)

Now imagine the call-stack when called with value 45.0 (using the
substitution model):

recursive_halve(45.0) -->
  return recursive_halve(22.5) -->
    return recursive_halve(11.25) -->
      return recursive_halve(5.625) -->
        return recursive_halve(2.8125) -->
	  return recursive_halve(1.40625) -->
	    return recursive_halve(0.703125) -->
	      return 0.703125
	    
-- 
Neil Cerutti
Life is indeed precious, and I believe the death penalty helps
affirm this fact. --Edward Koch



More information about the Python-list mailing list