![# Task: write a function that takes a list of strings # and outputs a dictionary that maps letters to a list of words # starting with this letter. from collections import defaultdict def worse(words: list[str]) -> dict[str, list[str]]: result = {} for word in words: if word[0] not in result: # We can get rid of result[word[0]] = [] # these two lines! result[word[0]].append(word) return result def better(words: list[str]) -> dict[str, list[str]]: result = defaultdict(list) # Each new key will be an empty list! for word in words: result[word[0]].append(word) return result words = ["alice", "anne", "bob", "barbara"] expected = {"a": ["alice", "anne"], "b": ["bob", "barbara"]} assert worse(words) == expected assert better(words) == expected](https://pbs.twimg.com/media/FdRb_qzXEAYc3fR.jpg?name=small&format=webp)
ALT # Task: write a function that takes a list of strings # and outputs a dictionary that maps letters to a list of words # starting with this letter. from collections import defaultdict def worse(words: list[str]) -> dict[str, list[str]]: result = {} for word in words: if word[0] not in result: # We can get rid of result[word[0]] = [] # these two lines! result[word[0]].append(word) return result def better(words: list[str]) -> dict[str, list[str]]: result = defaultdict(list) # Each new key will be an empty list! for word in words: result[word[0]].append(word) return result words = ["alice", "anne", "bob", "barbara"] expected = {"a": ["alice", "anne"], "b": ["bob", "barbara"]} assert worse(words) == expected assert better(words) == expected
![""" #CodeReviewChallenge task 4 What is wrong with this code? """ from itertools import cycle def split_into_bins(values: list, n_bins=3) -> list[list]: """Split the list of values into n_bins smaller lists. Examples -------- >>> split_into_bins([1,2,3,4,5,6,7,8]) [[1, 4, 7], [2, 5, 8], [3, 6]] """ bins = [[]] * n_bins indices = cycle(range(n_bins)) for value in values: bins[next(indices)].append(value) return bins](https://pbs.twimg.com/media/FbB5STuXwAA9vEt.jpg?name=small&format=webp)
ALT """ #CodeReviewChallenge task 4 What is wrong with this code? """ from itertools import cycle def split_into_bins(values: list, n_bins=3) -> list[list]: """Split the list of values into n_bins smaller lists. Examples -------- >>> split_into_bins([1,2,3,4,5,6,7,8]) [[1, 4, 7], [2, 5, 8], [3, 6]] """ bins = [[]] * n_bins indices = cycle(range(n_bins)) for value in values: bins[next(indices)].append(value) return bins










