An easier way to do this? (spoiler if you're using pyschools for fun)
Chris Rebert
clp2 at rebertia.com
Tue Nov 9 14:09:31 EST 2010
On Tue, Nov 9, 2010 at 11:00 AM, Matty Sarro <msarro at gmail.com> 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())
Just loop over the list directly:
for num in numList:
num = str(num)
> sumOfDigits+=int(num[-1:])
No need for the colon:
sumOfDigits+= int(num[-1])
> return sumOfDigits
And now for the much simpler math-based solution:
def getSumOfLastDigit(numList):
return sum(num%10 for num in numList)
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list