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.
It depends exactly what you mean. You could simply subtract the sum of the rest of the numbers from the first one, like this:
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:
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 theargs
parameter might represent the numbersx1
throughxn
. In that case you'd simply subtractsum(args)
from your running total. Maybe I'm reading too much into your code... I think you get it, huh?reduce(operator.xxx, list)
basically "inserts" the operator in-between list elements.