16.8 Exercises

From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period5 exercisesNot autograded

README.md

16.8 Exercises

Read first in the book: 16.5 Breaking Ties: Second Sorting, 16.6 When to use a Lambda Expression, 16.7 Glossary.

Exercise 1

You're going to write a function that takes a string as a parameter and returns a list of the five most frequent characters in the string. Eventually, you will be able to do this sort of problem without a lot of coaching. But we're going to step you through it as a series of exercises.

First, the function will count the frequencies of all the characters, as we've done before, using a dictionary and the accumulator pattern. Then, it will sort the (key, value) pairs. Finally, it will take a slice of the sorted list to get just the top five. That slice will be returned.

Step 1. Suppose you had this list, [8, 7, 6, 6, 4, 4, 3, 1, 0], already sorted, how would you make a list of just the best 5? (Hint: take a slice).

Open the 01 folder and edit main.py. This one is not graded, so check it yourself.

Exercise 2

Now suppose the list wasn't sorted yet. How would get those same five elements from this list?

Open the 02 folder and edit main.py. This one is not graded, so check it yourself.

Exercise 3

Now take a list L and make a dictionary of counts for how often these numbers appear in the list.

Open the 03 folder and edit main.py. This one is not graded, so check it yourself.

Exercise 4

Now sort the keys (numbers) based on their frequencies. Review Sorting a Dictionary if you're not sure how to do this. Keep just the top five keys.

Open the 04 folder and edit main.py. This one is not graded, so check it yourself.

Exercise 5

Finally, generalize what you've done. Write a function that takes a string instead of a list as a parameter and returns a list of the five most frequent characters in the string.

Open the 05 folder and edit main.py. This one is not graded, so check it yourself.

For teachers

16.8 Exercises

Students read Foundations of Python Programming's “Exercises” in CS Room and work through its 5 Python coding exercises.

  • Time: 1 class period

Reading first

Exercises

FolderGradingTests
01Not graded; students check it themselves0
02Not graded; students check it themselves0
03Not graded; students check it themselves0
04Not graded; students check it themselves0
05Not graded; students check it themselves0