[Tutor] script comparing two values - ASCII encoding error
Jeff Shannon
jeff@ccvcorp.com
Wed Feb 26 21:36:00 2003
Mic Forster wrote:
>I repeated the code you recommended and had no
>problem. All of the sudden this started happening:
>
I don't see offhand anything that should be causing a UnicodeError. Can
you give us the complete traceback that you're getting? Those few lines
that precede the "UnicodeError: ..." bit can tell us a lot about where
your problem is...
However, I'd like to point out one thing...
>>>>def f(k, s):
>>>>
>>>>
> return k / (1-k) * (1-k)**s / (1-(1-k)**s)
>
You should probably add some parens to this -- as it is, it could be
read two different ways (depending on which has higher priority,
multiplication or division -- I can't remember offhand which is higher
priority, which says to me that relying on priority is a bad idea).
Those two ways are:
( k / (1-k) ) * ( (1-k)**s / (1-(1-k)**s) )
or
k / ( (1-k) * (1-k)**s) / (1-(1-k)**s)
I think the first is what you meant, but since I'm not certain which way
Python will read it, I'd recommend being explicit about it.
For that matter, your last subexpression, 1-(1-k)**s, is slightly vague
too -- should that be (1-(1-k))**s, or 1-((1-k)**s)?? I'm pretty sure
that Python will presume the latter, and I believe that that's what you
want, but it never hurts to add parens to make it explicit. I'm a big
fan of using lots of parens in complicated mathematical expressions --
extra parens don't hurt, and may make the intended order more clear.
I'm also a big fan of using intermediate variables to split complicated
expressions into two or more lines, and I'd probably write the above
function like this:
def f(k, s):
subterm = (1-k)**s
return ( k / (1-k) ) * (subterm / (1-subterm) )
This makes the function a little easier to read, and also emphasises the
symmetry involved (and, as a side bonus, saves you time by calculating
the exponent only once). Of course, this is really just a matter of
taste...
Jeff Shannon
Technician/Programmer
Credit International