Final challenge: tables and groups
After this: Predict, complete and fix programs that reach into tables and dictionaries of lists.
This challenge has four steps, and each step is scored on its own. You will predict a column total, complete the line that reads one cell of each row, count the values across a dictionary of lists after two changes, and fix a table whose rows are one list. 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 4Predict it
Predict it
A grid has three rows of two. What does this print?
grid = [[2, 4], [6, 8], [1, 1]]total = 0for row in grid: total = total + row[1]print(total)int[][] grid = {{2, 4}, {6, 8}, {1, 1}};int total = 0;for (int[] row : grid) { total = total + row[1];}System.out.println(total);Complete the line
Complete the missing line so that the program adds the last value of each row to total and prints 9. Each row has three values.
grid = [[1, 2, 3], [4, 5, 6]]total = 0for row in grid: ____________________ # ← add the last value of this row to totalprint(total)int[][] grid = {{1, 2, 3}, {4, 5, 6}};int total = 0;for (int[] row : grid) { ____________________ // ← add the last value of this row to total}System.out.println(total);Count the groups
A dictionary of lists is changed twice before the count. What does this print?
groups = {"a": [1, 2], "b": [3]}groups["b"].append(4)groups["c"] = [5]count = 0for values in groups.values(): count = count + len(values)print(count)HashMap<String, ArrayList<Integer>> groups = new HashMap<>();groups.put("a", new ArrayList<>(List.of(1, 2)));groups.put("b", new ArrayList<>(List.of(3)));groups.get("b").add(4);groups.put("c", new ArrayList<>(List.of(5)));int count = 0;for (ArrayList<Integer> values : groups.values()) { count = count + values.size();}System.out.println(count);Fix it
This program is meant to make a table of two separate rows and put 5 in one cell of the first row. It prints the 5 twice. Which one change makes it right?
row = [0, 0, 0]table = [row, row]table[0][1] = 5print(table)Output
[[0, 5, 0], [0, 5, 0]]
int[] row = {0, 0, 0};int[][] table = {row, row};table[0][1] = 5;System.out.println(Arrays.deepToString(table));Output
[[0, 5, 0], [0, 5, 0]]
- Predict a column total and a count across a dictionary of lists, complete a line that reads one cell of each row, and fix a table whose rows share one list.