【问题标题】:Recursively find number of lowercase letters in a string递归查找字符串中小写字母的数量
【发布时间】:2021-12-10 12:58:29
【问题描述】:

我正在尝试递归查找字符串中小写字母的数量,该字符串具有确定需要考虑字符串的哪一部分的低和高索引:def count_lowercase(s, low, high)。由于if s[count] == s[count].lower() and s[count] != ' ',一旦遇到大写字母或空格,我的代码就会停止遍历字符串,但我无法弄清楚如何让它继续。非常感谢任何帮助!

我的代码

def count_lowercase(s, low, high):
    def countfunc(s2=s[low: high+1], count=0):
        if count > high:
            return count
        else:
            if s[count] == s[count].lower() and s[count] != ' ':
                return countfunc(s2, count+1)
        return count
    return countfunc()

【问题讨论】:

  • 需要递归吗?

标签: python string recursion


【解决方案1】:

如果您想在字符串的一部分中查找小写字母,为什么不采用这种方法:

import re

def count_lowercase(s, low, high):
    return len(re.findall("[a-z]", s[max(0,low):min(high, len(s))]))

跟进:如果您无法使用任何模块:

def count_lowercase(s, low, high):
    s = s[max(0,low):min(high, len(s))].strip(" ")
    return sum([x==x.lower() for x in s])

【讨论】:

  • 感谢您的回复!不幸的是,我不能将导入用于分配,但知道这是一个可能的解决方案绝对有帮助
  • @xander 如果在字符串的一部分中找到所有小写字符,你想要什么,对吗?
  • 是的!并且外部函数中的参数需要保持不变
  • @xander 如果只有外部函数的参数需要保持不变,我的answer 应该可以工作
【解决方案2】:

如果有大写或空格不处理,如果不是小写且不是空格,则立即返回计数。

不要将计数用作索引,而是将其分开。

def count_lowercase(s, low, high):
    def countfunc(s2=s[low: high+1], count=0, index=0):
        if index > high:
            return count
        else:
            if s[index] == s[index].lower() and s[index] != ' ':
                return countfunc(s2, count+1, index+1)
            else:
                return countfunc(s2, count, index+1)
        return count
    return countfunc()

想想如果代码到达一个空格或大写字母,你的 if 语句是假的并且没有被处理,直接转到return count。如果您输入 else 来处理大写/空格并仍然使用 count 作为索引,即使到达大写字母或空格,它也会增加以转到下一个索引。

将它们分开并添加其他!

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 2021-02-22
    • 2022-06-12
    • 1970-01-01
    • 2020-07-04
    • 2016-10-02
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多