Python多项式输入

时间:2018-01-24 15:29:32

标签: python variable-assignment string-parsing

我在高中,(不要评判)我最近一直致力于编写合成分频计算器,截至目前,它的确有效。但是,从下面的输出和输入记录中可以看出,信息收集阶段非常繁琐。

Enter the degree of the numerator (max 12):
 3
Enter the coefficient of x^3 in the numerator:
 2
Enter the coefficient of x^2 in the numerator:
 -6
Enter the coefficient of x in the numerator:
 -3
Enter the value of the constant in the numerator:
 8
Enter the degree of the denominator (max 2):
 2
Enter the coefficient of x^2 in the denominator:
 7
Enter the coefficient of x in the denominator:
 -5
Enter the value of the constant in the denominator:
 3
The quotient of the numerator 2x^3-6x^2-3x+8 and the denominator 7x^2-5x+3
 is equal to (2/7)x+(-32/49)+((-349/49)x+(488/49))/(7x^2-5x+3) which is
 (0.285714285714)x+(-0.65306122449)+((-7.12244897959)x+(9.95918367347))/(7x^2-5x+3)
 in rounded decimal format.

我想要的是:

import re
numerator = '7x^12-6x^5+2/3x-19'
for m in re.finditer( r'(-{0,1}\d*)x\^{0,1}(-{0,1}\d*)', numerator):
  coef, expn = list(map( lambda x: x if x != '' and x != '-' else x + '1' , m.groups( ) ))
  print ('coef:{}, exp:{}'.format( coef, expn ))

这样的事情:

import re
numerator = '7x^12-6x^5+2/3x-19'
for m in re.finditer( r'(-{0,1}\d*)x\^{0,1}(-{0,1}\d*)', numerator):
  coef, expn = list(map( lambda x: x if x != '' and x != '-' else x + '1' , m.groups( ) ))
  [A, B, C, ... , M] = #??? 

#so "print [A, B, C, ... , M]" would print "7, 0, 0, 0, ... ,-6 , ... , -19"
#currently, it completly misses the point and prints "coef:7, exp:12, coef:-6, exp:5, coef:3, exp:-19"

目标是能够简单地输入 2x ^ 3-6x ^ 2-3x + 8 7x ^ 2-5x + 3 ,或任何其他组合多项式,并让程序将每个系数转换为变量。如果这很复杂(我确信它可以完成,但我没有任何想法),那么让程序看看括号之间的内容可能会更容易。这将要求用户在输入多项式时要更加小心,因为单个额外的“(”可能会使整个事情变得混乱,但它会更容易,我会满意。

0 个答案:

没有答案