Velocity Reviews > Dict Comprehension ?

# Dict Comprehension ?

Ernst-Ludwig Brust
Guest
Posts: n/a

 10-06-2008
Given 2 Number-Lists say l0 and l1,
count the various positiv differences between the 2 lists

the following part works:

dif=[abs(x-y) for x in l0 for y in l1]
da={}
for d in dif: da[d]=da.get(d,0)+1

i wonder, if there is a way, to avoid the list dif

Ernst-Ludwig Brust

bearophileHUGS@lycos.com
Guest
Posts: n/a

 10-06-2008
Ernst-Ludwig Brust:
> Given 2 Number-Lists say l0 and l1,
> count the various positiv differences between the 2 lists
>...
> i wonder, if there is a way, to avoid the list dif

Instead of creating the list (array) dif, you can create a lazy
iterator. Then you can fed it to a set.

Bye,
bearophile

pruebauno@latinmail.com
Guest
Posts: n/a

 10-06-2008
On Oct 6, 8:59 am, "Ernst-Ludwig Brust" <(E-Mail Removed)> wrote:
> Given 2 Number-Lists say l0 and l1,
> count the various positiv differences between the 2 lists
>
> the following part works:
>
> dif=[abs(x-y) for x in l0 for y in l1]
> da={}
> for d in dif: da[d]=da.get(d,0)+1
>
> i wonder, if there is a way, to avoid the list dif
>
> Ernst-Ludwig Brust

from collections import defaultdict
da=defaultdict(int)
for x in [10]:
for y in [11]:
da[abs(x-y)]+=1

Ernst-Ludwig Brust
Guest
Posts: n/a

 10-07-2008
<(E-Mail Removed)> schrieb im Newsbeitrag
news:(E-Mail Removed)...
>
> Instead of creating the list (array) dif, you can create a lazy
> iterator. Then you can fed it to a set.

Thangs,
this idea is not only less storage-consuming but even faster
than the "List-Version".
But, i used the idea of pruebauno,
as this is faster.

Ernst-Ludwig Brust

Ernst-Ludwig Brust
Guest
Posts: n/a

 10-07-2008
"Ben Finney" <(E-Mail Removed)> schrieb im Newsbeitrag
news:(E-Mail Removed)...
> "Ernst-Ludwig Brust" <(E-Mail Removed)> writes:
>
> So, generator expressions can be a powerful way to clarify the purpose
> of a section of code. They can be over-used, though: don't use them
> unless they actually *do* clarify the code; sometimes an explicit
> looping construct is clearer.

Thangs,
my opinion was, that "one-statement-constructions" are
much faster then f.e. explicit loops.
But,
now i know, with Python, this is not allways true.

Ernst-Ludwig Brust

Ernst-Ludwig Brust
Guest
Posts: n/a

 10-07-2008
<(E-Mail Removed)> schrieb im Newsbeitrag
news:(E-Mail Removed)...
>
> from collections import defaultdict
> da=defaultdict(int)
> for x in [10]:
> for y in [11]:
> da[abs(x-y)]+=1

Thangs,
collections are a real good idea.
I will use this version.

Ernsst-Ludwwig Brust