Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, args):
        self.args = args

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

For addition, I can simply use return sum(args) to calculate the total but I am unsure of what I can do for subtractions.

like image 697
user1306134 Avatar asked Apr 01 '12 10:04

user1306134


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" the operator in-between list elements.

like image 118
georg Avatar answered Nov 02 '22 23:11

georg


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?

like image 25
machine yearning Avatar answered Nov 03 '22 00:11

machine yearning