FAQ: Survey of Computer Science - The Tale of Kenny - Optimization


#1

This community-built FAQ covers the “Optimization” exercise from the lesson “Survey of Computer Science - The Tale of Kenny”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Code Foundations

FAQs on the exercise Optimization

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

Why is it that when i use the binary search that it returns the same entry multiple times before moving forward?

Here you can find a screenshot of it. Image


#3

It’s to do with the recursion as the list gets shortened.

If the middle value comes after the search term, the function recurses over the left half, else the right. Check again for relativity, recurse half again, and so on. We can see it only takes about half a dozen recursions.

Feed in a range of numbers to see a clearer picture…

binary_search(range(1000),679)
Checking the bookshelf and finding: 0
Checking the bookshelf and finding: 501
Checking the bookshelf and finding: 501
Checking the bookshelf and finding: 626
Checking the bookshelf and finding: 626
Checking the bookshelf and finding: 658
Checking the bookshelf and finding: 674
Checking the bookshelf and finding: 674
Checking the bookshelf and finding: 678

Found the book: 679

#4

May I suggest replacing the line
print("Checking the bookshelf and finding: {0}".format(lst[0]))
with
print("Checking the bookshelf and finding: {0}".format(lst[len(lst) // 2]))

That way the program displays the book in the middle of the selection, which seems more relevant to me than the book at the start of the selection.