Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104497

Re: Simple exercise

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: Simple exercise
Date 2016-03-10 10:41 +0100
Organization None
Message-ID <mailman.122.1457602909.15725.python-list@python.org> (permalink)
References <CABRP1o-c+Y7U9owb7_g9WU71FjNo6GT7XVhcuQqgasMrsv2GtA@mail.gmail.com>

Show all headers | View raw


Rodrick Brown wrote:

> From the following input
> 
> 9
> BANANA FRIES 12
> POTATO CHIPS 30
> APPLE JUICE 10
> CANDY 5
> APPLE JUICE 10
> CANDY 5
> CANDY 5
> CANDY 5
> POTATO CHIPS 30
> 
> I'm expecting the following output
> BANANA FRIES 12
> POTATO CHIPS 60
> APPLE JUICE 20
> CANDY 20
> 
> However my code seems be returning incorrect value
> 
> #!/usr/bin/env python3
> 
> import sys
> import re
> from collections import OrderedDict
> 
> if __name__ == '__main__':
> 
>   od = OrderedDict()
>   recs = int(input())
> 
>   for _ in range(recs):
>     file_input = sys.stdin.readline().strip()
>     m = re.search(r"(\w.+)\s+(\d+)", file_input)
> 
>     if m:
>       if m.group(1) not in od.keys():
>         od[m.group(1)] = int(m.group(2))
>       else:
>         od[m.group(1)] += int(od.get(m.group(1),0))

Look closely at the line above. 

What value do you want to add to the current sum?
What value are you actually providing on the right side?

>   for k,v in od.items():
>     print(k,v)
> 
> What's really going on here?
> 
> $ cat groceries.txt | ./groceries.py
> BANANA FRIES 12
> POTATO CHIPS 60
> APPLE JUICE 20
> CANDY 40

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Simple exercise Peter Otten <__peter__@web.de> - 2016-03-10 10:41 +0100

csiph-web