Skip to content

Instantly share code, notes, and snippets.

@ltc-hotspot
Last active August 29, 2015 14:26
Show Gist options
  • Save ltc-hotspot/d35e1c352d810d8a17d6 to your computer and use it in GitHub Desktop.
Save ltc-hotspot/d35e1c352d810d8a17d6 to your computer and use it in GitHub Desktop.
counter
handle = """From: stephen.marquard@uct.ac.za
X-DSPAM-Probability: 0.0000
Author: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
Return-Path: <postmaster@collab.sakaiproject.org>
From: stephen.marquard@uct.ac.za
Received: from 141.211.14.97
From: zqian@umich.edu""".split("\n")
# Ok - we have fake data - let's process it
count = dict()
for line in handle:
if line.startswith("From "):
address = line.split()[1]
line = Counter(address)
maxval = None
maxkee = None
for kee, val in count.items():
if val > maxval: # if this one is the biggest so far
maxval = val # then remember it!
maxkee = kee
print maxkee, maxval
@ltc-hotspot
Copy link
Author

Alan Gauld
11:38 AM (6 hours ago)

to me, tutor
On 08/08/15 00:05, Ltc Hotspot wrote:
Hi Alan,

On line 15, I replaced: 'count[address] = count.get(address, 0) + 1' with 'line = Counter(address)'.

line = Counter(address)

will create a new Counter object with the address in it with a count value of 1.
Every line in the file will create a new Counter, overwriting the previous one.
At the end of the loop you will have exactly 1 Counter containing the last item
in the loop and a count of 1.

Instead create the Counter before the loop and then use the update()
method to add the address to it. Recall we talked about reading the Counter
documentation? It describes the update() method.

One you have the Counter with all the addresses in you can get the max value
and key directly without using a second loop and your maxkee and maxval
variables.

Again read the Counter documentation to see how.

Finally remember the imports. You never show us those but the Counter will
not work unless you import it.

Question: What is the cause of the empty dict?

You create it but never use it. You replaced the line where count got
populated with your Counter call. So count never gets populated.
Just because Counter sounds like count does not mean they are
in any way connected.

Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment