Full question: Write a function that takes a list of integers as the input and returns the sum of the last digit of every number in the list. For example, if the input is [11, 12], the function should return 3. When the input list if empty, it should return 0. For items in the list that are not integers, the function will ignore them. So an input of ['a', 'b'] will return 0. Your driver should test the function with at least four different scenarios, including a empty list, a list with all non-integers, with some but not all non-integers, and all integers.
I am not sure how to (1) find the last digit of every integer and (2) have the function differentiate between integers and non-integers. I thought about doing
for x in num_list:
if int(x) = x
return True
but not sure if that would work. Really unsure of where to start here. This is what I have so far:
num = []
def last_digit_sum(num):
answer = 0
for entry in num:
if int(entry) == entry:
l = entry[-1]
if entry == []:
print('0')
answer = l
return answer
print(last_digit_sum([121, 235, 345, 234])
CodePudding user response:
Here is a longer but easy to to understand answer:
a = [101, 102,345,4777]
def calculate(lst):
s = 0
for n in lst:
s = s n % 10
return s
calculate(a)
returns 15
CodePudding user response:
Check if an element is an int
and then use modulo % 10
to extract the last digit. Then use sum
.
for numbers in [
[11, 12, 998, 450, 66, 5],
[],
[0, 10, -300],
[3],
[3, 6],
[3, 6, -81],
[33, "a", "bb", -5678, "cd e"],
["a", "bb", "cd e"],
]:
print(
sum(map(lambda num: abs(num) % 10 if isinstance(num, int) else 0, numbers))
)
Output
22
0
0
3
9
10
11
0
CodePudding user response:
the simplest way would be
def sumup(lst):
return sum([int(x) % 10 for x in lst if str(x).isdigit()])
CodePudding user response:
Try this function, call Sum([11,12])
def Sum(lst):
sum =0
for x in lst:
t = str(x)
d = t[-1]
if d.isnumeric():
sum =sum int (d)
return sum