必要时在字符串中插入乘法运算符

2024-09-29 01:28:31 发布

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

作为我正在进行的项目的一部分,我想重写字符串,以便:

  1. 当数字和字母不存在时,乘法应该放在它们之间。

  2. 这个方程式应该等于零。

如果,输入:2x+5ydh=4,然后输出:2*x+5*ydh-4

如果,输入:x*3df + d5jk = -12,然后输出:x*3*df + d*5*jk +12

我正在考虑分别搜索数字和字母的位置,然后在确定乘法之前看到它们彼此跟随,但这就足够了吗?你知道吗


Tags: 项目字符串df字母数字乘法jk方程式
2条回答

为什么不做下面的代码片段?不用遍历和搜索每个数字或字母的位置,只需在一个循环中执行所有操作,这样效率更高。基本上,我们一个字符一个字符地遍历字符串。如果一个数字跟在一个字母后面,反之亦然,那么我们就加上一个“*”。否则,继续搜索。你知道吗

然后,要做“=”部分,只需将右手边的否定赋值给左手边。这部分是一个临时的(简单的)修复,但是如果您想要一个更简单的修复,您必须对右侧进行一些合法的解析和计算来否定它。你知道吗

def convert(inp: str):
    # Edge case check
    if len(inp) == 0: return inp

    # Go through the string looking for where to place '*'s
    # Add the first character
    tmp = [inp[0]]
    for i in range(1, len(inp)):
        # If letter followed by digit or the reverse, then add a '*'
        if (inp[i].isalpha() and inp[i - 1].isdigit()) or (inp[i].isdigit() and inp[i - 1].isalpha()):
            tmp.append('*')
        # Now add the current character
        tmp.append(inp[i])
    # Convert the resulting list back to a string
    ans = ''.join(tmp)

    # Now if the equal sign is present, split the result 
    # and negate the right hand side
    if '=' in ans:
        left, right = ans.split('=', 1)
        ans = '{}-({})'.format(left, right)

    # Return the answer
    return ans

print(convert('2x+5ydh=4'))
print(convert('x*3df + d5jk = -12'))

试试这个:

a = "2x+5ydh=4"
b = "x*3df + d5jk = -12"
def format_equation(inp_str):
    lst = str("".join([c + "*" if (c.isnumeric() and d.isalpha()) else (c+"*" if (c.isalpha() and d.isnumeric()) else c) for c,d in zip(inp_str,inp_str[1:])]) + inp_str[-1]).split("=")
    lhs = lst[0]
    rhs = "+" + str(abs(int(lst[1]))) if int(lst[1]) <0 else "-" + str(lst[1])
    return lhs + rhs
format_equation(a)    # 2*x+5*ydh-4
format_equation(b)    # x*3*df + d*5*jk +12

相关问题 更多 >