Home > Blockchain >  Running the same function in loop and saving the outputs
Running the same function in loop and saving the outputs

Time:12-13

The function slope() below generates the random b values and the values generated is used to calculate result in second function. In first run slope() will generate 15 values and calculate result for that 15 values and save in dictionary. I want to run this function for 100 times so for each set of 15 values it save the result like output for each run. I want to save the iteration number also. Here I am trying to save in dictionary So that I can save my result later in pandas dataframe. How can run this function 100 times?? How can I save the result so that later I can convert that result in pandas dataframe easily?

import numpy as np


# Randomly generated b values 
def slope():
    b = np.random.uniform(1,2.5,15).round(2)
    return b

def psd(a):
    y = np.random.uniform(1,2.5,2).round(2)
    for i in y:
        result = y**(-a)   1
    dictionary = {f'{a}':f'{list(result.round(5))}'}
    return dictionary

power = list(psd(x) for x in slope())

The output of above function is :

[{'2.08': '[1.40189, 1.38618]'}, 
 {'1.19': '[1.41358, 1.35635]'},
 {'2.0': '[1.51757, 1.61035]'},
 {'1.61': '[1.35884, 1.45538]'},
 {'1.07': '[1.38503, 1.80131]'},
 {'1.08': '[1.40485, 1.48885]'},
 {'2.37': '[1.11844, 1.66215]'},
 {'2.45': '[1.14653, 1.20226]'},
 {'1.34': '[1.3748, 1.34766]'},
 {'1.33': '[1.48239, 1.307]'},
 {'2.12': '[1.83302, 1.80152]'},
 {'1.19': '[1.46882, 1.6644]'},
 {'1.65': '[1.35917, 1.2442]'},
 {'1.61': '[1.27493, 1.24591]'},
 {'1.17': '[1.45778, 1.47483]'}]

CodePudding user response:

Here is a sample code to call it 100 times.

import numpy as np


# Randomly generated b values 
def slope():
    b = np.random.uniform(1,2.5,15).round(2)
    return b

def psd(a):
    y = np.random.uniform(1,2.5,2).round(2)
    for i in y:
        result = y**(-a)   1
    dictionary = {f'{a}':f'{list(result.round(5))}'}
    return dictionary


# Save power in a dict with iter value as key.
data = {}
for i in range(100):
    power = list(psd(x) for x in slope())
    data.update({i: power})

# print(data)
  • Related