@Hukyl

Почему вылезает ошибка «TypeError: () takes 1 positional argument but 2 were given»?

Делаю матричный калькулятор, хочу использовать рекурсию, но вылезает эта ошибка:

1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
4. Transpose matrix
5. Calculate a determinant
0. Exit
Your choice: 5
Enter size of matrix: 3 3
Enter matrix: 
1 2 3
4 5 6
7 8 9
[[5, 6], [8, 9]]
Traceback (most recent call last):
  File "MatrixCalculator.py", line 167, in <module>
    calc.main()
  File "MatrixCalculator.py", line 157, in main
    self.find_determinant()
  File "MatrixCalculator.py", line 122, in find_determinant
    print(super().find_determinant(self.__create_matrice__()))
  File "MatrixCalculator.py", line 86, in find_determinant
    determinant = (determinant + (elem * self.find_determinant( ([x - 1 for x in size], algebraic_complement) ))
TypeError: find_determinant() takes 1 positional argument but 2 were given


Вот сам код:
from copy import deepcopy

class MatrixCalculator:
    slicer = lambda lst, n: [list(lst[i:i + n]) for i in range(0, len(lst), n)]
    
    def find_determinant(self, size, matrix):
        if size[0] != size[1]:
            return 'This operation cannot be performed'
        elif size == [2, 2]:
            return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
        else:
            plus = True
            determinant = 0
            for idx, elem in enumerate(matrix[0]):
                if elem == 0:
                    plus = not plus
                    continue
                algebraic_complement = deepcopy(matrix[1:])
                for row in algebraic_complement:
                    row.pop(idx)
                print(algebraic_complement)
                determinant = (determinant + (elem * self.find_determinant([x - 1 for x in size], algebraic_complement))
                    if plus else (determinant - (elem * self.find_determinant([x - 1 for x in size], algebraic_complement))) )
        return determinant


class InterfaceMC(MatrixCalculator):

    def find_determinant(self):
        self.__print_matrice__(super().find_determinant(*self.__create_matrice__()))

    @staticmethod
    def __create_matrice__(identifier = ' '):
        size = [int(x) for x in input("Enter size of%smatrix: " % identifier).split()]
        print('Enter%smatrix: ' % identifier)
        matrix = [list(float(x) if '.' in x else int(x) for x in input().split()) for y in range(size[0])]
        return size, matrix

    @staticmethod
    def __print_matrice__(matrice):
        if isinstance(matrice, list):
            print('The result is: ')
            [print(*row) for row in matrice]
        else: 
            print(matrice)

    def main(self):
        while True:
            print('1. Add matrices', '2. Multiply matrix by a constant', '3. Multiply matrices', '4. Transpose matrix', '5. Calculate a determinant', '0. Exit', sep='\n')
            inp = input('Your choice: ').strip()
            if inp == '0':
                break
            elif inp == '1':
                self.add()
            elif inp == '2':
                self.mul_by_const()
            elif inp == '3':
                self.mul_matrices()
            elif inp == '4':
                self.transpose()
            elif inp == '5':
                self.find_determinant()
            else:
                print('Sorry, not implemented yet ༼ つ ◕_◕ ༽つ ')

            print()


if __name__ == '__main__':
    calc = InterfaceMC()
    calc.main()
  • Вопрос задан
  • 7897 просмотров
Решения вопроса 1
@mrxor
Simple is better than complex
Проблема в этом вызове
def find_determinant(self):
        self.__print_matrice__(super().find_determinant(*self.__create_matrice__()))

Код со * - правильный, там как раз должно получиться 2 аргумента, код в трейсбеке (без распаковки через *) - неправильный - в таком случае в функцию прилетает один аргумент вместо двух.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы