我的线性搜索必须输出所有一个字符的索引。因此,如果句子是Hello,那么它将打印L在索引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)
它只打印第一个字符,因为你突破了while循环。相反,试试这个:
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
else:
count += 1
if not found:
print("The character is -1.")
return count
这是一个使用元组的解决方案:
def linear_search(intList,target):
found = False
count = 0
for i , char in enumerate(sentence):
if char == target:
found = True
print(i , char)
if not found:
return -1
return count
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
输出:
Enter a sentence: i have a a time
Enter a character: a
3 a
7 a
9 a
11 a
由于while循环中的break
语句,原始代码失败。但是,即使你删除了中断,你也会得到一个无限循环,因为如果找到该字符,你永远不会增加计数器。