python coding contest

Claudio Grondi claudio.grondi at freenet.de
Sun Jan 1 09:49:58 EST 2006


Steven D'Aprano wrote:
> On Sun, 01 Jan 2006 03:34:33 +0100, Claudio Grondi wrote:
> 
> 
>>>Please send me comments, suggestions and ideas.
>>
>>Now, after the contest is over I analysed the outcome of it and have 
>>come to the conclusion, that there were two major factors which 
>>contributed to squeezing of code:
>>
>>   (1). usage of available variants for coding of the same thing
>>   (2). sqeezing the size of used numeric and string literals
> 
> 
> [snip]
> 
> 
>>Is there in Python any simple way to do the same as the following two 
>>following functions I have put together today:
> 
> 
> They are already pretty simple. You can make them even more simple by
> using less complicated names and getting rid of the explicit end block
> markers. It is sometimes useful to put in explicit end block markers when
> you have long blocks, but when the block is just a single line, well,
> I don't see the point.
> 
> Here is another possibility.
> 
> 
>>>>import array
>>>>A = array.array('b')
>>>>n = 1000000
>>>>while n:
> 
> ....     A.append(n&255); n = n >> 8
> .... 
> 
>>>>A.reverse()
>>>>A
> 
> array('b', [15, 66, 64])
> 
>>>>15*256**2 + 66*256 + 64
> 
> 1000000
> 
>>>>A.tostring()
> 
> '\x0fB@'
> 
> The reverse transformation is just as easy:
> 
> 
>>>>A = array.array('b', "\x0fB@")  # initialise from a byte string
>>>>n = 0L
>>>>for b in A:
> 
> ....     n = n << 8 | b
> ....
> 
>>>>n
> 
> 1000000L
> 
> And of course these can be turned into functions.
> 
> 
> 
What I have thought about as a simpler/better solution is a method 
allowing to avoid processing the content of the string or long integer 
object by looping over its content. I suppose, that knowing enough about 
Python internals it must be possible to change only the object type not 
beeing forced to process the content i.e. the value itself, what in case 
of big size of data to convert with methods like this above wastes CPU 
time.

Claudio



More information about the Python-list mailing list