Lecture 12 Finger Exercise
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Question 1.
Implement a function For example: When When next_char_frequencies() that satisfies the following docstring.def next_char_frequencies(phrases, target_char):
"""
Find which characters follow a given character and how often.
Parameters:
phrases (list): A collection of strs containing only lower-case
characters, no spaces.
target_char (str): A single lower-case character.
Return a dict that maps lower-case characters (str) to ints. The
values are the total number of times each character immediately
follows target_char across all strings in phrases. If a character
never follows target_char, it does not appear as a key.
"""
words = ["an", "ana", "banana"]
next_char_frequencies(words, "a") should evaluate to {"n": 4}.titles = ["greeneggsandham", "catinthehat", "hortonhearsawho"]
next_char_frequencies(titles, "e") should evaluate to {"a": 1, "e": 1, "g": 1, "h": 1, "n": 1}.
Given a starting location For example, if the input grid is the following and the start location is Hint 1:
If you run BFS to completion from a start node, it will visit all the nodes that are reachable from the start.
Thus, to identify all the locations of an island, is there a certain collection in our BFS implementation whose size would be relevant? Hint 2:
In class, we used explicit dictionaries to represent graphs.
Here, the edge relationships are implicitly a cell's neighboring Hint 3:
This is not strictly necessary, but note that because we are not returning a path, we may not have to store paths in our BFS frontiers.
Instead, maybe just storing the newly discovered nodes would be sufficient.m x n grid representing a geographic map, a cell value of 1 represents land, and a cell value of 0 represents water.
An island is a group of contiguous 1s that are connected horizontally, vertically, or diagonally.
(i, j) in the grid, implement the following function to compute the area of the island containing the location, which is the number of contiguous 1s connected to (i, j).def island_area(grid, start):
"""
Determine the area of an island that contains a given location.
Parameters:
grid (list): A list of lists of ints. The ints are either 1
(representing land) or 0 (representing water).
start (tuple): The (row, col) indices of a start location within
the grid.
Return the number of cells in grid for the island that the start
location is on. If the start location is in water, return 0.
"""
grid = [
[0, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 1],
]
(0, 1), then the island its on has size 5.1s in the supplied grid.
We suggest making a helper function to compute this.