12、编写一个递归函数来判断一个字符串是否为回文。编写一个主程序,从用户那里读取一个字符串,并使用你的递归函数来判断它是否为回文。然后程序应该向用户显示一条合适的消息。
以下是实现该功能的Python代码:
# @param s the string to check
# @return True if the string is a palindrome, False otherwise
def isPalindrome(s):
# Base case: The empty string is a palindrome. So is a string containing only 1 character.
if len(s) <= 1:
return True
# Recursive case: The string is a palindrome only if the first and last characters match, and
# the rest of the string is a palindrome
return s[0] == s[len(s) - 1] and isPalindrome(s[1 : len(s) - 1])
# Check whether or not a string entered by the user is a palindrome
def main():
# Read the string from the user
line = input("Enter a string: ")
# Check its status and display the result
if isPalindrome(line):
print("That was a palindrome!")
else:
print("That is not a palindrome.")
# Call the main function
main()
在上述代码中, isPalindrome 函数是一个递归函数,用于判断字符串是否为回文。如果字符串长度小于等于1,则直接返回 True ;否则,检查字符串的第一个和最后一个字符是否相等,并递归调用 isPalindrome 函数检查剩余的字符串。 main 函数负责从用户那里读取字符串,并调用 isPalindrome 函数进行判断,最后根据判断结果输出相应的消息。
13、编写一个递归函数来计算两个字符串之间的编辑距离。使用该递归函数编写一个程序,从用户那里读取两个字符串并显示它们之间的编辑距离。
以下是实现该功能的Python代码:
# 递归函数计算两个字符串之间的编辑距离
def editDistance(s1, s2):
# 如果第一个字符串为空,编辑距离为第二个字符串的长度
if len(s1) == 0:
return len(s2)
# 如果第二个字符串为空,编辑距离为第一个字符串的长度
if len(s2) == 0:
return len(s1)
# 如果两个字符串的最后一个字符相同
if s1[-1] == s2[-1]:
return editDistance(s1[:-1], s2[:-1])
else:
# 插入操作
insert = editDistance(s1, s2[:-1]) + 1
# 删除操作
delete = editDistance(s1[:-1], s2) + 1
# 替换操作
replace = editDistance(s1[:-1], s2[:-1]) + 1
# 返回三种操作中的最小值
return min(insert, delete, replace)
# 主函数,读取用户输入并计算编辑距离
def main():
# 从用户读取两个字符串
s1 = input('Enter a string: ')
s2 = input('Enter another string: ')
# 计算并显示编辑距离
print('The edit distance between %s and %s is %d.' % (s1, s2, editDistance(s1, s2)))
# 调用主函数
if __name__ == '__main__':
main()
代码解释:
-
editDistance函数 :
- 该函数使用递归的方式计算两个字符串之间的编辑距离。
- 基本情况:如果其中一个字符串为空,编辑距离就是另一个字符串的长度。
- 递归情况:如果两个字符串的最后一个字符相同,编辑距离等于去掉最后一个字符后的两个子字符串的编辑距离。如果最后一个字符不同,考虑三种操作(插入、删除

最低0.47元/天 解锁文章
1635

被折叠的 条评论
为什么被折叠?



