Simple exercise

BartC bc at freeuk.com
Thu Mar 10 19:05:52 EST 2016


On 10/03/2016 09:02, 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


Here's a rather un-Pythonic and clunky version. But it gives the 
expected results. (I've dispensed with file input, but that can easily 
be added back.)

def last(a):
     return a[-1]

def init(a):                 # all except last element
     return a[0:len(a)-1]

data =["BANANA FRIES 12",    # 1+ items/line, last must be numeric
        "POTATO CHIPS 30",
        "APPLE JUICE 10",
        "CANDY 5",
        "APPLE JUICE 10",
        "CANDY 5",
        "CANDY 5",
        "CANDY 5",
        "POTATO CHIPS 30"]

names  = []                        # serve as key/value sets
totals = []

for line in data:                  # banana fries 12
     parts = line.split(" ")        # ['banana','fries','12']
     value = int(last(parts))       # 12
     name  =  " ".join(init(parts)) # 'banana fries'

     try:
         n = names.index(name)      # update existing entry
         totals[n] += value
     except:
         names.append(name)         # new entry
         totals.append(value)

for i in range(len(names)):
     print (names[i],totals[i])


-- 
Bartc



More information about the Python-list mailing list