Search code examples
pythonfunctionnumpysubtraction

How can I subtract all given numbers in function with *args in python?


I'm trying to make a 'subtract' function in Python that will take in any amount of numbers and subtract them. I tried using Numpy's 'subtract' function, but I got an error that states:

Traceback (most recent call last):
  File "/Users/myname/Desktop/Python/Calculator/calculator_test.py", line 27, in <module>
    print(subtract(100, 6))  # Should return 94
  File "/Users/myname/Desktop/Python/Calculaotr/calculator_test.py", line 14, in subtract
    return np.subtract(numbers)  # - This isn't working
ValueError: invalid number of arguments

My Code:

from math import prod
import numpy as np


# Simple calculator app

# Add function
def add(*numbers):
    return sum(numbers)


# Subtract function
def subtract(*numbers):
    return np.subtract(numbers)  # - This isn't working


# Multiply function
def multiply(*numbers):
    return prod(numbers)


# Divide function
def divide(*numbers):
    return


print(subtract(100, 6))  # Should return 94

Version Info:

Python 3.9.4 (Python Version)

macOS BigSur 11.3 (Os version)

PyCharm CE 2021.1 (Code editor)


Solution

  • You could use functools.reduce paired with either operator.sub for subtraction or operator.truediv for division:

    from operator import sub, truediv
    from functools import reduce
    
    
    def divide(*numbers):
        return reduce(truediv, numbers)
    
    
    def subtract(*numbers):
        return reduce(sub, numbers)
    
    divide(4, 2, 1)
    2.0
    
    subtract(4, 2, 1)
    1
    
    subtract(100, 6)
    94