How to sum dict elements
You can use the collections.Counter counter = collections.Counter() for d in dict1: counter.update(d) Or, if you prefer oneliners: functools.reduce(operator.add, map(collections.Counter, dict1))
You can use the collections.Counter counter = collections.Counter() for d in dict1: counter.update(d) Or, if you prefer oneliners: functools.reduce(operator.add, map(collections.Counter, dict1))
For ruby >= 2.4 you can use sum: array.sum For ruby < 2.4 you can use inject: array.inject(0, :+) Note: the 0 base case is needed otherwise nil will be returned on empty arrays: > [].inject(:+) nil > [].inject(0, :+) 0
using System.Linq; … double total = myList.Sum(item => item.Amount);
There is a no exact representation of 0.1 as a float or double. Because of this representation error the results are slightly different from what you expected. A couple of approaches you can use: When using the double type, only display as many digits as you need. When checking for equality allow for a small … Read more
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
Short Answer: Just generate N random numbers, compute their sum, divide each one by the sum and multiply by M. Longer Answer: The above solution does not yield a uniform distribution which might be an issue depending on what these random numbers are used for. Another method proposed by Matti Virkkunen: Generate N-1 random numbers … Read more
You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns: In [91]: df = pd.DataFrame({‘a’: [1,2,3], ‘b’: [2,3,4], ‘c’:[‘dd’,’ee’,’ff’], ‘d’:[5,9,1]}) df[‘e’] = df.sum(axis=1) df Out[91]: a b c d e 0 1 2 dd 5 8 1 2 3 ee 9 14 2 3 4 ff 1 … Read more
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
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
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