Home > Software engineering >  I want to make a Class without using numpy but there's something wrong
I want to make a Class without using numpy but there's something wrong

Time:04-10

I'm trying to get used to how to use Class but I think I made some mistakes.
The first error that occurs to me is this:
TypeError: init() missing 2 required positional arguments: 'N' and 'M'
If I cannot make a matrix with random integers, then I cannot make others...
so I'm very crazy about fixing this problem... :( please help me!

import random
from typing import List

class Numpy:
    def __init__(self, N: int, M: int):
        ### Edit Here ###
        self.N = N
        self.M = M
        # make matrix with randInt
        self.matrix = self.randInt(self.N, self.M)
        #################
    
    def __str__(self):
        ### Edit Here ###
        print(self.matrix)
        # print matrix
        #################
        
    def randInt(self, N: int, M: int) -> List[List[int]]:
        ### Edit Here ###
        
        # make random int N * M matrix
        matrix = [[random.randint(0, 100) for row in range(self.N)] for column in range(self.M)]
        #################
        return matrix
        
    def mean(self, axis: int) -> List[int]:
        ### Edit Here ###
        if self.axis == 0:
            mean = []
            for j in range(self.M):
                s = 0
                for i in range(self.N):
                    s  = self.matrix[0][i]
                mean.append(s/self.M)
        elif self.axis == 1:
            mean = []
            for j in range(self.N):
                s = 0
                for i in range(self.M):
                    s  = self.matrix[0][i]
                mean.append(s/self.N)
        # calculate mean for each axis
        #################
        return mean
        
    def argmax(self, axis: int) -> List[int]:
        ### Edit Here ###
        # find index of max value for each axis
        x = self.axis
        index = max(range(len(x)), key=lambda i: x[i])
        #################
        return index
    
    def concatenate(self, mat: List[List[int]], axis: int):
        ### Edit Here ###
        # concatenate mat to existing matrix
        if axis == 0 :
            return self.matrix   mat
        elif axis == 1:
            for i in range(self.M):
                self.matrix[i] = self.matrix[i]   mat[i]
            return self.matrix
        #################
        
    def zeros(self, N: int, M: int) -> List[List[int]]:
        ### Edit Here ###
        # make N * M matrix with all zero values
        zeros = [([0]*self.M) for i in range(self.N)]
        #################

        return zeros

print(Numpy().randInt(3,2))

CodePudding user response:

I would do:

import random
from typing import List

class Matrix:
    def __init__(self, N: int, M: int):
        ### Edit Here ###
        self.N = N
        self.M = M
        # make matrix with randInt
        self.matrix = [[]]
        self.rand_int()
        #################

    def __str__(self):
        ### Edit Here ###
       return str(self.matrix)
        # print matrix
        #################

    def rand_int(self) -> List[List[int]]:
        ### Edit Here ###

        # make random int N * M matrix
        self.matrix = [[random.randint(0, 100) for row in range(self.N)] for column in range(self.M)]
        #################


    def mean(self, axis: int) -> List[int]:
        ### Edit Here ###
        if self.axis == 0:
            mean = []
            for j in range(self.M):
                s = 0
                for i in range(self.N):
                    s  = self.matrix[0][i]
                mean.append(s/self.M)
        elif self.axis == 1:
            mean = []
            for j in range(self.N):
                s = 0
                for i in range(self.M):
                    s  = self.matrix[0][i]
                mean.append(s/self.N)
        # calculate mean for each axis
        #################
        return mean

    def argmax(self, axis: int) -> List[int]:
        ### Edit Here ###
        # find index of max value for each axis
        x = self.axis
        index = max(range(len(x)), key=lambda i: x[i])
        #################
        return index

    def concatenate(self, mat: List[List[int]], axis: int):
        ### Edit Here ###
        # concatenate mat to existing matrix
        if axis == 0 :
            return self.matrix   mat
        elif axis == 1:
            for i in range(self.M):
                self.matrix[i] = self.matrix[i]   mat[i]
            return self.matrix
        #################

    def zeros(self, N: int, M: int) -> List[List[int]]:
        ### Edit Here ###
        # make N * M matrix with all zero values
        zeros = [([0]*self.M) for i in range(self.N)]
        #################

        return zeros

print(Matrix(3,2))

Note that there are few non pythonic ways in this code. For zeros and randint, for example, I would better do factories, which would result in:

import random

class Matrix:
    def __init__(self, matrix=None):
        self.matrix = matrix
    @property
    def n(self):
        return len(self.matrix)

    @property
    def m(self):
        if len(self.matrix) > 0:
            return len(self.matrix[0])
        else:
            return 0


    def __str__(self):
       return str(self.matrix)

    @classmethod
    def rand_int(cls, the_n, the_m):
        my_matrix = cls()
        my_matrix.matrix = [[random.randint(0, 100) for row in range(the_n)] for column in range(the_m)]
        return my_matrix

    @classmethod
    def zeros(cls, the_n, the_m):
        my_matrix = cls()
        my_matrix.matrix = [([0]*the_m) for i in range(the_n)]
        return my_matrix

print(Matrix())
print(Matrix.zeros(3,2))
print(Matrix.rand_int(3,2))
print(Matrix.rand_int(3,2).n)
print(Matrix.rand_int(3,2).m)

which results in

None
[[0, 0], [0, 0], [0, 0]]
[[31, 32, 62], [99, 89, 85]]
2
3

CodePudding user response:

The __init__ method is called when you create an instance of your Numpy class.

So if your __init__ methods takes 2 arguments N and M, your last line should be print(Numpy(2,3)).

This also means that you are calling the randInt method twice:

  • once when you create your object, in the init method (Numpy() should be replaced by self though, else you will be calling the method on a new Numpy object, and you will have an infinite recursion).
  • then when you call the method on your object in the print statement.

Moreover, your randInt method requires 2 arguments N and M, but you are not using them since you use the class variables self.N and self.M in your method.

So to fix your issue, I would suggest you to

  1. replace your print(Numpy().randInt(3,2)) statement with print(Numpy(3,2))
  2. replace the line self.matrix = Numpy().randInt(self.N, self.M) with self.matrix = self.randInt()
  3. modify your randInt function to remove the 2 arguments you do not use : def randInt(self) -> List[List[int]]:
  • Related