A
A
Arseniy Korlaisovich2020-09-19 14:42:19
Python
Arseniy Korlaisovich, 2020-09-19 14:42:19

Python how to extract number before x² and x?

Shalom everyone, I'm new to programming and the following problem arose:
There is an expression (it can be anything)
For example: 3x² + 16 - 7x
I need to get the number 3 in front of x² and add "a" to the variable, get the number -7 in front of x and add to the variable "b", well, get the number 16 and add this number to the variable "c", how can this be done? It is important that the order may not be observed, i.e. I could also write 13 -4x + x².
I will be very grateful for your help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2020-09-19
@XTerris

You can split into separate numbers using split(), discard the signs. And process an array of 3 elements.
Then check each:
1: if the last character is x, then take everything before it(number[:-1] and reduce to a number.
2: if the penultimate character is x, then take everything before it(number[:-2]
3: if x is not, then just cast to a number.

s = input().split()
for i in s:
    if len(i) > 2 and i[-2] == 'x':
        a = int(i[:-2])
    elif len(i) == 2 and i[0] == 'x':
        a = 1
    elif i[-1] == 'x':
        b = int(i[:-1]) if len(i) > 1 else 0
    elif i != '0' and i.isdigit():
        c = int(i)

print(a, b, c)

PS I redid the code, because I messed with lambdas

W
Wladislavich, 2020-09-21
@Wladislavich

Arseny, good afternoon!
I recommend that you look at the basic articles or help about the re module for regular expressions in python. This is what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question