- 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?
3 Answers
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!
Comments
- Using
sumand 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)
1 Comment
Gabio
Wow! very nice answer!