【发布时间】:2019-03-26 02:06:16
【问题描述】:
我的线性搜索必须输出所有存在的一个字符的索引。所以如果句子是 Hello,它会打印 L is in index 2 和 3。
我不知道该怎么做。
def linear_search(intList,target):
found = False
count = 0
#starting while loop
while count < len(intList):
if intList[count] == target:
print("The character is", count, "on the index.")
found = True
#break while loop
break
else:
count += 1
if not found:
print("The character is -1.")
return count
#inputting sentence and character
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
【问题讨论】:
-
它只打印第一个,因为你一找到第一个就跳出循环。
-
只是为了澄清我只需要找到字符是否在句子中不止一次,我不必打印出所有字符。因此,如果句子是 Hello,它将打印 L is in index 2 和 3。
标签: python linear-search