[Tutor] rounding up to the nearest multiple of 8

Albert-Jan Roskam fomcl at yahoo.com
Fri Oct 5 13:23:12 CEST 2012


----- Original Message -----

> From: Asokan Pichai <pasokan at talentsprint.com>
> To: tutor at python.org
> Cc: 
> Sent: Friday, October 5, 2012 11:06 AM
> Subject: Re: [Tutor] rounding up to the nearest multiple of 8
> 
> If you are doing so many times, it may be worth precomputing the padding for a
> given length and adding it by a look up on the length.
> 
> For example:
> ------------------------
> SPACE = ' '
> MAX = 1000
> TAB = 8
> paddding = [ SPACE * (n % TAB) for n in range(MAX) ]
> 
> .....
> s = padding[len(s)] + s
> .....
> --------------------------
> where s is string to be padded
> 
> Asokan Pichai


Good idea! I know that the string values can never exceed 32767 bytes. So when I combine all the advice I got here, the best way seems to be ver4, using Eryksun's ver3 to initialize a dictionary:

from timeit import timeit
setup = "from math import ceil; value = 1040 * '*'"
setup += "; " + "padLookup = dict([(i, -8 * (i // -8)) for i in range(1, 32767+1)])"
ver1 = timeit('int(ceil(len(value)/8.0)*8)', setup=setup)
ver2 = timeit('len(value) + (-len(value) % 8)', setup=setup)
ver3 = timeit('-8 * (len(value) // -8)', setup=setup)
ver4 = timeit('padLookup[len(value)]', setup=setup)

print ver1/ver4, ver2/ver4, ver3/ver4, ver4/ver4

Thanks guys!


More information about the Tutor mailing list