'Simple Clean Math Operations
I'm trying to make some basic methods for handling python math operations, I made a method for getting the sum of all numbers in the args like these:
def get_sum_of_numbers(*args):
temp_value = 0
for num in args:
temp_value += num
return temp_value
The problem is that when I try to create a simple average method:
def get_average_of_numbers(*args):
return get_sum_of_numbers(args) / len(args)
I can't reuse this method because I can't just pass to the sum method the args of the average method as an argument, I want to make both the average method and the sum method take as many numbers as the programmer wishes to input. Anyone have any ideas?
Solution 1:[1]
You can use the * operator again
def get_average_of_numbers(*args):
return get_sum_of_numbers(*args) / len(args)
Are you sure your get_sum_of_numbers function is doing what it's supposed to do though? Looks like it simply returns the value of the first arg. Why not do
def get_sum_of_numbers(*args):
return sum(args)
or if you don't want to use sum
def get_sum_of_numbers(*args):
temp_value = 0
for num in args:
temp_value += num
return temp_value # correct indentation
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 |
