Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use sympy which "understands" polynomials. 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')
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...