【问题标题】:Linear search code that has to output all numbers in the sentence必须输出句子中所有数字的线性搜索代码
【发布时间】: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


【解决方案1】:

它只打印第一个字符,因为您跳出了 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

【讨论】:

  • 这给出了一个无限循环
  • 计数应始终递增
【解决方案2】:

这是一个使用元组的解决方案:

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 语句,您的原始代码失败。但是,即使您删除了中断,您也会得到一个无限循环,因为如果找到字符,您永远不会增加计数器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 2022-01-15
    • 2012-08-02
    • 1970-01-01
    • 2016-05-06
    • 2018-12-09
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多