简体   繁体   English

存储特定的整数-Python

[英]Storing Specific Whole Numbers - Python

I need to find a simple method for storing a specific whole number in say- a polynomial. 我需要找到一种简单的方法来存储特定的整数,例如多项式。 If the user inputs: 如果用户输入:

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

I basically want to create a list (thinking this will be the easiest method) of [2, 5, -8, 3] as f(x) and then another list for g(x) so I can add them/subtract them later. 我基本上想创建一个[2,5,-8,3]的列表(认为这将是最简单的方法)作为f(x),然后为g(x)创建另一个列表,这样我以后就可以添加/减去它们。 I'm completely stumped on how to do this and I want the user to input the whole polynomial at once. 我对如何执行此操作完全感到困惑,我希望用户立即输入整个多项式。 I dont want my program to ask it in parts. 我不希望我的程序分部分询问。 Thanks:) (PS I'm going out for about half an hour/45 min so I will get back to this when I am home. Thanks again!) 谢谢:)(PS,我要出去大约半小时/ 45分钟,所以我回到家时会回到这里。再次感谢!)

You could use sympy which "understands" polynomials. 您可以使用“理解”多项式的sympy。 You'd still have to insert multiplication signs manually, though: 不过,您仍然必须手动插入乘法符号:

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')
...

Use re (regex) to do this pattern finding stuff, and use input to get the text entered: 使用re (正则表达式)执行此模式查找内容,并使用input获取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)])

Example Output: 示例输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM