Simple exercise
Mark Lawrence
breamoreboy at yahoo.co.uk
Thu Mar 10 20:21:21 EST 2016
On 11/03/2016 00:05, BartC wrote:
> 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]
What is wrong with a[0: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:
Never use a bare except. Better still, use an appropriate collection
rather than two lists. Off of the top of my head a counter or a
defaultdict.
> names.append(name) # new entry
> totals.append(value)
>
> for i in range(len(names)):
> print (names[i],totals[i])
>
Always a code smell when range() and len() are combined.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Python-list
mailing list