更新
考虑到您在 cmets 中的规格,我想出了这个:
def counting(string1: str, string2: str) -> tuple[int, int]:
if not string1 and not string2:
return 0, 0
if not string1:
str1a = str1b = 0
elif string1[0] == "a":
str1a, str1b = 1, 0
else:
str1a, str1b = 0, 1
if not string2:
str2a = str2b = 0
elif string2[0] == "a":
str2a, str2b = 1, 0
else:
str2a, str2b = 0, 1
next_round = counting(string1[1:], string2[1:])
return next_round[0] + str1a + str2a, next_round[1] + str1b + str2b
print(counting("aabb", "bbba"))
>> (3, 5)
旧答案:
您的递归函数运行良好,但是使用递归来跟踪两个变量,每个变量有两个字母可能会变得非常困难。我建议您使用递归函数一次计算一个单词中一个字母的出现次数,然后将结果相加。
为了使其在未来更具可扩展性(更多/其他单词,更多/其他要计算的字母),您可以创建这样的函数:
# You only count the occurrence of one letter in one word.
def counting(string: str, letter: str) -> int:
if not string:
return 0
elif string[0] == letter:
return 1 + counting(string[1:], letter)
else:
return counting(string[1:], letter)
# here you add up the results
def get_all_occurrences(word_list: list[str], letter_list: list[str]) -> tuple[int]:
letters_profile = []
for letter in letter_list:
letter_occurrences = 0
for word in word_list:
letter_occurrences += counting(word, letter)
letters_profile.append(letter_occurrences)
return tuple(letters_profile)
words = ["aabb", "abbb"]
letters = ["a", "b"]
occurrences = get_all_occurrences(words, letters)
print(occurrences)