AttributeError: 'datetime.date' object has no attribute 'sort'

Viewed 42

In this problem, we want to implement a new version of binary_search, called binary_search_year. binary_search_year will take in two parameters: a list of instances of Date, and a year as an integer. It will return True if any date in the list occurred within that year, False if not.

You should not assume that the list is pre-sorted, but you should know that the sort() method works on lists of dates.


    from datetime import date


    def binary_search_year(searchList, Year):
    
        searchList.sort()
        currentMiddle = len(searchList) // 2

        if searchList[currentMiddle].year == Year:
            return True

        elif Year < searchList[currentMiddle].year:
            binary_search_year(searchList[:currentMiddle], Year) 
            
        else:
            binary_search_year(searchList[currentMiddle+1], Year)

        return False

1 Answers

In your elif branch, you correctly pass a slice of the searchList :

            binary_search_year(searchList[:currentMiddle], Year) 
#                                         ^

But in the else branch you did not :

            binary_search_year(searchList[currentMiddle+1 ], Year)
#                                                        ^

Add the missing : and it shoudl work fine. Although the remark from @luthervespers about re-sorting the array in the recusive subcalls still stand.

Related