improving a huge double-for cycle

giltay at gmail.com giltay at gmail.com
Thu Sep 18 19:26:49 CEST 2008


On Sep 18, 11:18 am, prueba... at latinmail.com wrote:
> dup=set()
> SN=[]
> for item in IN:
>    c=item.coordinates[0], item.coordinates[1]
>    if c in dup:
>       SN.append(item.label)
>    else:
>       dup.add(c)

+1 for O(N)

If item.coordinates is just an (x, y) pair, you can skip building c
and save a little memory:

seen_coords = set()

for node in IN:
    if node.coordinates in seen_coords:
        SN.append(node.label)
    else:
        seen_coords.add(node.coordinates)

seen_coords gets populated with references to the existing
node.coordinates objects, instead of new tuples.

Geoff G-T




More information about the Python-list mailing list