Chapter 5 · Real programs

Practice: searching, sorting and testing

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 20 · Demo

Linear search looks at each item

By the end of this lesson you can search and sort by hand, and test with assert.

A linear search looks at each item in turn; return in the loop ends the function at once.

Run it. Each print shows a look. The search for 9 stops at the first 9; the one for 5 returns -1.

def find(xs, target):
    for i, x in enumerate(xs):
        print("look at", x)
        if x == target:
            return i
    return -1


nums = [7, 3, 9, 4, 9]
print(find(nums, 9))
print(find(nums, 5))
def find(names, name):
    """The index of the first item equal to name,
    capitals ignored; -1 when there is none."""
    for i, n in enumerate(names):
        if n == name:
            return i
    return -1


names = ["Ada", "Alan", "Grace", "Alan"]
print(find(names, "alan"))
print(find(names, "GRACE"))
print(find(names, "Linus"))
def find(xs, target):
    for i, x in enumerate(xs):
        if x == target:
            return i
    return -1


def test_find():
    assert find([7, 3, 9, 4, 9], 9) == 2
    assert find([7, 3, 9], 5) == -1
    assert find([], 1) == -1


test_find()
print("all tests passed")
def count_vowels(word):
    """How many of word's letters are vowels."""
    count = 0
    for ch in word:
        if ch in "aeiou":
            count += 1
        return count


def test_count_vowels():
    assert count_vowels("python") == 1
    assert count_vowels("banana") == 3
    assert count_vowels("Ada") == 2


test_count_vowels()
print("all tests passed")
def bsearch(xs, target):
    """The index of target in the sorted list xs,
    or -1 when it is not there."""
    return -1


def test_bsearch():
    nums = [3, 8, 12, 15, 23, 31, 40, 47]
    assert bsearch(nums, 23) == 4
    assert bsearch(nums, 3) == 0
    assert bsearch(nums, 47) == 7
    assert bsearch(nums, 20) == -1
    assert bsearch([], 5) == -1


test_bsearch()
print("all tests passed")
nums = [6, 4, 9, 2]
nums[0], nums[3] = nums[3], nums[0]
print(nums)
def selection_sort(xs):
    """Sort xs in place, smallest first."""
    pass


def test_sort():
    nums = [5, 3, 8, 1]
    selection_sort(nums)
    assert nums == [1, 3, 5, 8]
    words = ["pear", "fig", "apple"]
    selection_sort(words)
    assert words == ["apple", "fig", "pear"]


nums = [5, 3, 8, 1]
selection_sort(nums)
print(nums)
test_sort()
print("all tests passed")
from collections import Counter

nums = [5, 3, 8, 1]
print(sorted(nums))
print(nums)
nums.sort()
print(nums)
words = "the cat and the dog and the end".split()
print(Counter(words).most_common(2))
print(Counter("banana").most_common(1))
def is_palindrome(text):
    """True when text reads the same backwards,
    capitals and spaces ignored."""
    return text == text[::-1]


def test_palindrome():
    assert is_palindrome("level")
    assert is_palindrome("Never odd or even")
    assert not is_palindrome("python")


test_palindrome()
print("all tests passed")
def reverse_words(text):
    """The words of text in the opposite order."""
    return " ".join(text.split())


def test_reverse_words():
    assert reverse_words("one two three") == "three two one"
    assert reverse_words("hello") == "hello"


print(reverse_words("the cat sat"))
test_reverse_words()
print("all tests passed")
from collections import Counter

text = "peter piper picked a peck of peppers"
letters = Counter(text)
for letter, n in letters.most_common(3):
    print(letter, n)
def second_largest(xs):
    """The second largest item of xs (2 items or
    more), without sorting."""
    return xs[0]


def test_second_largest():
    assert second_largest([3, 9, 4, 7]) == 7
    assert second_largest([9, 3]) == 3
    assert second_largest([5, 5, 3]) == 5
    assert second_largest([1, 2, 3, 4]) == 3


print(second_largest([8, 2, 6]))
test_second_largest()
print("all tests passed")
def merge(a, b):
    """One sorted list of the items of the sorted
    lists a and b."""
    return a + b


def test_merge():
    assert merge([1, 4, 9], [2, 3]) == [1, 2, 3, 4, 9]
    assert merge([], [5]) == [5]
    assert merge([2, 2], [1, 2]) == [1, 2, 2, 2]


print(merge([1, 4, 9], [2, 3, 10, 12]))
test_merge()
print("all tests passed")
Terminal
Step 1 of 13Linear search

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)