Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...