Normalizing A Vector

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Sun Aug 1 09:59:38 EDT 2010


Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> writes:

>>>     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 ...)
>
> No, I deliberately put it in that order to ensure that the value for l can 
> only ever be evaulated once.

Try this (essentially equivalent to your code):

def f():
    print "hello"
    return 1

V = tuple( 1 for x in [1,2,3] for l in (f(),) )

How many "hello"s do you see?

Comprehension are not loops spelled backwards. The values in:

    whatever for i ... for j ...

are the values produced by the equivalent code:

    for i ...
        for j ...
            whatever

-- Alain.



More information about the Python-list mailing list