Home > Blockchain >  Returning multiple results from Python function for each variable
Returning multiple results from Python function for each variable

Time:07-25

Is it possible to have multiple "sum" results, for multiple "a" and "b" variables in below example? If so, how?

def function(a,b):
    sum = a  b
    return sum

I want to assign multiple values for a and b, and then calculate result for each scenario.

for a between 1 and 10 for b between 1 and 10 return sum for all those combinations of a and b values (100 combinations should be listed separately)

Is there any other way other than manually writing each scenario?

CodePudding user response:

You need to accept an iterable to your function and collect values from loops over both iterables.

def function(a,b):
    result = []
    for el_a in a:
        for el_b in b:
            result.append(el_a   el_b)
    return result

a = range(5)
b = range(5)

print(function(a,b))

CodePudding user response:

Something like this would do it:

def function(a, b):
    sums = []
    for num1 in range(a):
        for num2 in range(b):
            s = num1   num2
            sums.append(s)
    return sums

Example you mentioned can be calculated as: function(10, 100)

CodePudding user response:

def sum_funct(a,b):
    sum_dict = {}
    for a_ in range(a 1):
        for b_ in range(b 1):
            s_ = a_   b_
            sum_dict[str(a_) " " str(b_)] = s_
    return sum_dict
        

Something like this ? You'll get also the operation in the key if needed

sum_funct(2,2)
>>> {'0 0': 0,
 '0 1': 1,
 '0 2': 2,
 '1 0': 1,
 '1 1': 2,
 '1 2': 3,
 '2 0': 2,
 '2 1': 3,
 '2 2': 4}

CodePudding user response:

Is there any other way other than manually writing each scenario?

You might harness itertools.product as follows

import itertools
def function(a,b):
    return sum(i*j for i,j in itertools.product(a,b))
print(function([1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]))

gives output

3025
  • Related