Home > other >  I'm trying to write a code to calculate length, average and sum of 1000 random numbers
I'm trying to write a code to calculate length, average and sum of 1000 random numbers

Time:05-04

x = np.random.normal(size=1000)
class arrays:
    def __init__(self,data):
        self.data=data
    def ave(x):
        ave=data.mean()
        return self.ave
    def sum(self):
        self.s=sum(self.data)
        return self.s
a=arrays(x)

I'm trying to find the length, average and summation of 1000 random numbers using classes. I tried writing the code this way but I'm getting this error. TypeError: unsupported operand type(s) for : 'int' and 'str' Can someone please help me debug the code?

CodePudding user response:

import numpy as np
x = np.random.normal(size=1000)


class arrays:
    def __init__(self, data):
        self.data = data

    def ave(self):
        ave = self.data.mean()
        return ave

    def sum(self):
        s = sum(self.data)
        return s


a = arrays(x)

x = a.ave()
y = a.sum()
print(x, y)

I believe this is what you want. The arguments of the function are self, and you can just return the result.

This article explains the OOP paradigm better than I can. https://www.programiz.com/python-programming/object-oriented-programming

You can also call the functions directly on x and save the result in a variable as such

sum1 = x.sum()
mean1 = x.mean()
  • Related