Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

Use re (regex) to do this pattern finding stuff, and use input to get the text entered:

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

Example Output:

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

Post a Comment for "Storing Specific Whole Numbers - Python"