【问题标题】:Binary search coming to error in tkinter gui python 2.7tkinter gui python 2.7中的二进制搜索出错
【发布时间】:2016-05-08 05:50:28
【问题描述】:

这段代码似乎给我的论点一个错误,我不知道我在这段代码中做错了什么。当尝试使用 python 2.7 在 tkinter 中运行二进制搜索时,如果我不使用 gui 只是行代码,程序可以正常工作。这是我的程序基于的代码

http://www.pythonschool.net/data-structures-algorithms/binary-search/

错误是:Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):文件“C:\Python27\lib\lib-tk\Tkinter.py”,第 1536 行,调用返回 self.func(*args) TypeError: binarySearch() 只需要 2 个参数(给定 0)

from Tkinter import *
import csv

with open('scoresRecord.csv', 'rb') as f: 

reader = csv.reader(f) 
your_list = list(reader)

root = Tk()
root.resizable(0,0)
root.title("Score Board")


def binarySearch(myitem,myList):
found = False
bottom = 0
top = len(myList)-1
while bottom<=top and not found:
middle = (bottom+top)//2
if myList[middle]== myitem:
    found = True
elif myList[middle] < myitem:
    bottom = middle + 1
else:
    top = middle-1

return found




if __name__=="__main__":
    Scorelist = [row[0] for row in your_list]  
    Dismissallist =[row[1] for row in your_list] # create a list of only the          dismissal
    Venuelist =[row[2] for row in your_list] # create a list of only the venue
    item = int(input(entScore.get()))

    Scorelist = map(int, Scorelist)
    rowPos = Scorelist.index(item)
    isitFound = binarySearch(item,Scorelist)


if isitFound:
    Score= Scorelist[rowPos]
    Dismissal= Dismissallist[rowPos]
    Venue= Venuelist[rowPos]
else:
    Score= ("Not Found")
    Dismissal= ("Not Found")
    Venue= ("Not Found")



numScoreLbl.configure(text=Score)
numDismissal.configure(text=Dismissal)
outVenue.configure(text=Venue)


#==========GUI Section==================#

【问题讨论】:

  • 一个好的开始是修复你的缩进,使它真正匹配你正在运行的代码。缩进在 Python 中至关重要,您发布的内容根本不会运行。

标签: python python-2.7 tkinter binary-search


【解决方案1】:

首先,确保你的列表是有序的,否则结果可能是错误的。

其次,这样做

Scorelist = list(map(int, Scorelist))#convert to list
isitFound = binarySearch(item,Scorelist)

虽然,如果你使用 .index 方法,那么你可以这样做以获得更好的性能:

try:
    index = Scorelist.index(item)
    isitFound = True
except ValueError:
    isitFound = False

它去掉了二分搜索部分,但无论如何你都在使用 .index。所以这个比较好。希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2022-06-19
    相关资源
    最近更新 更多