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


Groups > comp.lang.python > #104537 > unrolled thread

Re: Simple exercise

Started byTerry Reedy <tjreedy@udel.edu>
First post2016-03-10 13:20 -0500
Last post2016-03-10 13:20 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Simple exercise Terry Reedy <tjreedy@udel.edu> - 2016-03-10 13:20 -0500

#104537 — Re: Simple exercise

FromTerry Reedy <tjreedy@udel.edu>
Date2016-03-10 13:20 -0500
SubjectRe: Simple exercise
Message-ID<mailman.142.1457634085.15725.python-list@python.org>
On 3/10/2016 4:02 AM, 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

Learn to debug.  The incorrect value is the one for candy.  First, 
reduce you input to the candy lines.  Still get wrong answer?  Then 
print the value in od within the loop after each calculation to see when 
and how it goes wrong.

> #!/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))
>    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
>


-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web