I have learnt one usually uses *arg arguments when you're not sure how many arguments might be passed to my function. I'm trying to create a generalised Pythagoras' theorem such that it computes for n things such that with
pytha(*arg)
with
print(pytha(x,y)) = np.sqrt(x**2 + y**2)
print(pytha(x,y,z)) = np.sqrt(x**2 + y**2 + z**2)
print(pytha(x,z)) = np.sqrt(x**2 + z**2)
print(pytha(x-7,y)) = np.sqrt((x-7)**2 + y**2)
print(pytha(x-3,y-5,z-8)) = np.sqrt((x-3)**2 + (y-5)**2 + (z-8)**2)
print(pytha(x,y,z,t)) = np.sqrt(x**2 + y**2 + z**2 + t**2)
I've done
def pytha(*arg):
but I don't know how to manipulate *arg within the body of the functions. So how would one go about creating this function with *arg?
The arguments you provide will get stored in the tuple with name you provided during function defining. If it is *arg
then the tuple will be arg
and you can then use it with that name.
>>> import numpy as np
>>> def pytha(*arg):
... v = [i**2 for i in arg] # collected all in one list
... return np.sqrt(sum(v)) # give argument by summing the list items
...
>>> pytha(2,3,4)
5.385164807134504