[英]using recursion to get sub strings in python
how can I use recursion to find the amount of 'a' that is in a string: 如何使用递归查找字符串中的“ a”数量:
example: get_a('halloa') -> 2 例如:get_a('halloa')-> 2
here is what I have: 这是我所拥有的:
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:])
the problem in your code is that you stop the recursion when you find the first a
. 代码中的问题是,找到第
a
时,您将停止递归。 You'll want to call get_a
and collect the a
s you've already found: 你会想打电话
get_a
和收集a
你已经找到S:
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:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.