鱼C论坛

 找回密码
 立即注册
查看: 2558|回复: 5

python第023,024讲课后题

[复制链接]
发表于 2016-11-29 16:01:29 | 显示全部楼层 |阅读模式
1鱼币
def is_palindrome(n, start, end):
        if start > end:
                return 1     
        else:
                return is_palindrome(n, start+1, end-1) if n[start] == n[end] else 0
        
string = input('请输入一串字符串:')
length = len(string)-1

if is_palindrome(string, 0, length):
        print('\"%s\"是回文字符串!' % string)
else:
        print('\"%s\"不是回文字符串!' % string)
这个代码有点看不懂,求大神逐步解答

最佳答案

查看完整内容

之前自己做的
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-29 16:01:30 | 显示全部楼层
  1. def is_palindrome(n, start, end):     #定义回文贴的方法,有三个入参(字符串的长度,字符串左边字符的索引,字符串右边字符的索引)                                                   
  2.         if start > end:               #如果字符左边字符索引>右边字符索引(说明一半的字符已经比较过了)
  3.                 return 1              #返回1
  4.         else:                         #如果左边索引值<右边索引值说明还没有对比完,如果第一个字符和最后一个字符相等则使用递归函数比较第二个字符和倒数第二个字符,否则返回0
  5.                 return is_palindrome(n, start+1, end-1) if n[start] == n[end] else 0
  6.         
  7. string = input('请输入一串字符串:')  #输入一个字符串
  8. length = len(string)-1                #确定字符串的长度(是为了确定end值)

  9. if is_palindrome(string, 0, length):  #如果返回的是1,说明是回文贴
  10.         print('"%s"是回文字符串!' % string)
  11. else:                                  #返回0说明不是回文贴
  12.         print('"%s"不是回文字符串!' % string)
复制代码


之前自己做的
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-11-30 07:49:23 | 显示全部楼层

return is_palindrome(n, start+1, end-1) if n[start] == n[end] else 0
这个if else还可以写在同一行?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-11-30 09:33:33 | 显示全部楼层

\"%s\" 中的\和"是干嘛用的
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-30 09:48:48 | 显示全部楼层
cuizihan2359 发表于 2016-11-30 09:33
\"%s\" 中的\和"是干嘛用的

\表示是转义,是转义后面的“”的
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-11-30 10:16:56 | 显示全部楼层
小茗同学 发表于 2016-11-30 09:48
\表示是转义,是转义后面的“”的

谢了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-24 05:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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