存储特定整数

2024-04-20 03:06:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找到一个简单的方法来存储一个特定的整数,比如说一个多项式。如果用户输入:

2x^3 + 5x^2 - 8x + 3

我基本上想创建一个列表(认为这将是最简单的方法)将[2,5,-8,3]作为f(x),然后再创建另一个列表作为g(x),这样我以后就可以添加/减去它们了。我完全搞不懂如何做到这一点,我希望用户输入整个多项式一次。我不想我的程序要求它的一部分。谢谢:) (PS我要出去大约半小时/45分钟,所以我回家后会回到这里。再次感谢!)你知道吗


Tags: 方法用户程序列表整数ps回家
2条回答

你可以使用“理解”多项式的sympy。不过,您仍然需要手动插入乘法符号:

import re, sympy

# example
s = '2x^3 + 5x^2 - 8x + 3'
# replace juxtapostion with explicit multiplication
sp = re.sub('[0-9][a-z]', lambda m: '*'.join(m.group()), s)
sp
# '2*x^3 + 5*x^2 - 8*x + 3'
# no we can create a poly object
p = sympy.poly(sp)
p
Poly(2*x**3 + 5*x**2 - 8*x + 3, x, domain='ZZ')
# getting coefficients is easy
p.coeffs()
[2, 5, -8, 3]
# and we can do all sorts of other poly stuff 
p*p
Poly(4*x**6 + 20*x**5 - 7*x**4 - 68*x**3 + 94*x**2 - 48*x + 9, x, domain='ZZ')
...

使用re(regex)查找模式,使用input输入文本:

import re
a=input('Enter your stuff: ')
s=re.sub('[a-zA-Z^]','',a)
print([int('-'+i[0]) if s[s.index(i)-2]=='-' else int(i[0]) for i in re.split(' [+|-] ',s)])

输出示例:

Enter your stuff: 2x^3 + 5x^2 - 8x + 3
[2, 5, -8, 3]

相关问题 更多 >