gpt4 book ai didi

python - 使用递归在python中获取子字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:06 26 4
gpt4 key购买 nike

我如何使用递归来查找字符串中“a”的数量:

例子:get_a('你好') -> 2

这是我的:

    def get_a(string):
'''
return how many times a exist in the string using recursion
'''
if string == '':
return 0
if string[0] == 'a':
return 1
return get_a(string[1:])

最佳答案

您的代码中的问题是当您找到第一个a 时就停止了递归。您需要调用 get_a 并收集您已经找到的 a:

def get_a(string):
'''
return how many times a exist in the string using recursion
'''
if string == '':
return 0
if string[0] == 'a':
return 1 + get_a(string[1:])
return get_a(string[1:])

关于python - 使用递归在python中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48688763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com