return sum of last digits in list
How to return the sum of the last digits of the values in a list? i cant think of an efficient way. If it wasn't for being in a list i could do it, but im really lost. Can anyone advise me? im going to look for a way in the python library.
Thank you for any help
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
If you think of something else than code under,give an example of list and task.
>>> l = [1,2,3,4]
>>> l[:2]
[1, 2]
>>> l[2:]
[3, 4]
>>> #Sum up last 2 digits
>>> sum(l[2:])
7
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
If you think of something else than code under,give an example of list and task.
>>> l = [1,2,3,4]
>>> l[:2]
[1, 2]
>>> l[2:]
[3, 4]
>>> #Sum up last 2 digits
>>> sum(l[2:])
7
sorry, i wasn't very clear of my intentions, forgive me. the objective is as follows;
Write a function getSumofLastDigits() that takes in a list of positive numbers and returns the sum of all the last digits in the list.
Examples
>>> getSumofLastDigits([2, 3, 4])
9
>>> getSumofLastDigits([1, 23, 456])
10
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
You can use modulo operator to find the last digit.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Just to give you a hint with modulo operator as pyTony mention.
>>> 38 % 10
8
>>> 369 % 10
9
>>> 36 % 10
6
>>> 36999 % 10
9
>>>
So loop over element in list with modulo operator ,and use build in sum() to get result.
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
Thanks for the help everyone!
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0