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

Peter Otten __peter__ at web.de
Tue Nov 9 14:13:47 EST 2010


Matty Sarro wrote:

> Hey everyone,
> I'm working on one of the puzzles on pyschools.com, and am trying to
> figure out if I can make my solution a bit more elegant.
> 
> def getSumOfLastDigit(numList):
>     sumOfDigits=0
>     for i in range(0, len(numList)):
>         num=str(numList.pop())
>         sumOfDigits+=int(num[-1:])
>     return sumOfDigits
> 
> Below is the problem. Basically you take the last digit of each number in
> the list, and add them together.
> 
> 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

Loop over a list directly:

for n in numlist:
   # ...

Use the modulo (%) operator to find the last digit:

last_digit = n % 10

There is a built-in sum() function:

sum([1,2,3]) # 6

There is an inlined form of the for-loop called "generator expression"

sum(i*i for i in [1,2,3]) # 14

Putting it all together:

>>> def gsold(numbers):
...     return sum(i%10 for i in numbers)
...
>>> gsold([12,23,34])
9
>>> gsold([2,3,4])
9
>>> gsold([1,23,456])
10

Peter




More information about the Python-list mailing list