How can I get rid of lambda
Robert Roy
rjroy at takingcontrol.com
Mon Oct 16 01:32:05 EDT 2000
I went a step further with your code and created a lookup dict for all
256 char values. 100,000 reps went from 9.2 seconds to 3.9 seconds.
Append the following to the code you posted
#--------------
# create a dict of characters and expansions
l = {}
for x in range(256):
l[chr(x)] = unpack(chr(x))
#print l
#print map(None, packedNumber)
# do some timing
import time
# so the range call does not influence the timing
reps = range(100000)
# test using unpack
s = time.clock()
for x in reps:
unpack(packedNumber)
t = time.clock()
print 'using unpack', t-s
#test using the dict, note there is no need for function call
# get rid of the dot
lget = l.get
s = time.clock()
for x in reps:
fnJoin(map(lget, packedNumber), '')
t = time.clock()
print 'using dict.get', t-s
On Mon, 16 Oct 2000 00:11:29 GMT, Steve Williams
<sandj.williams at gte.net> wrote:
>I'm working with IBM packed decimal data. The following code works OK,
>but there are millions of rows and 10 to 50 columns per row. I want as
>much speed as I can get.
>
>How can I avoid the lambda in the following unpack function? Or better,
>is there a faster way?
>
>By the way, if you want a testimonial to Python's capabilities, do a
>Google search on 'packed decimal' and have a look at some of the Java
>solutions to this problem.
>
>===============================================
>
>"""Unpack an IBM packed decimal string"""
>import string
>
>#Get rid of the dots
>fnJoin = string.join
>fnTranslate = string.translate
>
>#Create translate tables for the left and right nybbles
>_strSource = ""
>for _i in range(256): _strSource = _strSource + chr(_i)
>_trtLeftNybble = string.maketrans(_strSource, \
> "0"*16 + "1"*16 + "2"*16 + "3"*16 + "4"*16 + \
> "5"*16 + "6"*16 + "7"*16 + "8"*16 + "9"*16 + "."*96)
>_trtRightNybble = string.maketrans(_strSource,"0123456789+-+-++"*16)
>del _strSource
>del _i
>
>def unpack(strPacked):
> return fnJoin(map(lambda chrLeft, chrRight: chrLeft + chrRight,\
> fnTranslate(strPacked,_trtLeftNybble),\
> fnTranslate(strPacked,_trtRightNybble)),"")
>
>try:
> packedNumber = '\x01\x23\x45\x67\x89\x0f'
> print unpack(packedNumber)
>except RuntimeError, e:
> print e
>
>try:
> packedNumber = '\x01\x23\x45\x67\x89\x0d'
> print unpack(packedNumber)
>except RuntimeError, e:
> print e
>
>
>
More information about the Python-list
mailing list