如何计算包含数字和算术操作的字符串数组

huangapple go评论107阅读模式
英文:

How to calculate string array with numbers and arithmetic operations

问题

我尝试使用只包含算术符号和数字的数组创建一个计算器,但我不知道如何计算结果,因为我的数组只包含字符串。顺便说一下,我正在使用Python 3.11。

数组示例:

  1. # 示例 1
  2. arr = ['2', '*', '2'] # 2x2 = 4 <- 这应该是结果
  3. # 示例 2 - 更复杂
  4. arr = ['(', '1', '6', '*', '0', ')', '+', '(', '1', '6', '*', '1', ')', '+', '5'] # (16x0) + (16x1) + 5 = 21 <- 这应该是结果

我尝试过使用''.join(arr)将数组连接起来,但它只返回数组中的项目,因为它们都是字符串,而不是结果。

我还尝试过按算术符号拆分数组,并将数字从字符串转换为整数,但是在处理浮点数时遇到了问题,比如1.10、2.42、4.17等等。

英文:

I'm trying to create a calculator using only an array that contains arithmetic symbols and numbers, but I can't figure out how to actually calculate the result since my array will only have strings. By the way, I'm using Python 3.11.

Example of an array:

  1. # Example 1
  2. arr = [&#39;2&#39;, &#39;*&#39;, &#39;2&#39;] # 2x2 = 4 &lt;- This should be the result
  3. # Example 2 - More Complex
  4. arr = [&#39;(&#39;, &#39;1&#39;, &#39;6&#39;, &#39;*&#39;, &#39;0&#39;, &#39;)&#39;, &#39;+&#39;, &#39;(&#39;, &#39;1&#39;, &#39;6&#39;, &#39;*&#39;, &#39;1&#39;, &#39;)&#39;, &#39;+&#39;, &#39;5&#39;] # (16x0) + (16x1) + 5 = 21 &lt;- This should be the result

I have tried joining the array using &#39;&#39;.join(arr), but it only returns the items in the array since they are all strings and not the result.

I have tried joining the array using &#39;&#39;.join(arr), but it only returns the items in the array since they are all strings and not the result.

I have also tried splitting the array by the arithmetic simbols and converting the numbers from strings to integers, but I had some problems with floating numbers, such as 1.10, 2.42, 4.17 and so on.

答案1

得分: 2

Here is the translated code:

尝试使用 eval:

  1. def evaluate_expression(arr):
  2. expression = ''.join(arr)
  3. result = eval(expression)
  4. return result
  5. arr = ['2', '*', '2']
  6. result = evaluate_expression(arr)
  7. print(result) # 输出:4
  8. arr = ['(', '1', '6', '*', '0', ')', '+', '(', '1', '6', '*', '1', ')', '+', '5']
  9. result = evaluate_expression(arr)
  10. print(result) # 输出:21

如果你不想使用 eval() 函数,可以使用堆栈的方式:

  1. def evaluate_expression(arr):
  2. precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
  3. output_queue = []
  4. operator_stack = []
  5. for token in arr:
  6. if token.isdigit() or '.' in token:
  7. output_queue.append(token)
  8. elif token in precedence:
  9. while operator_stack and operator_stack[-1] != '(' and precedence[operator_stack[-1]] >= precedence[token]:
  10. output_queue.append(operator_stack.pop())
  11. operator_stack.append(token)
  12. elif token == '(':
  13. operator_stack.append(token)
  14. elif token == ')':
  15. while operator_stack[-1] != '(':
  16. output_queue.append(operator_stack.pop())
  17. operator_stack.pop()
  18. while operator_stack:
  19. output_queue.append(operator_stack.pop())
  20. stack = []
  21. for token in output_queue:
  22. if token.isdigit() or '.' in token:
  23. stack.append(float(token))
  24. elif token in precedence:
  25. operand2 = stack.pop()
  26. operand1 = stack.pop()
  27. if token == '+':
  28. result = operand1 + operand2
  29. elif token == '-':
  30. result = operand1 - operand2
  31. elif token == '*':
  32. result = operand1 * operand2
  33. elif token == '/':
  34. result = operand1 / operand2
  35. elif token == '^':
  36. result = operand1 ** operand2
  37. stack.append(result)
  38. return stack.pop()
  39. arr = ['2', '*', '2']
  40. result = evaluate_expression(arr)
  41. print(result) # 输出:4.0
  42. arr = ['(', '1', '6', '*', '0', ')', '+', '(', '1', '6', '*', '1', ')', '+', '5']
  43. result = evaluate_expression(arr)
  44. print(result) # 输出:21.0
英文:

try using eval:

  1. def evaluate_expression(arr):
  2. expression = &#39;&#39;.join(arr)
  3. result = eval(expression)
  4. return result
  5. arr = [&#39;2&#39;, &#39;*&#39;, &#39;2&#39;]
  6. result = evaluate_expression(arr)
  7. print(result) # Output: 4
  8. arr = [&#39;(&#39;, &#39;1&#39;, &#39;6&#39;, &#39;*&#39;, &#39;0&#39;, &#39;)&#39;, &#39;+&#39;, &#39;(&#39;, &#39;1&#39;, &#39;6&#39;, &#39;*&#39;, &#39;1&#39;, &#39;)&#39;, &#39;+&#39;, &#39;5&#39;]
  9. result = evaluate_expression(arr)
  10. print(result) # Output: 21

if you dont want to use eval() function, the labor way would be using stack:

  1. def evaluate_expression(arr):
  2. precedence = {&#39;+&#39;: 1, &#39;-&#39;: 1, &#39;*&#39;: 2, &#39;/&#39;: 2, &#39;^&#39;: 3}
  3. output_queue = []
  4. operator_stack = []
  5. for token in arr:
  6. if token.isdigit() or &#39;.&#39; in token:
  7. output_queue.append(token)
  8. elif token in precedence:
  9. while operator_stack and operator_stack[-1] != &#39;(&#39; and precedence[operator_stack[-1]] &gt;= precedence[token]:
  10. output_queue.append(operator_stack.pop())
  11. operator_stack.append(token)
  12. elif token == &#39;(&#39;:
  13. operator_stack.append(token)
  14. elif token == &#39;)&#39;:
  15. while operator_stack[-1] != &#39;(&#39;:
  16. output_queue.append(operator_stack.pop())
  17. operator_stack.pop()
  18. while operator_stack:
  19. output_queue.append(operator_stack.pop())
  20. stack = []
  21. for token in output_queue:
  22. if token.isdigit() or &#39;.&#39; in token:
  23. stack.append(float(token))
  24. elif token in precedence:
  25. operand2 = stack.pop()
  26. operand1 = stack.pop()
  27. if token == &#39;+&#39;:
  28. result = operand1 + operand2
  29. elif token == &#39;-&#39;:
  30. result = operand1 - operand2
  31. elif token == &#39;*&#39;:
  32. result = operand1 * operand2
  33. elif token == &#39;/&#39;:
  34. result = operand1 / operand2
  35. elif token == &#39;^&#39;:
  36. result = operand1 ** operand2
  37. stack.append(result)
  38. return stack.pop()
  39. arr = [&#39;2&#39;, &#39;*&#39;, &#39;2&#39;]
  40. result = evaluate_expression(arr)
  41. print(result) # Output: 4.0
  42. arr = [&#39;(&#39;, &#39;1&#39;, &#39;6&#39;, &#39;*&#39;, &#39;0&#39;, &#39;)&#39;, &#39;+&#39;, &#39;(&#39;, &#39;1&#39;, &#39;6&#39;, &#39;*&#39;, &#39;1&#39;, &#39;)&#39;, &#39;+&#39;, &#39;5&#39;]
  43. result = evaluate_expression(arr)
  44. print(result) # Output: 21.0

huangapple
  • 本文由 发表于 2023年5月7日 08:07:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定