I have multiple scripts that calculates the different means given a list of numbers as arguments when calling the python script (https://github.com/alvations/meanie):
For example, harmonic_mean():
# -*- coding: utf-8 -*-
import math
def harmonic_mean(x): # x is a list of values.
""" Returns the harmonic mean given a list of values. """
return len(x) / sum([1/i for i in x])
def main(means):
print "Input:", means
means = map(float,means)
print "harmonic mean = ", harmonic_mean(means)
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
sys.stderr.write('Usage: python %s mean1 mean2 mean3 ... \n' % sys.argv[0])
sys.exit(1)
main(sys.argv[1:])
and root_mean_square()
# -*- coding: utf-8 -*-
import math
def root_mean_square(x): # x is a list of values.
""" Returns the root mean square (rms) given a list of values. """
return math.sqrt(sum([i*i for i in x])/len(x))
def main(means):
print "Input:", means
means = map(float,means)
print "root mean square = ", root_mean_square(means)
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
sys.stderr.write('Usage: python %s mean1 mean2 mean3 ... \n' % sys.argv[0])
sys.exit(1)
main(sys.argv[1:])
As you see, the two script does exactly the same thing but just calling different mean() functions and prints different outputs at the main(). How could I combine them and allow users to give a mean option parameter/argument when they call it at the console/terminal? E.g. the combined script is call meannie.py :
$ python meanie.py harmonic 1 2 3
$ python meanie.py hm 1 2 3
The above command should give the same output as calling (this is how users call the harmonic_mean() script now):
$ python hm.py 1 2 3