Does python suck or I am just stupid?

John Machin sjmachin at lexicon.net
Sat Feb 22 19:30:49 EST 2003


andy at takecover.net (Andy Mroczkowski) wrote in message news:<41948401.0302221000.6257443f at posting.google.com>...
> I've been tearing my hair out over a bug(?) I've come across.  I've
> only been programming in Python for a few months so I'm no expert. 
> I've seen the same behavior in Python2.2 on several different
> machines.  Instead of banging my head against the wall even more, I
> thought I would ask the community for help.
> 
> A good example of it is in the following code snippet.
> 
> 
> ########################### BEGIN #########################
> #!/usr/bin/env python
> 
> u = 0.0
> u_inc = 0.001
> 
> v = (0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0)
> 
> while u <= 1.0:
>         for x in v:
>                 if u == x:
>                         print u, x
>         u = u + u_inc
> ######################### END ##########################

You have already got 3 lots of good advice (that I've seen) re
floating point precision. Here's some more general advice that might
save some head-banging and hair-pulling with future problems: Put some
print statements in your code to show what the actual values are, not
what you guess them to be e.g. just before the "if" statement, insert
"print repr(u), repr(x)"

And here's some gratuitous advice that may head off a "is Python slow
or ...?" question:

Your outer (while) loop does 1000 or 1001 iterations. Your inner (for)
loop does 12 (i.e. len(v)) iterations. That means the "if" statement
is executed 12,000 times. However the tuple v has duplicates for no
apparent reason. Eliminating the duplicates, if you can, cuts the
12,000 down to 5,000.

Further, when you expect the equality test to "work", it would be much
faster *and* much clearer if you used "if u in v: something()" than if
you used "for x in v: if u == x: something()" ... especially faster if
v can be a dictionary instead of a tuple.

If you really need to have duplicate values in v, consider using
v.count(u) ... again faster and clearer than writing your own loop.

Hope this helps,
John




More information about the Python-list mailing list