我正在解决挑战,但是自从过去4个小时以来,现在无法解决问题,我被困住了:
挑战:
> Given a mathematical equation that has *,+,-,/, reverse it as follows:
>
> solve("100*b/y") = "y/b*100"
> solve("a+b-c/d*30") = "30*d/c-b+a"
我为解决挑战而编写的代码
def solve(s):
a,b = s.split('/')
return (b+"/"+a)
预期输出: 'y / b * 100'
观察到的输出: 'y / 100 * b'
在解决此问题时,请您的帮助:
最好的问候, 迪瓦卡(Diwakar)
答案 0 :(得分:1)
这里是solve
函数的实现,可以逆转方程式。
def solve(equation):
parts = []
operand = ""
for ch in equation:
if ch in ["+", "-", "*", "/"]:
parts.append(operand)
parts.append(ch)
operand = ""
else:
operand += ch
if operand:
parts.append(operand)
return "".join(parts[::-1])
solve函数通过将部分(运算符[“ +”,“-”,“ *”,“ /”]和操作数[数字,变量等])分隔成一个列表来工作。 例如。 “ a + bc / d 30”变为[“ a”,“ +”,“ b”,“-”,“ c”,“ /”,“ d”,“ ”,“ 30 “]。反向并加入列表以获取最终解决方案。
答案 1 :(得分:1)
def solve(s): #Hardest part of this problem is to handle NUMBERS.
li = [s[0]] # the first element of s,such as "1"
for i in range(1,len(s)): # begin to handle the rest of s
if li[-1].isdigit() and s[i].isdigit(): # if the last element of li is digit and the current element of s is also digit,then they belong to a same NUMBER.
li[-1] = li[-1] + s[i]
else:
li.append(s[i])
return "".join(li[::-1])
这将奏效,希望对您有帮助