【问题标题】:Simple equation reversal简单的方程反转
【发布时间】:2020-09-06 04:50:14
【问题描述】:

我正在解决以下挑战,但自过去 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'

请您帮忙解决这个问题:

最好的问候, 迪瓦卡

【问题讨论】:

  • * 上拆分a 并反转结果。
  • Codewars 上的相关kata

标签: python python-3.6


【解决方案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+b-c/d30" 变成 ["a", "+", "b", "-", "c", "/", "d" , "", "30 "]。反向加入列表,得到最终解。

【讨论】:

  • 请补充说明。
【解决方案2】:
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])

这个可以,希望对你有帮助

【讨论】:

  • 请补充说明。
  • 这个问题最难的部分在于数字的处理。比如300直接倒序输出,就会变成003,这是错误的。
  • 使用拆分方法后,如果有连续的数字,则属于同一个号码。这是算法的核心
  • 希望对您有所帮助~
猜你喜欢
  • 2012-06-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
相关资源
最近更新 更多