Normalizing A Vector
Alain Ketterlin
alain at dpt-info.u-strasbg.fr
Sat Jul 31 07:18:04 EDT 2010
Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> writes:
>>> What I don’t like is having that intermediate variable L leftover after
>>> the computation.
>>
>> Well, it also guarantees that the square root is computed once.
>
> OK, this version should solve that problem, without requiring any new
> language features:
>
> V = tuple \
> (
> x
> /
> l
> for x in V
> for l in
> (math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V), 0)),)
> )
You got the order wrong (it has to be for l ... for x ...)
You're kind of lucky here, because the arglist to tuple() provides a
scope that hides x and l. Be careful if you ever change tuple(...) to
[...], because x and l would leak to the outer scope (with python 2.*).
In the general case
for L in [...some-expr...]:
... whatever
doesn't hide L. Python doesn't provide a "let" construct (à la Lisp or
*ML).
-- Alain.
More information about the Python-list
mailing list