An easier way to do this? (spoiler if you're using pyschools for fun)

Matteo Landi landimatte at gmail.com
Wed Nov 10 03:06:48 EST 2010


I agree with Peter:
* iterate over the list directly
* use %10 instead of string conversion + slice
(*) use genexps

Good luck,
Matteo

On Tue, Nov 9, 2010 at 8:18 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 11/9/2010 2:00 PM, Matty Sarro wrote:
>
>> I'm working on one of the puzzles on pyschools.com
>> <http://pyschools.com>, and am trying to figure out if I can make my
>> solution a bit more elegant.
>
> Definitely
>
>> def getSumOfLastDigit(numList):
>>     sumOfDigits=0
>>     for i in range(0, len(numList)):
>>         num=str(numList.pop())
>
> This is an awkward way to iterate through a list ;-)
>
>>         sumOfDigits+=int(num[-1:])
>>     return sumOfDigits
>
>> Write a function: getSumOfLastDigit(numList) that takes in a list of
>> positive numbers and returns the sum of all the last digit in the list.
>>
>> *Examples*
>>    >>>  getSumOfLastDigit([12,  23,  34])
>>    9
>>    >>>  getSumOfLastDigit([2,  3,  4])
>>    9
>>    >>>  getSumOfLastDigit([1,  23,  456])
>>    10
>
> # Straightforward version of what you did
>
> def getSumOfLastDigit(numList):
>    sumOfDigits=0
>    for i in numList:
>        sumOfDigits+=int(str(i)[-1:])
>    return sumOfDigits
>
> print(getSumOfLastDigit([12, 23, 34]),
>      getSumOfLastDigit([2, 3, 4]),
>      getSumOfLastDigit([1, 23, 456]) )
> # 9 9 10
>
> # Use generator expression with built-in sum function
>
> def getSumOfLastDigit(numList):
>    return sum(int(str(i)[-1:]) for i in numList)
>
> print(getSumOfLastDigit([12, 23, 34]),
>      getSumOfLastDigit([2, 3, 4]),
>      getSumOfLastDigit([1, 23, 456]) )
> # 9 9 10
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list