Sum of numeric values and +/- signs as string algorithm

huangapple go评论52阅读模式
英文:

Sum of numeric values and +/- signs as string algorithm

问题

这是我有的字符串:

s = 'one+one-two-one+two'

我需要计算这个字符串的总和。

这是我尝试过的方法:

s = 'one+one-two-one+two'
d = {'one': 1, 'two': 2}
add = s.split('+')
result = 0
for i in range(len(add)):
    val = d.get(add[i], None)
    if val:
        result += val
    else:
        sub = add[i].split('-')
        for j in range(len(sub)):
            if j > 0:
                result -= d[sub[j]]
            else:
                result += d[sub[j]]
print(result)

在这种情况下,从 'one+one-two-one+two' 到 'one+-one-two-one+two',我的方法不起作用。

有什么建议吗?

英文:

So I have this string:

s = 'one+one-two-one+two'

And I need to calculate the sum of this.

Tis is what I have try:

s = 'one+one-two-one+two'
d = {'one': 1, 'two': 2}
add = s.split('+')
result = 0
for i in range(len(add)):
    val = d.get(add[i], None)
    if val:
        result += val
    else:
        sub = add[i].split('-')
        for j in range(len(sub)):
            if j > 0:
                result -= d[sub[j]]
            else:
                result += d[sub[j]]
print(result)

In case 'one+one-two-one+two' to 'one+-one-two-one+two' my way not works well.

Any suggestions ?

答案1

得分: 1

你可以使用 re.split() 来使用 +- 进行分割。然后在循环中,根据每个数字之前的分隔符来进行加法或减法操作。

import re

s = 'one+one-two-one+two'
d = {'one': 1, 'two': 2}

parsed = re.split(r'([-+])', s)
total = d.get(parsed[0])

for i in range(1, len(parsed), 2):
    op = parsed[i]
    num = d.get(parsed[i+1])
    if op == '+':
        total += num
    else:
        total -= num

print(total)

将正则表达式放在捕获组中会使 re.split() 包括分隔符在结果列表中。

英文:

You can use re.split() to split it using both + and -. Then in the loop you can add or subtract depending on which delimiter is before each number.

import re

s = 'one+one-two-one+two'
d = {'one': 1, 'two': 2}

parsed = re.split(r'([-+])', s)
total = d.get(parsed[0])
    
for i in range(1, len(parsed), 2):
    op = parsed[i]
    num = d.get(parsed[i+1])
    if op == '+':
        total += num
    else:
        total -= num

print(total)

Putting the regexp in a capture group makes re.split() include the delimters in the list of results.

答案2

得分: 1

你可以使用递归方法:

def calc(s, sign=1):
    if s.startswith('+'): return calc(s[1:], sign)
    if s.startswith('-'): return calc(s[1:], -sign)
    if s.startswith('one'): return sign * 1 + calc(s[3:])
    if s.startswith('two'): return sign * 2 + calc(s[3:])
    return 0

输出:

print(calc('one+one-two-one+two')) # 1

print(calc('one+-one-two-one+two')) # -1
英文:

You could use a recursive approach:

def calc(s,sign=1):
    if s.startswith('+'):   return calc(s[1:], sign)
    if s.startswith('-'):   return calc(s[1:],-sign)
    if s.startswith('one'): return sign * 1 + calc(s[3:])
    if s.startswith('two'): return sign * 2 + calc(s[3:])
    return 0

output:

print(calc('one+one-two-one+two')) # 1

print(calc('one+-one-two-one+two')) # -1

huangapple
  • 本文由 发表于 2023年6月1日 00:36:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定