如何在python中使用递归将分配给字符串中字母/数字的值相加?

如何在python中使用递归将分配给字符串中字母/数字的值相加?,python,Python,我是python新手,仍然不完全了解递归是如何工作的。我正在编写一个程序,它遍历一个字符串并将分配给它的值相加 一封信得1分 一个数字就是这个数字实际包含的点数 一个空间就是零点 e、 g print(count_函数(“Cows 16”)的数量为11 我该怎么做呢 def str_score (s): if ((s[len(s) - 1].isalpha())): return 1 if ((s[len(s) - 1].isdigit())): return int(s

我是python新手,仍然不完全了解递归是如何工作的。我正在编写一个程序,它遍历一个字符串并将分配给它的值相加

  • 一封信得1分
  • 一个数字就是这个数字实际包含的点数
  • 一个空间就是零点
e、 g print(count_函数(“Cows 16”)的数量为11

我该怎么做呢

def str_score (s): 
if ((s[len(s) - 1].isalpha())): 
    return 1
if ((s[len(s) - 1].isdigit())):
    return int(s[len(s) - 1])
if (' ' in s):
    return 0    

这就是我要做的,但不知道如何做递归部分。我喜欢像电影《盗梦空间》那样形象化递归。我们可以从一个方法内部调用该方法。从一个梦中我们可以进入另一个梦。在每个梦中我们可以做操作,当我们完成后,我们可以醒来并向上级提供结果层。因此,首先我们需要确定当我们开始解开我们的梦想时,我们的最终情况是什么。在这种情况下,是当我们到达字符串中的最后一个字符时。如果我们不在那里,那么我们将更深入地做一个梦

def calc_score(n):
    # Calculate the score for the first element in the string
    score = 0
    if n[0] == ' ': score = 0
    elif not n[0].isdigit(): score = 1
    else: score = int(n[0])

    # If the current dream only has a single element
    # return the score
    if len(n) == 1: return score

    # If there are more than one element in the
    # string still, then go into another dream layer
    # with the string without the first character.
    else:
        score += calc_score(n[1::])
        return score

n = "Cows 16"
calc_score(n)
十一,


我们可以看到,这不是一个理想的情况,我们希望使用递归。我们不需要不断地进入梦境层,因为我们知道我们将应用算法的顺序,因此for循环将是最佳的

def calc_score(n):
    score = 0
    for i in n:
        if i == ' ': continue
        elif not i.isdigit(): score += 1
        else: score += int(i)
    return score

n = "Cows 16"
calc_score(n)
十一,


除了空格外,还可以传递其他非字母数字值,因此我们应该只检查数字或字母,因为这些是唯一可以接收值的项,因此忽略字符串中传递的任何其他内容

下面代码中的函数将检查任意长度字符串中的每个值,并根据您规定的规则返回相关金额

def str_score(s):

    count = 0 

    for letter in s:
        if unicode(letter, "utf-8").isalpha():
            count += 1
        if unicode(letter, "utf-8").isnumeric():
            count += int(letter)

    return count

s = raw_input("Enter string: ")

count = str_score(s)

print count

注:这也将处理len(s)的情况==0

这是一个单行程序,它将通过使用iterable理解来完成您所描述的内容,假设特殊字符的分数为0,类似于空白。此函数将创建一个数组,其中包含字符串中每个字符的分数,然后计算并返回这些分数的总和

def str_score(s):
    return sum([int(x) if x.isdigit() else 1 if x.isalpha() else 0 for x in s])

print(str_score('Cows 16'))
>>> 11
如果希望特殊字符的值为1,例如字母,则以下函数将实现此功能

def str_score(s):
    return sum([int(x) if x.isdigit() else 1 for x in s.replace(' ', '')])

在第二个函数中,我删除了字符串中的所有空格,因为它们没有值。

对于涉及序列的问题,递归没有任何意义。我能用一个更合适的例子给出解释递归的答案吗?是的,那太好了!但如果你能帮我解决这个问题,我也希望能够解决,谢谢estion明确要求递归解决方案