G-Bule 发表于 2022-10-7 11:52:31

请问为什么会报错?

问题:给定一个字符串 text 和字符串列表 words,返回 words 中每个单词在 text 中的位置(要求最终的位置从小到大进行排序)。
举例:
text:"I love FishC and FishC love me"
words:"FishC"
输出:[, ]

text:"I love FishC and FishC love me"
words:"FishC love"
输出:[, , , ]

text:"FCFCF"
words:"FCF FC"
输出:[, , , ]

答:
text = input("请输入text的内容:")
words = input("请输入words的内容:")
i = j = 0
list = []
while i <= len(words):
    if words ==' 'or i == len(words):          #这行会报错 IndexError: string index out of range
      b = text.find(words)
      list.append()-1])
      j = i + 1
      i = i + 1
      
    else:
      i = i + 1
print(list)

jackz007 发表于 2022-10-7 12:25:19

本帖最后由 jackz007 于 2022-10-7 12:50 编辑

while i <= len(words):# <= 得改成 < 否则,word[ i ] 会越界

s = input("text : ") . strip()
w = input("word : ") . strip() . split()
d = []
for word in w:
    c = 0
    while c >= 0:
      c = s . find(word , c)
      if c >= 0:
            d . append()
            c += len(word)
e = sorted(d)
print(e)
      运行实况:
D:\\Python>python x.py
text : I love FishC and FishC love me
word :FishC
[, ]

D:\\Python>python x.py
text : I love FishC and FishC love me
word : FishC love
[, , , ]

D:\\Python>python x.py
text : FCFCF
word : FCF FC
[, , ]

D:\\Python>
      【另】:FCF 的那个样例显然是错误的,FCF 只有 1 个,FC 有 2 个,总共应该找到 3 个而不是 4 个。

G-Bule 发表于 2022-10-7 13:22:11

jackz007 发表于 2022-10-7 12:25
while i

感谢您的提醒, 我对代码做了修改,已经可以实现题目要求了。
text = input("请输入text的内容:")
words = input("请输入words的内容:")
i = j = 0
b = -1
list = []
while i < len(words):
    if words ==' ':
      b = text.find(words)
      while b != -1:
            list.append()-1])
      
            b = text.find(words,b + 1)
      j = i + 1
      i = i + 1
      
    else:
      i = i + 1

b = text.find(words)
while b != -1:
    list.append()-1])
      
    b = text.find(words,b + 1)

print(sorted(list))

运行实况:
======================= RESTART: E:/我python/练习代码/78986.py ======================
请输入text的内容:I love FishC and FishC love me
请输入words的内容:FishC
[, ]
>>>
======================= RESTART: E:/我python/练习代码/78986.py ======================
请输入text的内容:I love FishC and FishC love me
请输入words的内容:FishC love
[, , , ]
>>>
======================= RESTART: E:/我python/练习代码/78986.py ======================
请输入text的内容:FCFCF
请输入words的内容:FCF FC
[, , , ]

关于FCF那个样例看个人理解:有人觉得只有(FCF)CF这一个,有人觉得有(FCF)CF和FC(FCF)两个。
页: [1]
查看完整版本: 请问为什么会报错?