|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问题:给定一个字符串 text 和字符串列表 words,返回 words 中每个单词在 text 中的位置(要求最终的位置从小到大进行排序)。
举例:
text:"I love FishC and FishC love me"
words:"FishC"
输出:[[7, 11], [17, 21]]
text:"I love FishC and FishC love me"
words:"FishC love"
输出:[[2, 5], [7, 11], [17, 21], [23, 26]]
text:"FCFCF"
words:"FCF FC"
输出:[[0, 1], [0, 2], [2, 3], [2, 4]]
答:
text = input("请输入text的内容:")
words = input("请输入words的内容:")
i = j = 0
list = []
while i <= len(words):
if words[i] ==' 'or i == len(words): #这行会报错 IndexError: string index out of range
b = text.find(words[j:i])
list.append([b,b+len(words[j:i])-1])
j = i + 1
i = i + 1
else:
i = i + 1
print(list)
本帖最后由 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 , c + len(word) - 1])
- c += len(word)
- e = sorted(d)
- print(e)
复制代码
运行实况:
- D:\[00.Exerciese.2022]\Python>python x.py
- text : I love FishC and FishC love me
- word : FishC
- [[7, 11], [17, 21]]
- D:\[00.Exerciese.2022]\Python>python x.py
- text : I love FishC and FishC love me
- word : FishC love
- [[2, 5], [7, 11], [17, 21], [23, 26]]
- D:\[00.Exerciese.2022]\Python>python x.py
- text : FCFCF
- word : FCF FC
- [[0, 1], [0, 2], [2, 3]]
- D:\[00.Exerciese.2022]\Python>
复制代码
【另】:FCF 的那个样例显然是错误的,FCF 只有 1 个,FC 有 2 个,总共应该找到 3 个而不是 4 个。
|
|