python-3.x - 无法成功比较两个字符串
问题描述
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 =”中的其余代码不起作用。
解决方案
我已经根据您的代码创建了一个工作版本。主要问题是类型不一致。此外,为了更好地理解,我在代码中添加了几条注释,它包含几个用于调试的打印。
代码:
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
推荐阅读
- asp.net-mvc - 从 .NET Framework ASP.NET Intranet 应用程序使用 Microsoft Graph
- python - 如何在python中制作查找和替换系统
- sql - 3种方式的复杂案例
- cordova - 在科尔多瓦钩子上执行 gulp4 任务
- r - 在 RShiny 中将对象分配给 .GlobalEnv
- pandas - 从整个数据框中删除特定的字符串值而不指定列或行
- python - 通过 Python 用数字标记泰勒图
- sql - SQL中的数据透视表具有多列
- excel - 有没有办法根据 Power Query 中的条件从另一列应用最小日期和相关值?
- binary - 邮递员中的二进制体