- Starting array:
[1555, 1116, 221, 997]
- Ending array:
[16, 9, 5, 25]
- Where each number in the ending array is the sum of the digits of the corresponding number in the starting array.
- How do I get from the starting array to the ending array?
Asked
Active
Viewed 636 times
1

Trenton McKinney
- 56,955
- 33
- 144
- 158

Gabriel Nair
- 11
- 1
3 Answers
1
You can use list comprehension where each number is converted to string -> splitted to list of chars -> converted to digits(numbers) back -> summed:
start = [1555, 1116, 221, 997]
end = [sum(map(int, list(str(x)))) for x in start]
print(end) # output: [16, 9, 5, 25]

Gabio
- 9,126
- 3
- 12
- 32
1
I believe what you are asking is to create an array whose elements are the sum of the digits of each number in the original array. The number digit summation is shamelessly stolen from Sum the digits of a number - python, and putting it all together you get:
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
in_array = [1555, 1116, 221, 997]
out_array = [sum_digits(n) for n in in_array]
print(out_array)
Hope this helps!

minerharry
- 101
- 8
1
- Using
sum
and a list-comprehension - Without
map
&list
t = [1555, 1116, 221, 997]
result = [sum(int(d) for d in str(v)) for v in t]
print(result)
[16, 9, 5, 25]
- Corresponding
for-loop
result = list()
for v in t:
r = list()
for d in str(v):
r.append(int(d))
result.append(sum(r))
%%timeit
comparison
- Given the following test list
import numpy as np
np.random.seed(123)
t = [np.random.randint(100, 4000) for _ in range(4000000)]
- This answer
%%timeit
[sum(int(d) for d in str(v)) for v in t]
5.27 s ± 60.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
[sum(map(int, list(str(x)))) for x in t]
4.63 s ± 37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
- Answer from minerharry
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
%%timeit
[sum_digits(n) for n in t]
1.72 s ± 10.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Trenton McKinney
- 56,955
- 33
- 144
- 158
-
1Wow! very nice answer! – Gabio Jun 25 '20 at 17:05