Suggests using builtin functions for median, sample, shuffle, split_lines and zip

This commit is contained in:
Pablo Baeyens
2020-01-04 14:00:20 +01:00
parent 2ba974cd2d
commit ed8394afc8
5 changed files with 10 additions and 0 deletions

View File

@ -7,6 +7,8 @@ Finds the median of a list of numbers.
Sort the numbers of the list using `list.sort()` and find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even.
[`median`](https://docs.python.org/3/library/statistics.html#statistics.median) provides similar functionality to this snippet.
```py
def median(list):
list.sort()

View File

@ -7,6 +7,8 @@ Returns a random element from a list.
Use `random.randint()` to generate a random number that corresponds to an index in the list, return the element at that index.
[`random.sample`](https://docs.python.org/3/library/random.html#random.sample) provides similar functionality to this snippet.
```py
from random import randint

View File

@ -7,6 +7,8 @@ Randomizes the order of the values of an list, returning a new list.
Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.
[`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle) provides similar functionality to this snippet.
```py
from copy import deepcopy
from random import randint

View File

@ -7,6 +7,8 @@ Splits a multiline string into a list of lines.
Use `s.split()` and `'\n'` to match line breaks and create a list.
[`str.splitlines`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) provides similar functionality to this snippet.
```py
def split_lines(s):
return s.split('\n')

View File

@ -9,6 +9,8 @@ Use `max` combined with `list comprehension` to get the length of the longest li
Loop for `max_length` times grouping elements.
If lengths of `lists` vary, use `fill_value` (defaults to `None`).
[`zip`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) provide similar functionality to this snippet.
```py
def zip(*args, fill_value=None):
max_length = max([len(lst) for lst in args])