Newbie question about function return values

John Machin sjmachin at lexicon.net
Sat Mar 15 01:19:21 CET 2003


Chad Netzer <cnetzer at mail.arc.nasa.gov> wrote in message news:<mailman.1047603262.3191.python-list at python.org>...
> 
> def sectors(x):
>     if ((x % 512) != 0):
>         x = x + 1
>         return sectors(x)
>     else:
>         return x
> 
> 
> BTW - There are better methods of finding the next larger power of two. 
> Try starting with the value 1 and doubling it until it is larger than
> the comparison value, for example.

(1) The OP's function is badly named; once it's been "fixed",
sectors(511) -> 512, sectors(1000) -> 1024 etc. It doesn't return a
number of sectors. It returns the input size rounded up to the nearest
multiple of the sector size traditionally favoured by one particular
operating system.

(2) "power of 2" seems totally irrelevant.

(3) It doesn't need a loop, let alone recursion.

Try this:

def round_to_higher_mult_of_512(x):
   return ((x + 511L) // 512L) * x
   # 'L' just in case rounded-up file size >= 2GB




More information about the Python-list mailing list