[Tutor] optimization: faster than for

Alan Gauld alan.gauld at btinternet.com
Mon Jul 2 22:50:41 CEST 2007

"elis aeris" <hunter92383 at gmail.com> wrote
> The letter I equals to "282" because it has 2 points on the y axis 
> of the
> first point, and 8 points on the y axis on the second, and then 2 on 
> the
> last one.
> So the string would be translated into:
> 28201722030033330000004222400722240172206 and so on.
> #####################
> so what I am going to have is a string like above and what I 'll 
> have is
> a list of tuples, for instance   [a, 222] , [b,333]  and so forth

Better to use a dictionary keyed by m=number, I think:

letters = { 222: 'a', 333: 'b',....}

Then access it with


Now all you have to do is extract groups of 3 digits from
the string which can be done using slicing and indexing:

for index in range(0,len(codeString),3):
    num = int(codeString[index:index+3])

Which will result in myString containing all the letter equivalents.

> how do I write the fastest code to do this

Once you get it working you can profile the code to find out
how to make it faster, but until you get it working its pointless
to worry about making it faster. Making broken code faster
just results in faster bugs.

> optimization is immediately needed because the job is done as soon 
> this
> translation is complete.

Optimization is only needed if the simple solution is too slow.
How you define "too slow" is not clear to us at this point. And
optimisation stops when the code is no longer "too slow"

> image.getdata()  is a good solution, i haven't found a better one,

OK, Go with getdata for now.
The next trick is to create your lists of numbers which involves
summing the columns of pixels.

> and the other bottle neck is this translation process.

Try the (untested) solution offered above and see how well the
total solution works. Then we can decide how much speed up it
needs - if any. And we can start to work out the most beneficial
place to do that speedup.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list