gpt4 book ai didi

python - 使用递归查找字符串中相邻的字符对

转载 作者:行者123 更新时间:2023-12-01 04:43:08 26 4
gpt4 key购买 nike

我必须编写一个程序,使用递归函数来计算字符串中重复字符对的数量,并且字符对不能重叠。

例如,我输入字符串“Hello, Sabeena”。我需要输出为“2”,一个用于一对 ls,一个用于一对 es。

我已经尝试过,但没有输出。

message = input("Enter a message:\n")
pairs = 0
k = 0

if len(message) == k:
return("Number of pairs:",pairs)
else:
if message[k] == message[k+1]:
pairs = pairs + 1
k = k+1
else:
k = k+1

理想情况下,程序应如下所示:

Enter a message:
Hello, Sabeena
Number of pairs: 2

有人可以建议我哪里出错了吗?

最佳答案

将递归代码放入函数中(直到它真正被视为递归),如果尚未达到基本情况,则返回对函数的递归调用 (k == len( message) - 1),每次增加k

def find_adjacent(message, pairs, k):
if k == len(message) - 1: #subtract one to avoid getting a string index out of range error
return("Number of pairs:", pairs)
else:
return find_adjacent(message, pairs+1 if message[k]==message[k+1] else pairs, k+1)


if __name__ == "__main__":
message = "message" # change to input("Enter a message:\n")
pairs = 0
k = 0
m, p = find_adjacent(message, pairs, k)
print m, p

以上打印

Number of pairs: 1

如果您喜欢它不那么紧凑并且更具可读性:

def find_adjacent(message, pairs, k):
if k == len(message)-1:
return("Number of pairs:", pairs)
elif message[k] == message[k+1]:
if k == 0:
return find_adjacent(message, pairs+1, k+1) # first letter of message, all good
elif message[k] != message[k-1]:
return find_adjacent(message, pairs+1, k+1) # not first letter, and this pair hasn't been counted before
else:
return find_adjacent(message, pairs, k+1) # this sequence has already been counted
else:
return find_adjacent(message, pairs, k+1)

关于python - 使用递归查找字符串中相邻的字符对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103153/

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