Skip to content Skip to sidebar Skip to footer

What Is A Subtraction Function That Is Similar To Sum() For Subtracting Items In List?

I am trying to create a calculator, but I am having trouble writing a function that will subtract numbers from a list. For example: class Calculator(object): def __init__(self,

Solution 1:

from functools import reduce  # omit on Python 2
import operator

a = [1,2,3,4]

xsum = reduce(operator.__add__, a)  # or operator.add
xdif = reduce(operator.__sub__, a)  # or operator.sub

print(xsum, xdif)
## 10 -8

reduce(operator.xxx, list) basically "inserts" the operator in-between list elements.


Solution 2:

It depends exactly what you mean. You could simply subtract the sum of the rest of the numbers from the first one, like this:

def diffr(items):
    return items[0] - sum(items[1:])

It's tough to tell because in subtraction it's dependent on the order in which you subtract; however if you subtract from left to right, as in the standard order of operations:

x0 - x1 - x2 - x3 - ... - xn = x0 - (x1 + x2 + x3 + ... + xn)

which is the same interpretation as the code snippet defining diffr() above.

It seems like maybe in the context of your calculator, x0 might be your running total, while the args parameter might represent the numbers x1 through xn. In that case you'd simply subtract sum(args) from your running total. Maybe I'm reading too much into your code... I think you get it, huh?


Post a Comment for "What Is A Subtraction Function That Is Similar To Sum() For Subtracting Items In List?"