[Tutor] Dictionary Issue
Alan Gauld
alan.gauld at btinternet.com
Fri Aug 7 00:00:36 CEST 2015
On 06/08/15 19:30, Ltc Hotspot wrote:
> I moved counter outside the loop and below dict, maxval = None
> maxkee = None are both positioned outside the loop.
You moved counter but it is still a dict() and you
don't use it anywhere.
> URL link to the revisions are available at http://tinyurl.com/nvzdw8k
>
> Question: How do I define Counter
Counter is defined for you in the collections module.
So to use it you need to import collections and access it as
collections.Counter.
But did you read how to use it? It is a lot more than
just a dictionary, it has many extra methods, some of
which almost solve your problem for you. (Whether your
teacher will approve of using Counter is another
issue!)
> Revised code reads:
> fname = raw_input("Enter file name: ")
> handle = open (fname, 'r')
>
> counter = dict ()
> c = Counter(['address'])
You only need to pass a list if you are adding multiple things.
But by the same token you can add a list of items, such
as email addresses. So if you had such a list you could
create a Counter() to hold them and count them for you.
And return the one with the highest value.
Sound familiar?
Please (re)read the Counter documentation.
Then play with one in the >>> prompt.
Don't expect us to just provide you with code, learn
how it works for yourself. Experiment.
The >>> prompt is your friend. You will learn more from that in 15
minutes than in a bunch of emails showing other peoples
code.
Alternatively forget about Counter and just go back to
your dict(). You have written all the code you need already,
you just need to assemble it in the correct order.
> maxval = None
> maxkee = None
>
> for line in handle:
> if line.startswith("From: "):
> address = line.split()[1]
You are not storing the addresses anywhere.
> for maxkee, val in c.items():
>
> maxval = val
> maxkee = kee
You are still not testing if its the maximum,
you just keep overwriting the variables for
each element.
> print maxkee and maxval
You still have an 'and' in there.
--
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
More information about the Tutor
mailing list