Sorting, Deduplication, Two Pointers

Pattern 7, Sorting. You will almost always use the built-in sort. But understanding one simple sort explains why the built-in matters.

Selection sort in plain English: find the smallest remaining item, move it to the front, repeat. It is easy to understand and slow on large data, which is exactly the point Module 23 will make.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Change it to sort from largest to smallest, by finding the biggest remaining number each time.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Pattern 8, Deduplication. Remove repeats. A set does it instantly, or you can build a new list and check membership as you go.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Remove the duplicates from a list of cities of your own, keeping the order they first appeared in.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Pattern 9, Two pointers. Work from both ends toward the middle. Perfect for reversing, or for checking whether something reads the same forwards and backwards.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Test it on your own name and on "noon". Then make it ignore capital letters, so "Racecar" counts as a palindrome too.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Pattern 10, Binary search. On a sorted list, check the middle. If the target is smaller, throw away the whole upper half. Repeat. Halving the search space every step is astonishingly fast: a million items takes about twenty checks.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Search a list of 100000 numbers and print how many steps it takes.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

◈ Graded Challenge

Write a function that takes a list of member records (each with a name and hours) and returns the number of members with more than 50 hours. Combine the filtering and counting patterns.

Name it exactly: def count_dedicated(members):

3 visible + 3 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back