【问题标题】:Generate equations using a 2D/3D array as input使用 2D/3D 数组作为输入生成方程
【发布时间】:2021-08-05 16:45:13
【问题描述】:

我遇到了从二维数组输入生成方程的问题。 方程只需要用一个变量(具有 i,j 索引)对行和列进行求和

例子:

Input :
[1 2 3 4 5
 6 7 8 9 10
 11 12 13 14 15
]

Outputs :
1. (row-sum with Xs) : 
x11*1 + x12*2 + x13*3 + x14*4 + x15*5 
x21*6 + x22*7 + x23*8 + x24*9 + x25*10 
x31*11 + x32*12 + x33*13 + x34*14 + x35*15 

2. (column-sum with Xs) :
x11*1 + x21*6 + x31*11
x12*2 + x22*7 + x31*12
x13*3 + x23*8 + x33*13
x14*4 + x24*9 + x34*14
x15*5 + x25*10 + x35*15

当输入可能发生变化时,最有效的书写方式是什么? 输入可以是 2 维或 3 维数组,但不能超过。

【问题讨论】:

  • 您的输入是列表列表(系数矩阵),而您的输出是字符串吗?
  • @CamiloMartínez - 是的,输入是矩阵系数的列表,输出是带有上述 Xs 示例的字符串。
  • 你能举一个输入是 3 维的例子吗?
  • @CamiloMartínez - 它将采用表格格式 - 在一个表格中,3 个维度作为 3 列,值作为第四列。如果上述输入不够有用,我们可以以类似的方式对两者进行标准化。

标签: python multidimensional-array equation


【解决方案1】:

我不明白您想要的 3 维列表(列表列表列表)的输出,但希望这可以是一个好的开始。

def to_eq(coeffs: list, column_sum: bool = False, var: str = 'x') -> str:
    if column_sum: # Transpose the input list of lists
        coeffs = [list(k) for k in zip(*coeffs)]
        output = '\n'.join(
            ' + '.join(var + str(j+1) + str(i+1) for j, coeff in enumerate(line)) 
            for i, line in enumerate(coeffs)
        )
    else: 
        output = '\n'.join(
            ' + '.join(var + str(i+1) + str(j+1) for j, coeff in enumerate(line)) 
            for i, line in enumerate(coeffs)
        )
    return output

它看起来很重复,但由于您想要一个有效的实现,我把if 放在外面。 ij 的反转以匹配您的示例可能由比我更有创造力的人在一行中完成。我不知道你在你的例子中是否真的是这个意思。通常的表示法是先有行,后有列,即ij

>>> coeffs = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> to_eq(coeffs)
    x11 + x12 + x13 + x14 + x15
    x21 + x22 + x23 + x24 + x25
    x31 + x32 + x33 + x34 + x35
>>> to_eq(coeffs, column_sum=True)
    x11 + x21 + x31
    x12 + x22 + x32
    x13 + x23 + x33
    x14 + x24 + x34
    x15 + x25 + x35

顺便说一句,transpose a list of lists 有很多方法。除了我在这里使用的选项之外,请查看其他选项。

一些测试:

>>> cols = 100000
>>> max_ = 10000000
>>> coeffs = [[i + j for i in range(cols)] for j in range(0, max_, cols)]
>>> print(len(coeffs), ' by ', len(coeffs[0]))
    100  by  100000

>>> %timeit to_eq(coeffs)
    5.66 s ± 90.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit to_eq(coeffs, column_sum=True)
    6.28 s ± 118 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

>>> cols = 1000
>>> max_ = 10000
>>> coeffs = [[i + j for i in range(cols)] for j in range(0, max_, cols)]
>>> print(len(coeffs), ' by ', len(coeffs[0]))
    10  by  1000

>>> %timeit to_eq(coeffs)
    5.59 ms ± 308 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)  
>>> %timeit to_eq(coeffs, column_sum=True)
    5.98 ms ± 111 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多