鱼C论坛

 找回密码
 立即注册
查看: 1363|回复: 1

[已解决]回文字符串递归解法表达式怎么理解?

[复制链接]
发表于 2020-6-26 12:50:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. def is_palindrome(n,start,end):
  2.     if start > end:
  3.         return 1
  4.     else:
  5.         return is_palindrome(n,start+1,end-1) if n[start] == n[end] else 0

  6. string = input("请输入一串字符串:")
  7. length = len(string)-1

  8. if is_palindrome(string,0,length): #这里面的实参是什么意思?跟形参start end之间是什么关系?
  9.     print('"%s"是回文字符串!' % string)
  10. else:
  11.     print('"%s"不是回文字符串!' % string)
复制代码




#return里面有if else 而且没有缩进跟冒号,这样也可以吗?if的条件 n[start] n[end]是什么意思?
最佳答案
2020-6-26 12:57:41
  1. def is_palindrome(n,start,end):
  2.     if start > end:
  3.         return 1
  4.     else:
  5.         return is_palindrome(n,start+1,end-1) if n[start] == n[end] else 0
  6.     """ 1, is_palindrome(n,start+1,end-1)就是把字符串的开头向前移动一位,
  7.     末尾向后移动一位,缩小范围,然后依次比较这俩玩意。
  8.     2, if n[start] == n[end] else 0 三元表达式,你应该学过吧。
  9.     3,if n[start] == n[end]就是比较start位置的字符是否和end位置的字符相等,不相等就return 0."""

  10. string = input("请输入一串字符串:")
  11. length = len(string)-1

  12. if is_palindrome(string,0,length): # string是目标字符串,0是字符串开头,length是字符串的结尾
  13.     print('"%s"是回文字符串!' % string)
  14. else:
  15.     print('"%s"不是回文字符串!' % string)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-26 12:57:41 | 显示全部楼层    本楼为最佳答案   
  1. def is_palindrome(n,start,end):
  2.     if start > end:
  3.         return 1
  4.     else:
  5.         return is_palindrome(n,start+1,end-1) if n[start] == n[end] else 0
  6.     """ 1, is_palindrome(n,start+1,end-1)就是把字符串的开头向前移动一位,
  7.     末尾向后移动一位,缩小范围,然后依次比较这俩玩意。
  8.     2, if n[start] == n[end] else 0 三元表达式,你应该学过吧。
  9.     3,if n[start] == n[end]就是比较start位置的字符是否和end位置的字符相等,不相等就return 0."""

  10. string = input("请输入一串字符串:")
  11. length = len(string)-1

  12. if is_palindrome(string,0,length): # string是目标字符串,0是字符串开头,length是字符串的结尾
  13.     print('"%s"是回文字符串!' % string)
  14. else:
  15.     print('"%s"不是回文字符串!' % string)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 15:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表