计算字符串中给出的电路的总电阻

Calculate the total resistance of a circuit given in a string

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

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

这是一个例子:

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

一步一步:

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

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

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)

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

def resistance(array):
if isinstance(array, int):
    return array
else:
    if isinstance(array,list):
        temp = array
    else:
        temp = array.split(" ")
    i = 0
    while True:
        try:
            a = new_resistance(temp[i], temp[i+1], temp[i+2])
        except Exception as e:
            i += 1            
        if len(temp[i+3:]) == 0:
            return resistance(new_resistance(temp[i], temp[i+1], temp[i+2]))
        else:
            return resistance(temp[:i] + [new_resistance(temp[i], temp[i+1], temp[i+2])] + temp[i+3:])

该程序背后的想法是从列表的开头开始计算列表的前三个元素的电阻,然后将它们追加到新列表的开头(没有三个元素)和使用新列表再次调用该函数。这样做直到只剩下一个整数和 return 个整数。

感谢任何帮助。


更新:

问题的解决方法,使用堆栈和类似于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

您的程序,或者更具体地说,您的 parser, seems to be relying on the Reverse Polish Notation, which in turn is a small variant of the Normal Polish Notation。简而言之,RPN 是一种抽象表示,其中算术表达式 的运算符跟随 它们的操作数,这与 Normal Polish Notation 中的运算符 不同在 他们的操作数之前。基于这种表示的解析器可以很容易地通过使用堆栈来实现(通常不需要解释括号)。

如果您的任务是开发该解析器,您可能会从我上面链接的维基百科文章中获得一些输入。

问题是,一旦达到 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 并修改正则表达式以解析浮点数。

感谢第一个识别出 RPN 的@none。

我想起了过去的回忆。我在 1980 年代在 8 位计算机上玩 FORTH 语言。 好的,回到 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])
  1. 本着VPfB的精神进行串并联的任意组合(不仅成对)

     def calculateresistor(dataString):
     stack = []
     r = []
     cicuit=dataString
     for n in circuit.split():
         if n == 'S':
             stackSize=size(stack)
             if size(stack)>=2:
                 for k in range(0,size(stack)-1):
                     r.append(float(stack.pop()))
                     r.append(float(stack.pop()))
                     stack.append((r[-1]+r[-2]))
         elif n == 'P':
             stackSize=size(stack)
             if size(stack)>=2:
                 for k in range(0,size(stack)-1):
                     r.append(float(stack.pop()))
                     r.append(float(stack.pop()))
                     r.append(0.0 if (r[-1] == 0 or r[-2] == 0) else (1/(1/r[-1]+1/r[-2])))
                     stack.append(r[-1])
         else:
             stack.append(float(n))
     assert len(stack) == 1
     return(stack)