A brief note on Searching, Sorting and Recursion: linear and binary search, sorted() and sort() with a key function, counting the work, and recursion with a base case and the call stack. With a worked example, practice, a program and questions to check yourself.
A brief note on Searching, Sorting and Recursion. Read it before a test. Try each question at the end before you open its answer.
-1 when the target is not there. Positions start at 0.n items, linear search needs up to n checks.target in items answers True or False. items.index(target) gives the first position, but stops with an error when the target is missing.(low + high) // 2. The loop runs while low <= high, and moves to middle + 1 or middle - 1.sorted(x) gives a new sorted list and leaves x as it was. x.sort() sorts x itself and gives back None.reverse=True puts the biggest first. key=len sorts by length, and key=str.lower ignores capital letters.(-mark, name) puts the biggest mark first, and equal marks in name order.sorted is faster than both.| Method | Checks for n items | When n doubles |
|---|---|---|
| Linear search | up to n | twice the work |
| Binary search | about the number of halvings | one more check |
| Bubble sort | about | four times the work |
RecursionError.isinstance(item, dict) tells a folder from a file.How many times can 40 be halved with // 2 before it reaches 1? This function answers by recursion.
halvings(40) waits for halvings(20). That one waits for halvings(10), then come halvings(5), halvings(2) and halvings(1).halvings(1) gives back 0 without another call.| Call | Gives back |
|---|---|
halvings(1) | 0 |
halvings(2) | 1 |
halvings(5) | 2 |
halvings(10) | 3 |
halvings(20) | 4 |
halvings(40) | 5 |
The program shows 5. This count is why binary search is fast: a sorted list of 40 items needs at most halvings(40) + 1, that is 6 checks, and not 40.
A sports teacher ranks the long jump results, longest first. Then a binary search finds a length in the sorted list, and counts its checks.
marks = marks.sort(). sort() gives back None, so the list is lost. Write marks.sort() on its own, or marks = sorted(marks).(low + high) / 2 for the middle. A decimal number cannot be a position: TypeError: list indices must be integers or slices, not float. Use //.index() for a missing item. [3, 8].index(5) stops with ValueError: list.index(x): x not in list. Ask with in first.sorted([5, "apple"]) stops with TypeError: '<' not supported between instances of 'str' and 'int'.n == 0, and ends in RecursionError: maximum recursion depth exceeded.return in the recursive case. The answer is lost, and the caller gets None.climb(3) show?scores = [("Neel", 64), ("Ojas", 81), ("Pia", 64)]. Write a key function that sorts by score, highest first, with equal scores in name order. In what order do the names come?product(items), which multiplies the first item by product(items[1:]). What should the base case give back for an empty list, and why not 0?Log in to join the discussion.
Loading…