简体   繁体   中英

TypeError: binarySearch() got an unexpected keyword argument 'key'

Code

a = int(input("What number do you want to search for in the list? "))

def bubbleSort(alist):                                         
    for passnum in range(len(alist)-1,0,-1):                                   
        for i in range(passnum):                                   
            if alist[i]>alist[i+1]:                                            
                temp = alist[i]                                                         
                alist[i] = alist[i+1]                                          
                alist[i+1] = temp                                                

def binarySearch(alist, item):
    first = 0
    last = len(alist)-1
    found = False

    while first<=last and not found:
        midpoint = (first + last)//2                                           
        if alist[midpoint] == item:                                              
            found = True                                                           
        else:                                 
            if item < alist[midpoint]:
                last = midpoint-1
            else:
                first = midpoint+1

    return found                

def getkey(item):                                                 
    return item[0]                                               
alist = [(75, "Jack"), (23, "Mark"), (31, "Dave"), (93, "Michael"), (52, "Clare"), (67, "Connie"), (37, "Bob"), (87, "Gary"), (59, "Billy"), (69,"Simon")]                             
bubbleSort(alist)                                  

print(binarySearch(alist, a, key=getkey))

This is the error I'm getting:

Traceback (most recent call last):
File "C:/Python34/Lib/idlelib/Binary Search.py", line 35, in
print(binarySearch(alist, a, key=getkey))
TypeError: binarySearch() got an unexpected keyword argument 'key'

Any idea why?

You pass to binarySearch() three argument, but this function accept only two, so the argument 'key' is not recognized.

Call the function in this way:

print(binarySearch(alist, a))

Because you defined the function has two parameters and you pass three parameter to the function, so the error occur. You can define your function like

`def binarySearch(alist, item, key=getkey):
    #your code

then you can pass three or two parameters to the functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM