0

Is it possible to write a function such that in every call it save data; for example- the following function takes two arguments x & y; where x is a data and y is the array size. Call the function first time, it would create y dimensional array, fill the first position with x value and in the second call it would fill the 2nd position of the array and continue and it will return a average when at least 2 values are in that array. The array size would be fixed, if call the function more than y times, it will delete first data (FIFO).

def storedata(x,y):
    return z
Sanjib
  • 9
  • 4
  • Use global variables to hold the information between calls. Then you can check the values of the variables to see what to do. – Barmar Jan 13 '22 at 06:46
  • This would be a good use for a class, you can save the information between calls in attributes. – Barmar Jan 13 '22 at 06:47

3 Answers3

0

you can use global variables to keep your data in them and call them between your functions.

check out this page: What is the pythonic way of saving data between function calls? maybe solve your problem if you want to use the class and attribute solution.

Draxsis
  • 11
  • 5
  • I am thinking to keep this function in another file not in my main program file, so global does not help here. I will check that link. Thanks! – Sanjib Jan 13 '22 at 07:10
  • @Sanjib Not that globals are a good solution (use a class) but you *can* have globals in another file. – Mark Tolonen Jan 13 '22 at 07:31
0

You should use a class when you want to store data.

An small example is given below, but please look online for tutorial and examples to fully understand the working of classes and OOP in python.

class Storedata:
    def __init__(self, x, y):
        self.arr = []
        self.max_arr_size = y
        self.add_data(x)
    def add_data(self, x):
        if len(self.arr) < self.max_arr_size:
            self.arr.append(x)
    def __call__(self):
        return sum(self.arr)/len(self.arr)

storedata = Storedata(3, 5)
print(storedata.arr)
>>> [3]
print( storedata() )
>>> 3.0
storedata.add_data(5)
print( storedata() )
>>> 4.0
3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
0

Thanks everyone for the solutions. Using a class is a good way but I think I was looking for the following code.

def storedata(x, y):
    if not hasattr(storedata, 'z'):
        storedata.z = np.zeros(y, dtype=float)
    storedata.z = np.roll(storedata.z, 1)
    storedata.z[0] = x
    storedata.z[storedata.z == 0] = np.nan
    return storedata.z, np.nanmean(storedata.z)


for i in range(1, 11):
    print(storedata(x=i, y=10))

Sanjib
  • 9
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 14 '22 at 00:35