What is a subtraction function that looks like sum () to subtract items in a list?

I'm trying to create a calculator, but it's hard for me to write a function that subtracts numbers from a list.
For instance:

class Calculator(object):
    def __init__(self, args):
        self.args = args

    def subtract_numbers(self, *args):
        return ***here is where I need the subtraction function to be****

To add, I can simply use return sum(args)to calculate the total, but I'm not sure what I can do for the subtractions.

+5
source share
2 answers
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" an operator between list items.

+11
source

It depends on what you mean. You could simply subtract the sum of the remaining numbers from the first, for example:

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

, , ; , , :

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

, , diffr() .

, x0 , args x1 xn. sum(args) . , ... , , ?

+4

All Articles