【问题标题】:Python algorithm-Bubble Sort, Linear and Binary SearchPython算法-冒泡排序、线性和二分搜索
【发布时间】:2018-07-09 21:09:20
【问题描述】:

这个问题基本上是让我写一个二维数组来存储乐队名称和他们的销售额。 然后它要求我编写一个程序,根据销售数量使用冒泡排序对列表进行排序。 前两个部分相当简单并且工作正常。但是,它后来要求我允许它让用户输入乐队的名称并使用线性搜索获得他们的图表位置。这是我正在努力解决的部分。

myList = [[53,"band1"],[26,"band2"],[923,"band3"],[31,"band4"],[44,"band5"],
[55,"band6"],[231,"band7"]]
def bubbleSort(myList):
    for passnum in range(len(myList)-1,0,-1):
        for i in range(passnum):
            if myList [i]>myList[i+1]:
                top7 = myList[i]
                myList[i] = myList[i+1]
                myList[i+1] = top7

x = int(input("Enter a band name: "))

found = False

for i in range(len(myList)):
 if(myList[i] == x):
  found = True
  print("%d found at %dth position"%(x,i))
  break

if(found == False):
 print("%d is not in list"%x)


bubbleSort(myList)
print(myList)

这是输出: 输入乐队名称:band4 回溯(最近一次通话最后): 文件“python”,第 10 行,在 ValueError: int() 以 10 为底的无效文字:'band4'

【问题讨论】:

  • 您的代码有:x = int(input("Enter a band name: "))。当您尝试将字符串转换为 int 时,这是预期的行为。
  • 如何解决?
  • 不要将其转换为 int。只需对字符串进行搜索即可。

标签: python


【解决方案1】:

当您需要一个字符串作为乐队名称时,为什么要使用 int(input())?

x=input("Enter band name") 

应该有效

【讨论】:

  • 感谢您的建议。但是现在我收到此错误 Traceback (最近一次调用最后一次): File "python", line 21, in TypeError: %d format: a number is required, not str
  • 将第一个 %d 替换为 %s,因为 x 是字符串而不是整数。
  • 这似乎已经修复了语法错误,但是代码表明乐队实际上不在列表中。 “输入乐队名称 band2 band2 不在列表中”但是 band2 在列表中
  • 是的,我已经尝试了所有组合,但仍然说乐队不在列表中
猜你喜欢
  • 2018-02-08
  • 2014-11-05
  • 2016-03-19
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 2013-09-04
  • 2013-11-02
相关资源
最近更新 更多