'Easy way to square `*args`
The code below prints the square root of 7+6+3 (=4).
import math
def notdist(*args):
return math.sqrt(sum(args))
print(notdist(7,6,3))
I want somenting like this:
import math
def dist(*args):
return math.sqrt(sum(args**2))
print(dist(7,6,3))
for calculating the distance from O(0,0), but this is giving the error:
unsupported operand type(s) for ** or pow(): 'tuple' and 'int'
I know that I can use another code like:
import math
def uglydist(*args):
s = 0
for i in range(len(args)):
s = s + args[i]**2
return math.sqrt(s)
print(uglydist(3,4)) # = 5
but I 'm wondering if it is an easy way to modify the first code. Something like the second code, but correct.
Thanks in advance!
Solution 1:[1]
using the for like this would be better, but I think this too isn't what you wanted
import math
def NotSoGoodDist(*args):
s = 0
for i in args:
s = s + i**2
return math.sqrt(s)
print(NotSoGoodDist(3,4)) # = 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | No.BoD |
