[Tutor] counting occurrences of pairings

Israel Evans israel@lith.com
Thu, 25 Apr 2002 07:38:15 -0700


Cool!  Nice tricks.

I was just thinking about the tuple key thing last night, but I didn't know
about the .get() method.  That smoothes things out a bit.

I was trying to think of a way of figuring out the pairings/groupings of all
possible combinations, so this tuple key and .get() methods seem like they
will help.  I'll probably end up with huge dictionaries, but I think it
could work quite nicely.  Sorting will be easier as well.

Thanks!


~Israel~


-----Original Message-----
From: Jeff Shannon [mailto:jeff@ccvcorp.com] 
Sent: 24 April 2002 5:46 PM
To: tutor@python.org
Subject: Re: [Tutor] counting occurrences of pairings

> Israel Evans <israel@lith.com> wrote:
>
> I found that I had to create the spaces before I started assigning values
to
> them in a different way than I was.

There's a nice feature of dicts that you might want to take advantage of...

Instead of initializing your dictionaries with 0 for each pair of numbers
that you
expect, you can use the dictionary's get() method.  This will return the
value for a
key if it exists, or a default value if it doesn't exist.

>>> d = {'one':1, 'two':2}
>>> d.get('one', 0)
1
>>> d.get('two', 0)
2
>>> d.get('three', 0)
0
>>> d.get('three', 3)
3
>>>

Thus, the simple way to count, using dictionaries, is this:

    d[key] = d.get(key, 0) + 1

This will add one to whatever preexisting value d[key] had, or create a new
key with
the value of one if it didn't exist previously.

Another trick you might want to use -- instead of using nested dictionaries,
like
you do, you could instead use a single dictionary, and have the key be an
(x, y)
tuple instead of a string.

If we combine these two tricks, then your code will end up looking something
like
this:


>>> atupe = ('a', 'b', 'c', 'd', 'e')
>>> btupe = ('a', 'f', 'g', 'd', 'h')
>>> ctupe = ('a', 'i', 'j', 'f', 'd')
>>> alltupe = (atupe, btupe, ctupe)
>>> alldict = {}
>>> for tupe in alltupe:
...  for char in tupe:
...   for other in tupe:
...    alldict[(char,other)] = alldict.get((char,other), 0) + 1
...
>>> for key, value in alldict.items():
...  print key, '--', value
...
('a', 'd') -- 3
('a', 'e') -- 1
('c', 'c') -- 1
('c', 'a') -- 1
('a', 'a') -- 3
('a', 'b') -- 1
< ......  >  # ommitting numerous lines of output
('d', 'f') -- 2
('b', 'c') -- 1
('b', 'b') -- 1
>>>

Hope that helps!

Jeff Shannon
Technician/Programmer
Credit International





_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor