私は現在 Java から Python に移行しており、( Sympy のようなカスタム モジュールを使用せずに) 中置表記の数式で記号演算を実行できる電卓を作成しようとするタスクを引き受けました。現在、スペースで区切られた文字列を受け入れるように構築されており、(、)、+、-、*、および / 演算子のみを実行できます。残念ながら、シンボリック式を単純化するための基本的なアルゴリズムを理解できません。
たとえば、文字列 '2 * ( ( 9 / 6 ) + 6 * x )' が与えられた場合、プログラムは次の手順を実行する必要があります。
- 2 * (1.5 + 6 * x)
- 3 + 12 * ×
しかし、2を配布するときにプログラムにxを無視させることはできません。さらに、「x * 6 / x」を処理して、単純化後に「6」を返すにはどうすればよいですか?
編集:明確にするために、「シンボリック」とは、残りの計算を実行しながら、出力に「A」や「f」などの文字を残すことを意味しました。
編集 2: 私は (ほとんど) コードを完成させました。今後誰かがこの投稿に出くわした場合、または興味がある場合は、ここに投稿します。
def reduceExpr(useArray):
# Use Python's native eval() to compute if no letters are detected.
if (not hasLetters(useArray)):
return [calculate(useArray)] # Different from eval() because it returns string version of result
# Base case. Returns useArray if the list size is 1 (i.e., it contains one string).
if (len(useArray) == 1):
return useArray
# Base case. Returns the space-joined elements of useArray as a list with one string.
if (len(useArray) == 3):
return [' '.join(useArray)]
# Checks to see if parentheses are present in the expression & sets.
# Counts number of parentheses & keeps track of first ( found.
parentheses = 0
leftIdx = -1
# This try/except block is essentially an if/else block. Since useArray.index('(') triggers a KeyError
# if it can't find '(' in useArray, the next line is not carried out, and parentheses is not incremented.
try:
leftIdx = useArray.index('(')
parentheses += 1
except Exception:
pass
# If a KeyError was returned, leftIdx = -1 and rightIdx = parentheses = 0.
rightIdx = leftIdx + 1
while (parentheses > 0):
if (useArray[rightIdx] == '('):
parentheses += 1
elif (useArray[rightIdx] == ')'):
parentheses -= 1
rightIdx += 1
# Provided parentheses pair isn't empty, runs contents through again; else, removes the parentheses
if (leftIdx > -1 and rightIdx - leftIdx > 2):
return reduceExpr(useArray[:leftIdx] + [' '.join(['(',reduceExpr(useArray[leftIdx+1:rightIdx-1])[0],')'])] + useArray[rightIdx:])
elif (leftIdx > -1):
return reduceExpr(useArray[:leftIdx] + useArray[rightIdx:])
# If operator is + or -, hold the first two elements and process the rest of the list first
if isAddSub(useArray[1]):
return reduceExpr(useArray[:2] + reduceExpr(useArray[2:]))
# Else, if operator is * or /, process the first 3 elements first, then the rest of the list
elif isMultDiv(useArray[1]):
return reduceExpr(reduceExpr(useArray[:3]) + useArray[3:])
# Just placed this so the compiler wouldn't complain that the function had no return (since this was called by yet another function).
return None