我正在嘗試創建一個基本的導數計算器,并且已經能夠創建代碼以將方程中的值更改為它們的導數。但最后,我所擁有的只是每個術語的單獨派生值,無法正確連接它們,因為我不知道如何將運算子放入適當的位置,因為我無法讓程式識別字符是否在字串是“ ”或“-”以及它所屬的位置。前任:
string = "9x^2 4x - 8"
一旦通過主代碼塊,結果是:
18x 4
這是各個術語的正確推導,但此處缺少運算子,我無法手動連接“ ”,因為用戶可能在同一位置有“ ”或“-”。我已經通過 for 回圈結合 .split() .remove() .replace() 嘗試了各種迭代。如何保留字串和運算元型別中的位置?如有必要,用于計算導數的代碼塊如下。
def derivative():
# Clean up input into usable data
string1 = string.replace("^", "")
string2 = string1.replace(" ", "")
string3 = string2.replace("-", "")
# Turn string in list, clean up list
eq = string3.split(" ")
while("" in eq):
eq.remove("")
# For loop to go through each item in list and turn it into its derivative
dydx = ""
for item in eq:
# Condition only allows a term with both an int, variable and a power
if item[-1].isdigit() and item[-1] != item:
# Derivation power rule
num = int(item[0:-2]) * int(item[-1])
var = item[-2] "^" str(int(item[-1]) - 1)
term = str(num) var
# If the power is 1, it is not necessary to show
if term[-1] == "1":
term = term[:-2]
dydx = (str(term) " ")
else:
dydx = (str(term) " ")
# Condition only allows a term with an int and variable
if item[-1].isalpha():
# Power rule, 1-1 = 0, anything to the 0 power is 1
if len(item) == 1:
term = item.replace(item[-1], "1")
dydx = (str(term) " ")
# 1 multiplied by the number next to it equals the number next to it
else:
term = item.replace(item[-1], "")
dydx = (str(term) " ")
# Only allows numbers through
if item[-1] == item and item.isdigit():
#The derivative of a constant (number) is zero
del item
print(dydx)
uj5u.com熱心網友回復:
我已經弄清楚如何存盤運算元并在以后使用它們。我根據需要為加號和減號創建盡可能多的空變數,在第 1 項、第 2 項和第 3 項之后將它們排序為 1、2、3 等。在 for 回圈中,我然后列舉字串,以便我可以得到相對于它前面的術語的運算元型別。條件通過使用拆分字串中的項來確定等式中每個運算元周圍的區域來確認回圈正在進行哪個迭代,然后 for 回圈遍歷字串該特定部分中的每個字符,直到找到“ ”或“-”。結果然后增加到它各自的空字串。
string = input("Enter equation: ")
countability = string.split()
plus1 = ""
minus1 = ""
plus2 = ""
minus2 = ""
plus3 = ""
minus3 = ""
for count, char in enumerate(string):
if count < (int(len(countability[0])) 3):
if char == " ":
plus1 = " "
elif char == "-":
minus1 = "-"
else:
pass
if count > (int(len(countability[0])) 3) and count < (int(len(countability[0])) (int(len(countability[2])) 6)):
if char == " ":
plus2 = " "
elif char == "-":
minus2 = "-"
else:
pass
if count > (int(len(countability[0])) int(len(countability[2])) 6) and count < (int(len(countability[0])) int(len(countability[2])) (int(len(countability[4]))) 9):
if char == " ":
plus3 = " "
elif char == "-":
minus3 = "-"
else:
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390110.html
上一篇:數學運算不回傳預期結果
下一篇:如何從大十進制恢復初始分數
