How do I use python to display multiple answers for n amount of input sets of 2

53 Views Asked by At

I want do take my function

def function_name(inputa, inputb)
    #long formula which uses 2 inputs
    return answer

if __name__ == '__main__':
    function_name(float(sys.argv[1]), float(sys.argv[2]))

input to bash

 python3 function_name.py 0.3 0.2 0.1 0.5

would like to take inputa, inputb = 0.3, 0.2 and run formula for answer 1 then rerun formula with inputa, inputb = 0.1, 0.5 and give the output for answer 2

this should work with n amount of inputs such as python3 function_name.py 0.3 0.2 or python3 function_name.py 0.3 0.2 0.1 0.5 0.6 0.7 and so on

expected output

answer 1 
answer 2 
def function_name(inputa, inputb)
    #long formula which uses 2 inputs
    return answer

if __name__ == '__main__':
    function_name(float(sys.argv[1]), float(sys.argv[2]))

input:

python3 function_name.py 0.3 0.2

output:

answer 

input:

python3 function_name.py 0.3 0.2 0.4 0.5

output:

answer1
answer2  
2

There are 2 best solutions below

9
Tim Roberts On

This does what you asked, but I'm pretty sure what you asked is not really what you wanted. I've supplied a fake function just to show it working:

import sys
def function_name(inputa, inputb):
    #long formula which uses 2 inputs
    return inputa+inputb
if __name__ == '__main__':
    args = sys.argv[1:]
    while len(args) >= 2:
        a = args.pop(0)
        b = args.pop(0)
        print("Answer:", function_name(float(a), float(b)))

Output:

timr@Tims-NUC:~/src$ python x.py 0.5 0.7 1.2 1.5 2.5 2.9
Answer: 1.2
Answer: 2.7
Answer: 5.4
timr@Tims-NUC:~/src$
3
Swifty On

Here's an implementation where the function works with several (pairs of) arguments; the function actually returns a generator for the answers:

import sys

def function_name(*args):
    for i in range(0, len(args)//2):
        inputa, inputb = args[2*i], args[2*i+1]
        #long formula which uses 2 inputs
        yield inputa + inputb


if __name__ == '__main__':
    args = sys.argv[1:]
    print(list(function_name(*map(float, args))))

Example:

C:\Users\Swifty\.spyder-py3>python tmp.py 1 2 3 4 1.2 4.7
[3.0, 7.0, 5.9]

Note: I coded a protection against an odd number of arguments: the last one is ignored.

Example:

C:\Users\Swifty\.spyder-py3>python tmp.py 1 2 3 4 1.2
[3.0, 7.0]