简体   繁体   中英

returning result of a function multiple times within the same function

I am trying to return a list of numbers that add up to 100 .. 11 times.

There are 3 numbers which are generated from a numpy random uniform distribution.

I want to add an if statement to see if the 1st, 2nd and 3rd numbers of each list (11 in total).. if plotted would have a Pearson correlation coefficient of >0.99.

At the moment, I am only able to generate 1 list of numbers which have a sum equal to 100.

I have following code:

import math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

c1_high = 98
c1_low = 75
c2_high = 15
c2_low = 6
c3_high = 8
c3_low = 2

def mix_gen():
    while True:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99<= tot <=100.01:
            comp_list = [c1,c2,c3]
            return comp_list

my_list = mix_gen()
print(my_list)

so if i was to plot each component.. for example c1... i would get an R^2 value of >0.99.

在此处输入图片说明

I'm stuck at generating multiple lists inside the same function. I know this can be done outside the function.. using [mix_gen() for _ in range(11)].. but this will not work because I require this additional check of the peasron corr coeff before returning the 11 lists.

OBJECTIVE:

to return a dataframe with the following values:

   C1    C2    C3    sum
1   70    20    10    100
2   ..
3   ..
4   ..
5   ..
6   ..
7   ..
8   ..
9   ..
10  ..
11  90
R^2  1     1     1

This can be an option using a list of lists for the return

def mix_gen(number):
    flag = 0
    container = []
    while flag < number:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99 <= tot <= 100.01:
            flag += 1
            container.append([c1,c2,c3])

    return container

You call it with

my_list_of_lists = mix_gen(11)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM