简单的方程式反转
Simple equation reversal
我正在解决以下挑战,但自从过去 4 小时以来现在无法解决,我被卡住了:
Challenge :
> 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'
请您帮忙解决这个问题:
此致,
迪瓦卡
这里是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])
求解函数通过将部分(运算符 [“+”、“-”、“*”、“/”] 和操作数 [数字、变量等])分离到一个列表中来工作。
例如。 "a+b-c/d30" 变成 ["a", "+", "b", "-", "c", "/", "d" , " ”,“30”]。反转并加入列表以获得最终解决方案。
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])
这个有用,希望对你有帮助
我正在解决以下挑战,但自从过去 4 小时以来现在无法解决,我被卡住了:
Challenge :
> 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'
请您帮忙解决这个问题:
此致, 迪瓦卡
这里是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])
求解函数通过将部分(运算符 [“+”、“-”、“*”、“/”] 和操作数 [数字、变量等])分离到一个列表中来工作。 例如。 "a+b-c/d30" 变成 ["a", "+", "b", "-", "c", "/", "d" , " ”,“30”]。反转并加入列表以获得最终解决方案。
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])
这个有用,希望对你有帮助