Sunday, July 21, 2013

Python 解析线性方程组

~/projects/python/parse-linear-equations.py.html

我姐是做会计的,有时需要做一些简单的运算,比如线性方程组。当然能解决这类问题的软件 有很多,但是对于这么一个小问题而言有点「大炮打蚊子」之说了,而且她还得去学习使用一个 工具。

我此前用C写了一个线性代数基本运算库,其中包括最基本的高斯消元法,正好能派上用场,但是 C可是不善长跟用户打交道,尤其是语言(在此指文本)解析方面,所以我就用Python写了一个解析 方程组的工具,然后利用Python的ctypes模块去调用C。而且Python有MS的Excel的API。

代码如下:

 1 #!/usr/bin/env python
 2 #coding=utf-8
 3 
 4 import re
 5 
 7 def parse_linear_equations(equations):
 8     '''
 9     according equations make augmented_matrix
10     eg.
11       x1 + x2 + 2x3 = 4
12       2x1 - 6x3 = 9
13     can get augmented_matrix as follow:
14       x1 x2 x3 __b__
15       1  1  2    4
16       2  0  6    9
17     '''
18     dim = len(equations)                    # 约束方程数
19     augmented_matrix = {'__b__':[0]*dim}    # 初始化增广矩阵
20     parse_ptrn = r'([+-]?\d*)(\w+)'         # 第一个括号匹配系数, 第二个匹配变量名
21     parse_obj = re.compile(parse_ptrn)
22     for i in range(dim):
23         e = ''.join(equations[i].split())              # 去除所有空格
24         left, right = e.split('=')
25         augmented_matrix['__b__'][i] = float(right)
26         for coeff, var in parse_obj.findall(left):
27             if coeff == '': coeff = 1
28             elif coeff == '-': coeff = -1
29             else:
30                 coeff = float(coeff)
31             if var not in augmented_matrix:
32                 augmented_matrix[var] = [0] * dim   # 新增变量元
33             augmented_matrix[var][i] = coeff
34     return augmented_matrix
35 
36 if __name__ == '__main__':
37     equations = ['2x + 7y + 9z = 18',
38                  '3x + 4y = 9',
39                  'x + 4z = 7']
40     result = parse_linear_equations(equations)
41     print result

源代码托管在github上,其中这部分在这里,线性代数库在这里


版权声明
本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者Saturn和本文原始地址:
https://ndtm-idea.blogspot.com/2013/07/python.html

0 comments:

Post a Comment