【问题标题】:Recursively return if the number of lowercase letters in a string is even如果字符串中小写字母的个数为偶数则递归返回
【发布时间】:2020-07-04 09:58:55
【问题描述】:

我正在尝试编写一个递归函数,如果字符串中小写字母的数量是偶数,则返回 true。这是我到目前为止所拥有的:

def is_number_of_lowercase_even(s,low,high):
if (low==high):
    return False
if low<high:
    left = s[low].islower()       
    return left and not is_number_of_lowercase_even(s,low+1,high)

我必须坚持上面的函数定义。不知道我做错了什么。

【问题讨论】:

    标签: string recursion


    【解决方案1】:

    这样的?将范围分成两半。如果两半都是偶数或两半都是奇数,则总数为偶数。

    def f(s, low, high):
      if low == high:
        return not s[low].islower()
    
      mid = low + (high - low) // 2
      left = f(s, low, mid)
      right = f(s, mid + 1, high)
    
      return (left and right) or (not left and not right)
    
    strs = [
      "Abc",
      "ABc",
      "asdf",
      "aSdF",
      "ASdf",
      "AsDF"
    ]
    
    for s in strs:
      print(s, f(s, 0, len(s) - 1))
    
    """
    ('Abc', True)
    ('ABc', False)
    ('asdf', True)
    ('aSdF', True)
    ('ASdf', True)
    ('AsDF', False)
    """
    

    【讨论】:

      猜你喜欢
      • 2013-12-11
      • 2021-12-10
      • 2018-12-29
      • 2023-03-07
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多