我需要编写一个程序,对句子中的一个字符进行线性搜索。除了print()
之外,我必须不使用任何内置函数。
程序应输出字符所在的索引。
如果字符不在句子中,则应输出-1作为索引。
我的代码输出如下:
Enter a sentence: Hello
Enter a character: e
The character is -1.
The character is 1 on the index.
即使它只应输出:
Enter a sentence: Hello
Enter a character: e
The character is 1 on the index.
以下是我的代码:
def linear_search(intList,target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
print("The character is", count, "on the index.")
found = True
break
if intList[count] != target:
print("The character is -1.")
count = count + 1
return count
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
while count < len(intList):
if intList[count] == target:
print("The character is", count, "on the index.")
found = True
break
else: count += 1
if not found:
print("The character is -1.")
return count
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
问题出在while循环中。
这些线是:
if intList[count] != target:
print("The character is -1.")
count = count + 1
这里,如果角色与目标不同,它将立即打印出“角色为-1”。但是,您希望在查看字符串中的每个元素之后执行此操作,而不是在它只是命中一个不相同的字符时。
你想要的是它最后打印,所以你的linear_search函数看起来应该更像这样:
def linear_search(intList,target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
print("The character is", count, "on the index.")
found = True
return count
count = count + 1
print("The character is -1")
return -1
在较少代码和没有内置函数的情况下执行此操作的另一种方法是使用for循环,如下所示:
def linear_search(intList, target):
for char in intList:
if char == target:
print("The character is", count, "on the index.")
return count
count += 1
print("The character is -1")
return -1