Final challenge: count it and look it up
After this: Predict, complete, fix and choose, with dictionaries and sets.
This challenge has five steps, and each step is scored on its own. You will predict what a dictionary holds after two changes, complete a counting loop, fix one that reads a count before it exists, choose the right shape for a job, and predict a set after repeated adds. Every step shows the code in Python and in Java; the answers are the same in both. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 5Predict it
Predict it
A dictionary is built up in two steps. What does this print?
marks = {"Ana": 72}marks["Ben"] = 85marks["Ana"] = 90print(marks["Ana"])print(len(marks))HashMap<String, Integer> marks = new HashMap<>(Map.of("Ana", 72));marks.put("Ben", 85);marks.put("Ana", 90);System.out.println(marks.get("Ana"));System.out.println(marks.size());Complete the count
The counting line is missing. Complete it so that the program counts each fruit and prints 2 for apple. Use the fallback form, so that a new fruit starts at 1.
fruits = ["apple", "pear", "apple"]counts = {}for fruit in fruits: ____________________ # ← add one to this fruit's countprint(counts["apple"])ArrayList<String> fruits = new ArrayList<>(List.of("apple", "pear", "apple"));HashMap<String, Integer> counts = new HashMap<>();for (String fruit : fruits) { ____________________ // ← add one to this fruit's count}System.out.println(counts.get("apple"));Fix it
This program is meant to count the words and print 2. It fails on the first pass of the loop. Which one change makes it right?
words = ["to", "be", "to"]counts = {}for word in words: counts[word] = counts[word] + 1print(counts["to"])Output
KeyError: 'to'
ArrayList<String> words = new ArrayList<>(List.of("to", "be", "to"));HashMap<String, Integer> counts = new HashMap<>();for (String word : words) { counts.put(word, counts.get(word) + 1);}System.out.println(counts.get("to"));Output
NullPointerException
Which shape
Tickets are scanned at a door. For each ticket number the program must say whether that number has been scanned before. Which shape fits best?
Set it
Five values go into a set. What does this print?
seen = set()for n in [3, 1, 3, 3, 2]: seen.add(n)print(len(seen))print(3 in seen)HashSet<Integer> seen = new HashSet<>();for (int n : List.of(3, 1, 3, 3, 2)) { seen.add(n);}System.out.println(seen.size());System.out.println(seen.contains(3));- Predict what a built-up dictionary holds, complete a counting loop, fix one that reads a key before it exists, choose the right shape for a job, and predict a set after repeats.