鱼C论坛

 找回密码
 立即注册
查看: 622|回复: 3

[已解决]29讲动手1和动手2 没有理解代码

[复制链接]
发表于 2025-3-8 16:23:49 | 显示全部楼层
本帖最后由 jackz007 于 2025-3-8 18:33 编辑

         使用 find() 的版本
  1. text  = input(" What text : ")
  2. words = input("What words : ")
  3. e = []
  4. for w in words . split(' ') :
  5.     k = text . find(w , 0)
  6.     while k != -1 :
  7.         e . append([k , k + len(w) - 1])
  8.         k = text . find(w , k + 1)
  9. if e:
  10.     e . sort()
  11.     print(e)
复制代码


        不使用 find() 的版本:
  1. text  = input(" What text : ")
  2. words = input("What words : ")
  3. e = []
  4. for w in words . split(' ') :
  5.     for k in range(len(text) - len(w) + 1) :
  6.         if text[k : k + len(w)] == w :
  7.             e . append([k , k + len(w) - 1])
  8. if e:
  9.     e . sort()
  10.     print(e)
复制代码


运行实况;
  1. D:\[00.Exercise]\[Python]>python x.py
  2. What text : I love FishC and FishC love me
  3. What words : FishC
  4. [[7, 11], [17, 21]]

  5. D:\[00.Exercise]\[Python]>python x.py
  6. What text : I love FishC and FishC love me
  7. What words : FishC love
  8. [[2, 5], [7, 11], [17, 21], [23, 26]]

  9. D:\[00.Exercise]\[Python]>python x.py
  10. What text : FCFCF
  11. What words : FCF FC
  12. [[0, 1], [0, 2], [2, 3], [2, 4]]

  13. D:\[00.Exercise]\[Python]>
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-10-6 03:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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