Simple exercise

Chris Kaynor ckaynor at zindagigames.com
Thu Mar 10 21:14:11 EST 2016


On Thu, Mar 10, 2016 at 4:05 PM, BartC <bc at freeuk.com> wrote:

> 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'
>

This could be written as (untested):

name, value = line.rsplit(' ', 1) # line.rsplit(maxsplit=1) should also work
value = int(value)


No need to rejoin the string this way.

See also: https://docs.python.org/3.5/library/stdtypes.html#str.rsplit


>     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])
>

Chris



More information about the Python-list mailing list