计算串中给定电路的总电阻

2024-04-26 04:55:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力解决这个问题。问题是:

Given a string describing the circuit, calculate the total resistance of the circuit.

下面是一个例子:

  • 输入:3 5 S
  • 预期输出:8

字符串中的操作数由运算符跟踪,表示电阻是串联还是并联。然而,让我们分析一个更复杂的电路:

  • 输入:3 5 S 0 P 3 2 S P
  • 预期输出:0

循序渐进:

  1. 输入开头的3 5 S给出了8,因此第一个中间步骤是字符串8 0 P 3 2 S P。在
  2. 8 0 P给我们0,因为一个电阻短路,因此我们得到{}。在
  3. 3 2 P5。在
  4. 最后0 5 P是{}。在

这是我的尝试。我尝试使用递归,因为它似乎是一个可以用这种方式解决的问题。首先我编写了一个helper函数:

def new_resistance(a,b,c):
if c == '':
    if int(a) == 0 or int(b) == 0:
        return 0
    else:
        return 1/(1/int(a) + 1/int(b))
else:
    return int(a) + int(b)

以及计算电路新电阻的函数:

^{pr2}$

该程序的思想是从列表的开头开始,计算列表的前三个元素的电阻,然后将它们附加到新列表的开头(不包含这三个元素),然后使用新列表再次调用函数。这样做,直到只剩下一个整数并返回整数。在

感谢任何帮助。在


更新:

问题的解决方案,使用一个堆栈和一个类似于NPR解析器的解析器。在

operator_list = set('PS')

def resistance(circuit):
  temp = circuit.split(" ")
  stack = []
  for char in temp:
      if char in operator_list:
          a = new_resistance(stack.pop(), stack.pop(), char)
          print(a)
          stack.append(a)
      else:
          print(char)
          stack.append(char)
  return stack[-1]

def new_resistance(a,b,c):
  if c == 'P':
      if float(a) == 0 or float(b) == 0:
          return 0
      else:
          return 1/(1/float(a) + 1/float(b))
  else:
      return float(a) + float(b)

circuit = '3 5 S 0 P 3 2 S P'
resistance(circuit)

# 3
# 5
# 8.0
# 0
# 0
# 3
# 2
# 5.0
# 0


Tags: the字符串列表newreturnifstackdef
3条回答

问题是一旦到达0 3 2 S P,就不能简单地获取前3个元素。您需要查找number number S_or_P,无论它在字符串中的哪个位置。在

您可以将正则表达式用于此任务:

import re

circuit = '3 5 S 0 P 3 2 S P'

pattern = re.compile('(\d+) +(\d+) +([SP])')

def parallel_or_serie(m):
  a, b, sp = m.groups()
  if sp == 'S':
    return str(int(a) + int(b))
  else:
    if a == '0' or b == '0':
      return '0'
    else:
      return str(1/(1/int(a) + 1/int(b)))

while True:
  print(circuit)
  tmp = circuit
  circuit = re.sub(pattern, parallel_or_serie, circuit, count=1)
  if tmp == circuit:
    break

# 3 5 S 0 P 3 2 S P
# 8 0 P 3 2 S P
# 0 3 2 S P
# 0 5 P
# 0

注意,1 1 P将输出0.5。您可以将int替换为float,并修改regex以解析浮点。在

归功于@none谁第一次认识了RPN。在

我想起了往事。20世纪80年代,我在8位计算机上玩第四种语言。好,回到Python:

circuit = '3 5 S 0 P 3 2 S P'

stack = []
for n in circuit.split():
    if n == 'S':
        r1 = stack.pop()
        r2 = stack.pop()
        stack.append(r1+r2)
    elif n == 'P':
        r1 = stack.pop()
        r2 = stack.pop()
        stack.append(0.0 if (r1 == 0 or r2 == 0) else 1/(1/r1+1/r2))
    else:
        stack.append(float(n))

assert len(stack) == 1    
print(stack[0])

您的程序,或者更具体地说您的parser,似乎依赖于{},而这又是{a2}的一个小变体。简单地说,RPN是一种抽象表示,其中算术表达式的运算符跟在操作数之后,而在{}中,运算符之前。基于此表示的解析器可以通过使用堆栈轻松实现(通常不需要解释括号)。在

如果你的任务是开发这个解析器,你可以从我上面链接的维基百科文章中得到一些输入。在

相关问题 更多 >