首页 > 解决方案 > 无法成功比较两个字符串

问题描述

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?

使用 Python 3.8.1

实际的主要代码从for item. 这就是问题发生的地方,因为输入应该是3x^2+2x^1+-4x^4,或类似的东西,但 Python 似乎无法找到在"^"列表中签名的权力,因此“c =”中的其余代码不起作用。

标签: python-3.x

解决方案


我已经根据您的代码创建了一个工作版本。主要问题是类型不一致。此外,为了更好地理解,我在代码中添加了几条注释,它包含几个用于调试的打印。

代码:

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

输出:

>>> 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

推荐阅读