Sum a list of numbers in Python

Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, … etc. We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two … Read more

Sum the digits of a number

Both lines you posted are fine, but you can do it purely in integers, and it will be the most efficient: def sum_digits(n): s = 0 while n: s += n % 10 n //= 10 return s or with divmod: def sum_digits2(n): s = 0 while n: n, remainder = divmod(n, 10) s += … Read more

How to sum all column values in multi-dimensional array?

You can use array_walk_recursive() to get a general-case solution for your problem (the one when each inner array can possibly have unique keys). $final = array(); array_walk_recursive($input, function($item, $key) use (&$final){ $final[$key] = isset($final[$key]) ? $item + $final[$key] : $item; }); Example with array_walk_recursive() for the general case Also, since PHP 5.5 you can use … Read more