From 9cd13f560ee9de1474733bc6846f4b3bab4b8ba8 Mon Sep 17 00:00:00 2001 From: Veronica Guo Date: Thu, 22 Oct 2020 22:35:06 -0400 Subject: [PATCH] Update `count_by`, `chunk_into_n` and `initial` --- snippets/chunk_into_n.md | 4 ++-- snippets/count_by.md | 13 ++++++++----- snippets/initial.md | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/snippets/chunk_into_n.md b/snippets/chunk_into_n.md index e4a0b790a..1fe4df135 100644 --- a/snippets/chunk_into_n.md +++ b/snippets/chunk_into_n.md @@ -17,10 +17,10 @@ def chunk_into_n(lst, n): size = ceil(len(lst) / n) return list( map(lambda x: lst[x * size:x * size + size], - list(range(0, n))) + list(range(n))) ) ``` ```py -chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4)) # [[1, 2], [3, 4], [5, 6], [7]] +chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4) # [[1, 2], [3, 4], [5, 6], [7]] ``` diff --git a/snippets/count_by.md b/snippets/count_by.md index 4fa78534c..41024cbea 100644 --- a/snippets/count_by.md +++ b/snippets/count_by.md @@ -5,15 +5,18 @@ tags: list,intermediate Groups the elements of a list based on the given function and returns the count of elements in each group. +- Use `defaultdict()` to initialize a dictionary. - Use `map()` to map the values of the given list using the given function. - Iterate over the map and increase the element count each time it occurs. ```py -def count_by(arr, fn=lambda x: x): - key = {} - for el in map(fn, arr): - key[el] = 1 if el not in key else key[el] + 1 - return key +from collections import defaultdict + +def count_by(lst, fn=lambda x: x): + count = defaultdict(int) + for val in map(fn, lst): + count[val] += 1 + return dict(count) ``` ```py diff --git a/snippets/initial.md b/snippets/initial.md index cb53c5df8..41c3cc373 100644 --- a/snippets/initial.md +++ b/snippets/initial.md @@ -5,11 +5,11 @@ tags: list,beginner Returns all the elements of a list except the last one. -- Use `lst[0:-1]` to return all but the last element of the list. +- Use `lst[:-1]` to return all but the last element of the list. ```py def initial(lst): - return lst[0:-1] + return lst[:-1] ``` ```py