Browser lab18 min+60 XP

Counting things

Count words, votes and letters. A classic data science move.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

counts[x] = counts.get(x, 0) + 1 counts anything.

votes = ["pizza", "tacos", "pizza", "sushi", "pizza", "tacos"]3"pizza"2"tacos"1"sushi"Winner: pizza
The votes counted into a dictionary, shown as bars.

Counting how often each thing appears is called a frequency count, and dictionaries are perfect for it. Each key is the thing, each value is its count.

The pattern: start with an empty dictionary, loop through the items, and for each one do counts[item] = counts.get(item, 0) + 1.

To split a sentence into words use sentence.split(). To find the most common item, use max(counts, key=counts.get).

Real life linkVote counting, "most played song" charts and trending hashtags all come from counting how often each thing appears.
Example code
votes = ["pizza", "tacos", "pizza", "sushi", "pizza", "tacos"]
counts = {}
for v in votes:
    counts[v] = counts.get(v, 0) + 1
print(counts)
print("Winner:", max(counts, key=counts.get))
TASK 2

Try it yourself

+10 XP

Count how many times each letter appears in the word "banana" and print the dictionary: {'b': 1, 'a': 3, 'n': 2}.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What does "I like code".split() return?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Word frequency

+20 XP

Count the words in the text (make it all lowercase first). Print each word with its count in alphabetical order, like the: 3, then print Most common: the.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.