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

Terry Reedy tjreedy at udel.edu
Tue Nov 9 20:18:34 CET 2010


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




More information about the Python-list mailing list