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

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

How to calculate string array with numbers and arithmetic operations

问题

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

数组示例:

# 示例 1
arr = ['2', '*', '2']  # 2x2 = 4 <- 这应该是结果

# 示例 2 - 更复杂
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:

# Example 1
arr = [&#39;2&#39;, &#39;*&#39;, &#39;2&#39;]  # 2x2 = 4 &lt;- This should be the result

# Example 2 - More Complex
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:

def evaluate_expression(arr):
    expression = ''.join(arr)
    result = eval(expression)
    return result
arr = ['2', '*', '2']
result = evaluate_expression(arr)
print(result)  # 输出:4

arr = ['(', '1', '6', '*', '0', ')', '+', '(', '1', '6', '*', '1', ')', '+', '5']
result = evaluate_expression(arr)
print(result)  # 输出:21

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

def evaluate_expression(arr):
    precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}

    output_queue = []
    operator_stack = []
    for token in arr:
        if token.isdigit() or '.' in token:
            output_queue.append(token)
        elif token in precedence:
            while operator_stack and operator_stack[-1] != '(' and precedence[operator_stack[-1]] >= precedence[token]:
                output_queue.append(operator_stack.pop())
            operator_stack.append(token)
        elif token == '(':
            operator_stack.append(token)
        elif token == ')':
            while operator_stack[-1] != '(':
                output_queue.append(operator_stack.pop())
            operator_stack.pop()
    while operator_stack:
        output_queue.append(operator_stack.pop())

    stack = []
    for token in output_queue:
        if token.isdigit() or '.' in token:
            stack.append(float(token))
        elif token in precedence:
            operand2 = stack.pop()
            operand1 = stack.pop()
            if token == '+':
                result = operand1 + operand2
            elif token == '-':
                result = operand1 - operand2
            elif token == '*':
                result = operand1 * operand2
            elif token == '/':
                result = operand1 / operand2
            elif token == '^':
                result = operand1 ** operand2
            stack.append(result)

    return stack.pop()

arr = ['2', '*', '2']
result = evaluate_expression(arr)
print(result)  # 输出:4.0

arr = ['(', '1', '6', '*', '0', ')', '+', '(', '1', '6', '*', '1', ')', '+', '5']
result = evaluate_expression(arr)
print(result)  # 输出:21.0
英文:

try using eval:

def evaluate_expression(arr):
expression = &#39;&#39;.join(arr)
result = eval(expression)
return result
arr = [&#39;2&#39;, &#39;*&#39;, &#39;2&#39;]
result = evaluate_expression(arr)
print(result)  # Output: 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;]
result = evaluate_expression(arr)
print(result)  # Output: 21

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

def evaluate_expression(arr):
precedence = {&#39;+&#39;: 1, &#39;-&#39;: 1, &#39;*&#39;: 2, &#39;/&#39;: 2, &#39;^&#39;: 3}
output_queue = []
operator_stack = []
for token in arr:
if token.isdigit() or &#39;.&#39; in token:
output_queue.append(token)
elif token in precedence:
while operator_stack and operator_stack[-1] != &#39;(&#39; and precedence[operator_stack[-1]] &gt;= precedence[token]:
output_queue.append(operator_stack.pop())
operator_stack.append(token)
elif token == &#39;(&#39;:
operator_stack.append(token)
elif token == &#39;)&#39;:
while operator_stack[-1] != &#39;(&#39;:
output_queue.append(operator_stack.pop())
operator_stack.pop()
while operator_stack:
output_queue.append(operator_stack.pop())
stack = []
for token in output_queue:
if token.isdigit() or &#39;.&#39; in token:
stack.append(float(token))
elif token in precedence:
operand2 = stack.pop()
operand1 = stack.pop()
if token == &#39;+&#39;:
result = operand1 + operand2
elif token == &#39;-&#39;:
result = operand1 - operand2
elif token == &#39;*&#39;:
result = operand1 * operand2
elif token == &#39;/&#39;:
result = operand1 / operand2
elif token == &#39;^&#39;:
result = operand1 ** operand2
stack.append(result)
return stack.pop()
arr = [&#39;2&#39;, &#39;*&#39;, &#39;2&#39;]
result = evaluate_expression(arr)
print(result)  # Output: 4.0
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;]
result = evaluate_expression(arr)
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:

确定