Merge pull request #411 from veronicaguo/update-snippets

Update `count_by`, `chunk_into_n` and `initial`
This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-25 12:38:38 +02:00
committed by GitHub
3 changed files with 12 additions and 9 deletions

View File

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

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

View File

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