python中的线性搜索代码不起作用并输出错误的文本

时间:2019-03-23 04:28:45

标签: python linear

我需要编写一个对句子中的字符进行线性搜索的程序。除了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)

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

问题出在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

答案 1 :(得分:1)

您的问题是您在检查整个字符串之前输出了不想要的结果。您只需检查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)