Матрицы в Python

prarabacha

Новичок
Пользователь
Окт 27, 2021
15
1
3
Здраствуйте, нужна помощь в подсчете определителя матрицы, используя правило перестановок.
И также создании троих функций: функция создания списка перестановок, функция подсчета произведений и функция подсчета общей суммы.
Всё, что вышло на данный момент. Был бы признателен в помощи.
Код:
import numpy as np
import itertools

while True:

    def matrix_size(message):
        try:
            matrix_size = int(input(message))
            if matrix_size <= 0 and matrix_size > 10: raise Typerror
            except TypeError:
                print('Input should be more than 0 and less than 10')
                return 0
            return matrix_size

    def random_matrix(dim):
        """
        The function generates dim x dim array of integers
        between 0 and 10
        """
        matrix = np.random.randint(10, size = (dim, dim))
        return matrix
 
  • Мне нравится
Реакции: Student

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 672
478
83
Код:
import numpy as np
import itertools


def write(matrix_size):
    """
    This function defines matrix size from 0 to 10.
    """
    try:
        matrix_size = int(input())
        if matrix_size <= 0 or matrix_size > 10: raise Typerror
    except TypeError:
            print('Input should be more than 0 and less than 10')
            return 0
    return matrix_size

def random_matrix(dim):
    """
    The function generates dim x dim array of integers
    between 0 and 10.
    """
    matrix = np.random.randint(10, size = (dim, dim))
    return matrix

def list_of_permutations(matrix):
    """
    This function designed to create a list of all permutations of numbers from 1 to n + 1.
    """
    permutation = list(permutations(''.join(map(str,range(1, n+1))), n))
    return permutation
   
def multiplication(list_of_permutations):
    multiplication = []
    for list_of_permutations in matrix_permutation:
        temp = 1
        for x in list_of_permutations:
            temp *= x
        multiplication.append(temp)
        return multiplication
   
def add(matrix, matrix_size):
    return sum(matrix, matrix_size)

while True:
    try :
        dim=int(input("Enter a dim of matrix : "))
        random_matrix(dim)
    except ValueError:
        print("Nope. It`s must be a positive intenger number!")
    else:
        break

    print('det A=',add(multiplication(list_of_permutations(random_matrix(dim)))))

    repeat = input('Input "mi scusi" to enter one more line of elements or another symbol to exit  : ')
    if repeat == "mi scusi":
        continue
    else:
        break
в трае елсе брейк уберите
Python:
...

while True:
    try :
        dim=int(input("Enter a dim of matrix : "))
        random_matrix(dim)
    except ValueError:
        print("Nope. It`s must be a positive intenger number!")
#    else:
#        break

...

дальше у вас начинаются ошибки, что половина имен не определено...
 

prarabacha

Новичок
Пользователь
Окт 27, 2021
15
1
3
Вот что вышло, но программа не выводит результат. Если кто-то знает, был бы благодарен в помощи.

Код:
import numpy as np
import itertools

while True:
    def write(matrix_size):
        """
        This function defines matrix size from 0 to 10.
        """
        try:
            matrix_size = int(input())
            if matrix_size <= 0 or matrix_size > 10: raise Typerror
        except TypeError:
                print('Input should be more than 0 and less than 10')
                return 0
        return matrix_size

    def random_matrix(dim):
        """
        The function generates dim x dim array of integers
        between 0 and 10.
        """
        matrix = np.random.randint(10, size = (dim, dim))
        return matrix

    def list_of_permutations(matrix):
        """
        This function designed to create a list of all permutations of numbers from 1 to n + 1.
        """
        permutation = list(permutations(''.join(map(str,range(1, n+1))), n))
        return permutation
    
    def multiplication(list_of_permutations):
        multiplication = []
        for list_of_permutations in matrix_permutation:
            temp = 1
            for x in list_of_permutations:
                temp *= x
            multiplication.append(temp)
            return multiplication
    
    def add(matrix, matrix_size):
        return sum(matrix, matrix_size)

    try :
        dim=int(input("Enter a dim of matrix : "))
        random_matrix(dim)
    except ValueError:
        print("Nope. It`s must be a positive intenger number!")
    else:
        break

    print('det A=',add(multiplication(list_of_permutations(random_matrix(dim)))))

    repeat = input('Input "mi scusi" to enter one more line of elements or another symbol to exit  : ')
    if repeat == "mi scusi":
        continue
    else:
        break
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 672
478
83
наверное нужно цикл while после функций написать, где try начинается...
 

prarabacha

Новичок
Пользователь
Окт 27, 2021
15
1
3
наверное нужно цикл while после функций написать, где try начинается...
Не помогло
 

prarabacha

Новичок
Пользователь
Окт 27, 2021
15
1
3
ну вы в вечном цикле определяете функции, уберите этот цикл, функции определите без него, а после функций где трай, делаете уже цикл
Код:
import numpy as np
import itertools


def write(matrix_size):
    """
    This function defines matrix size from 0 to 10.
    """
    try:
        matrix_size = int(input())
        if matrix_size <= 0 or matrix_size > 10: raise Typerror
    except TypeError:
            print('Input should be more than 0 and less than 10')
            return 0
    return matrix_size

def random_matrix(dim):
    """
    The function generates dim x dim array of integers
    between 0 and 10.
    """
    matrix = np.random.randint(10, size = (dim, dim))
    return matrix

def list_of_permutations(matrix):
    """
    This function designed to create a list of all permutations of numbers from 1 to n + 1.
    """
    permutation = list(permutations(''.join(map(str,range(1, n+1))), n))
    return permutation
    
def multiplication(list_of_permutations):
    multiplication = []
    for list_of_permutations in matrix_permutation:
        temp = 1
        for x in list_of_permutations:
            temp *= x
        multiplication.append(temp)
        return multiplication
    
def add(matrix, matrix_size):
    return sum(matrix, matrix_size)

while True:
    try :
        dim=int(input("Enter a dim of matrix : "))
        random_matrix(dim)
    except ValueError:
        print("Nope. It`s must be a positive intenger number!")
    else:
        break

    print('det A=',add(multiplication(list_of_permutations(random_matrix(dim)))))

    repeat = input('Input "mi scusi" to enter one more line of elements or another symbol to exit  : ')
    if repeat == "mi scusi":
        continue
    else:
        break
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 672
478
83
ща я посмоотрю
 

Форум IT Специалистов