【问题标题】:Searching a list of integers搜索整数列表
【发布时间】:2017-02-21 06:16:05
【问题描述】:

我正在尝试创建一个代码,其中 Python 将生成 0 到 9 之间的五个随机数,然后将它们存储在一个列表中。我需要程序允许用户输入一个整数然后搜索列表。

def main():
    choice = displayMenu()
    while choice != '4':
        if choice == '1':
            createList()
        elif choice == '2':
            print(createList)
        elif choice == '3':
            searchList()
        choice = displayMenu()

    print("Thanks for playing!")


def displayMenu():
    myChoice = '0'
    while myChoice != '1' and myChoice != '2' \
                  and myChoice != '3' and myChoice != '4':
         print ("""Please choose
                        1. Create a new list of 5 integers
                        2. Display the list
                        3. Search the list
                        4. Quit
                        """)
         myChoice = input("Enter option-->")

         if myChoice != '1' and myChoice != '2' and \
            myChoice != '3' and myChoice != '4':
             print("Invalid option. Please select again.")

    return myChoice 

import random

def linearSearch(myList):
target = int(input("--->"))
for i in range(len(myList)):
    if myList[i] == target:
        return i
    return -1


#This is where I need it to ask the user to give five numbers 

def createList():
    newList = []
    while True:
        try:
            num = input("Give me five numbers: ")
            num = [int(num) for num in input().split(' ')]
            print(num)
            if any([num < 0 for num in a]):
                Exception

            print("Thank you")
            break
        except:
            print("Invalid. Try again...")

    for i in range(5):
        newList.append(random.randint(0,9))
    return newList


#This is where the user should be able to search the list

def searchList():
    target = int(input("--->"))
    result = linearSearch(myList,target)
    if result == -1:
        print("Not found...")
    else:
        print("Found at", result)

但是,一旦我让用户输入号码,它就不会搜索列表?

【问题讨论】:

  • 你使用什么版本的 Python? (input 在 2.6 和 3.3 中的工作方式不同)。
  • 我正在使用 python 3.6!
  • 你在哪里定义了线性搜索?
  • 抱歉,我意识到我忘记添加了,我编辑了它以显示。
  • “搜索”和“不会搜索”是什么意思?

标签: python list search integer


【解决方案1】:

createlist() 正在创建一个列表,但 searchList() 没有对它的引用。 您的 searchList() 没有接受任何参数,因此 linearSearch() 不知道要搜索哪个列表。

linearSearch(),可以用更好的方式定义:

def linearSearch(myList,target):
    for i,j in enumerate(myList):
        if target == j:
            return i
        else:
            return -1

【讨论】:

    【解决方案2】:

    您的代码存在一些问题

    1. 在 createList 函数中,您要求用户输入五个您没有在任何地方使用的数字。
    2. 在 main 函数中,您正在调用 createList(),但您没有将其存储在任何变量中。它应该是这样的:

      list=createList()

    3. 在选择=2的主函数中,您正在打印函数本身,而不是您应该执行以下操作:

      print(list)

    记得在 main 函数的开头声明 list。因为如果用户选择了选项 2 而没有选择 1 则会出现错误。

    1. 你应该在 searchList 函数中传递列表如下:

      def searchList(list): target = int(input("--->")) try: result=list.index(target) print("Found at", result) except: print("Not found")

    【讨论】:

    • 这非常有帮助!谢谢!
    【解决方案3】:

    首先,线性搜索没有在任何地方定义。假设您已经在某处定义了它,您必须将 myList 传递给 searchList 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2016-03-19
      • 1970-01-01
      • 2019-02-11
      • 2020-01-03
      相关资源
      最近更新 更多