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 find the cumulative sum of numbers in a list?

If you’re doing much numerical work with arrays like this, I’d suggest numpy, which comes with a cumulative sum function cumsum: import numpy as np a = [4,6,12] np.cumsum(a) #array([4, 10, 22]) Numpy is often faster than pure python for this kind of thing, see in comparison to @Ashwini’s accumu: In [136]: timeit list(accumu(range(1000))) 10000 … 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

How do I get SUM function in MySQL to return ‘0’ if no values are found?

Use COALESCE to avoid that outcome. SELECT COALESCE(SUM(column),0) FROM table WHERE … To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0 More Information: Given three tables (one with all numbers, one with all nulls, and one with a mixture): SQL Fiddle MySQL 5.5.32 Schema Setup: CREATE TABLE foo ( id INT NOT NULL … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)