Unable to successfully compare two strings

Viewed 51
phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
new_phrase = phrase.split("+")#splits phrase at the + operator
print(len(new_phrase))

for item in new_phrase:
    c = (new_phrase>new_phrase.index("^"))#actul differentiation part c is the power of whatever (this is where python has a problem) line 6
    y = (new_phrase<(new_phrase.index("^")-1))# y is the number before x 
    print(float(c)*float(y)+"^"+float(c)-1)# this is the final differentiated answer

#however it keeps saying ^ is not in the list how can I fix this?

Using Python 3.8.1

The actual main code is starting at for item. This is where the problem occurs, as the input is supposed to be 3x^2+2x^1+-4x^4, or something like, that but Python cannot seem to find where the power to sign "^" in the list thus the rest of the code from the " c =" does not work.

2 Answers

I have created a working version from your code. Mainly the problem was the type inconsistency. Furthermore I have added several comments to the code for the better understanding and it contains several prints for the debugging.

Code:

phrase = input("Enter the equation you want differentiated: ").lower()  # 3x^2+2x^1+-4x^4
new_phrase = phrase.split("+")  # splits phrase at the + operator
print("Elements: {}".format(new_phrase))  # Print elements of differential
for item in new_phrase:
    print("Tested element: {}".format(item))
    c = float(item.split("^")[-1])  # Get after part of "^" character
    y = float(item.split("^")[0].replace("x", ""))  # Get before part of "^" character (withour "x")
    print("c={} ; y={}".format(c, y))

    print(
        "Result: {}^{}".format(float(c) * float(y), float(c) - 1)
    )  # this is the final differentiated answer

Output:

>>> python3 test.py 
Enter the equation you want differentiated: 3x^2+2x^1+-4x^4
Elements: ['3x^2', '2x^1', '-4x^4']
Tested element: 3x^2
c=2.0 ; y=3.0
Result: 6.0^1.0
Tested element: 2x^1
c=1.0 ; y=2.0
Result: 2.0^0.0
Tested element: -4x^4
c=4.0 ; y=-4.0
Result: -16.0^3.0

Here is some Python script that can differentiate algebraic expressions based on your code.

phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
# Splits phrase at the + operator
split_phrase = phrase.split("+")
# Placeholder for the differentiated phrase
new_phrase = ""

for item in split_phrase:
    # Exponent - index of ^ - 1
    c = int(item[item.index("^") + 1:])
    #Coefficient - from 0 to index of x - 1
    y = int(item[0:item.index("x")])
    #Reconstructs the algebraic expression
    new_phrase += str(c*y) + "x^" + str(c-1)
    # Adds a plus sign if it is not the last item
    if split_phrase.index(item) != len(split_phrase) - 1:
        new_phrase += "+"
Related