Result of function vs loop

Viewed 67

My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773
5 Answers

As said in the comments, you need to create a loop and append the values inside just like so:

import numpy as np
from scipy import integrate

input_= [0.1, 0.2]

def newvalue():
    values = []
    for i in input_:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        values.append(value[0])
    return values

print(newvalue()) #[1.8229239584193715, 1.2226505441838773]

The first script only provides one value because you have a return in the loop — the loop doesn’t continue after that.

There are two typical ways to handle this situation. The first is to create an empty array before your loop, add each result to the array during the loop, and return that results array after the loop. That approach is ok if the number of values / loops is small, i.e. you don’t want to build up a 10,000,000 element array.

If the number of values / loops is bigger, or if your outer function may not need all the values, use a yield in place of your return. That allows the called function to generate each value as needed when called from an outer loop.

After calling return statements the function does not continue and all information is lost that has not been either returned or is not referenced by a variable outside the function scope.

The answer from Anwarvic should do the trick.

Your function should not take it's argument from a global variable. You can define your function so that it accepts one value, and returns the caluclated result for this value.

def newvalue(input):
    value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
    return value

You can then query it in a few different fashions :

  1. In a loop
for i in [0.1, 0.2]:
    print(newvalue(i))
  1. Or via list comprehension :
inputs = [0.1,0.2]
answers = [newvalue(i) for i in inputs]

print(answers)

In your first example simply replace the command

return value[0]

with

yield value[0]

Then you may use a newvalue() in these forms, for example:

  1. list(newvalue()) to obtain a list of all calculated values,
  2. for i in newvalue(): to iterate through calculated values.
Related