Skip to content Skip to sidebar Skip to footer

Calculating The Coefficients Of A Differentiated Polynomial Using Re.compile And Searching In Python

Testing the polynomial '2x^3+4x^2+8x-16' my code below outputs [6, 8] as the coefficients of the differentiated polynomial. However, the output should be [6, 8, 8]. Why is the func

Solution 1:

This problem can be solved much more easily using negative lookbehind assertions.

COEFFICIENT_PATTERN = re.compile(r"(?<!x\^)(?<!x\^-)-?\d+")
coefficients = [int(c) for c in COEFFICIENT_PATTERN.findall(polynomial)]

This solution uses two negative lookbehinds for x^ and x^- (because look behinds must be fixed length). So it reads "get me all integers not preceded by x^.

>>> COEFFICIENT_PATTERN.findall('2x^3+4x^2+8x-16')
['2', '4', '8', '-16']

Post a Comment for "Calculating The Coefficients Of A Differentiated Polynomial Using Re.compile And Searching In Python"