Update count_by, chunk_into_n and initial

This commit is contained in:
Veronica Guo
2020-10-22 22:35:06 -04:00
parent c05e62d821
commit 9cd13f560e
3 changed files with 12 additions and 9 deletions

View File

@ -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