应该生成矩阵,其中行/列的总和被定义为输入列表

时间:2018-04-24 11:29:16

标签: python matrix random

我有一个任务来创建从范围(0-8)中的非负整数生成矩阵的函数

  • 该功能的输入是2个列表:
    • sumForEveryCol
    • sumForEveryRow
  • 每个列表包含每个行/列的值的总和
  • 示例:sumForEveryRow应包含每行的索引(sumForEveryRow [0] =第一行的总和等等。)
  • sumForEveryColumn [0] =第一列的总和.. sumForEveryColumn [1] - 第二列......等。)
  • 每行或每列的总和是40
  • 的常数值
  • 任何单元格的值应在0,8
  • 范围内

我有一些奇怪的想法(下面的代码),但根本没有机会工作..因为算法...一般来说生成这样的矩阵的算法是什么?实现它的最佳方法是什么蟒

示例:

sumsForEveryRow = [4,20,8,8] = constant 40
sumsForEveryCol = [8,8,8,8,8] = constant 40

gen_matrix(sumForEveryRow, sumForEveryCol) should produce random matrix like:

[ 0 , 2 , 0 , 0 , 2 ],  - sum of row 1 should be 4
[ 1 , 2 , 8 , 5 , 4 ],  - sum of row 2 should be 20
[ 3 , 2 , 0 , 3 , 0 ],  - sum of row 3 should be 8
[ 4 , 2 , 0 , 0 , 2 ],  - sum of row 4 should be 8
sum for every column should be
  8   8   8   8   8



import random
import numpy

sumsForEveryCol = [8,8,8,8,8]
sumsForEveryRow = [4,20,8,8]
def gen_matrix(sumForEveryCol, sumForEveryRow):
    sum = 40
    max_value_cell = 8
    num_of_rows = len(sumsForEveryRow)
    num_of_cols = len(sumsForEveryCol)
    matrix = numpy.zeros((num_of_rows, num_of_cols), dtype=numpy.int)

    for i in range(0, num_of_rows - 1):
        cur_row_sum = sumsForEveryRow[i]
        for j in range(0, num_of_cols - 1):
            if max_value_cell >= cur_row_sum:
                if cur_row_sum == 0:
                    matrix[i][j] = 0
                else:
                    # Dont generate 0 values ????
                    rand_digit = random.randint(1, cur_row_sum)
                    cur_row_sum = cur_row_sum - rand_digit
                    matrix[i][j] = rand_digit
            else:
                rand_digit = random.randint(0, max_value_cell)
                matrix[i][j] = rand_digit
                cur_row_sum = cur_row_sum - rand_digit


    return matrix

0 个答案:

没有答案
相关问题