Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-11-02 19:28:35 +02:00
parent 98b5f67412
commit bff03eb7f4
23 changed files with 72 additions and 51 deletions

View File

@ -1,6 +1,6 @@
--- ---
title: shuffle title: shuffle
tags: list,random,intermediate tags: list,random,advanced
--- ---
Randomizes the order of the values of an list, returning a new list. Randomizes the order of the values of an list, returning a new list.
@ -23,6 +23,6 @@ def shuffle(lst):
``` ```
```py ```py
foo = [1,2,3] foo = [1, 2, 3]
shuffle(foo) # [2,3,1], foo = [1,2,3] shuffle(foo) # [2, 3, 1], foo = [1, 2, 3]
``` ```

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns a list of elements that exist in both lists. Returns a list of elements that exist in both lists.
- Use list comprehension on `a` to only keep values contained in both lists. - Use a list comprehension on `a` to only keep values contained in both lists.
```py ```py
def similarity(a, b): def similarity(a, b):

View File

@ -5,7 +5,9 @@ tags: string,regexp,intermediate
Converts a string to snake case. Converts a string to snake case.
- Break the string into words and combine them adding `_` as a separator, using a regexp. - Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them.
- Use `re.sub()` to replace any `-` characters with spaces.
- Finally, use `str.join()` to combine all words using `-` as the separator.
```py ```py
from re import sub from re import sub
@ -20,6 +22,7 @@ def snake(s):
```py ```py
snake('camelCase') # 'camel_case' snake('camelCase') # 'camel_case'
snake('some text') # 'some_text' snake('some text') # 'some_text'
snake('some-mixed_string With spaces_underscores-and-hyphens') # 'some_mixed_string_with_spaces_underscores_and_hyphens' snake('some-mixed_string With spaces_underscores-and-hyphens')
snake('AllThe-small Things') # "all_the_small_things" # 'some_mixed_string_with_spaces_underscores_and_hyphens'
snake('AllThe-small Things') # 'all_the_small_things'
``` ```

View File

@ -1,14 +1,14 @@
--- ---
title: some title: some
tags: list,function,intermediate tags: list,intermediate
--- ---
Returns `True` if the provided function returns `True` for at least one element in the list, `False` otherwise. Checks if the provided function returns `True` for at least one element in the list.
- Use `any()` in combination with `map()` and `fn` to check if `fn` returns `True` for any element in the list. - Use `any()` in combination with `map()` to check if `fn` returns `True` for any element in the list.
```py ```py
def some(lst, fn=lambda x: x): def some(lst, fn = lambda x: x):
return any(map(fn, lst)) return any(map(fn, lst))
``` ```

View File

@ -10,13 +10,15 @@ Sorts one list based on another list containing the desired indexes.
- Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the third argument. - Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the third argument.
```py ```py
def sort_by_indexes(lst, indexes, reverse = False): def sort_by_indexes(lst, indexes, reverse=False):
return [val for _, val in sorted(zip(indexes, lst), key = lambda x: x[0], reverse = reverse)] return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \
x[0], reverse=reverse)]
``` ```
```py ```py
a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk'] a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk']
b = [3, 2, 6, 4, 1, 5] b = [3, 2, 6, 4, 1, 5]
sort_by_indexes(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges'] sort_by_indexes(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges']
sort_by_indexes(a, b, True) # ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples'] sort_by_indexes(a, b, True)
# ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples']
``` ```

View File

@ -17,5 +17,6 @@ def sort_dict_by_key(d, reverse = False):
```py ```py
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
sort_dict_by_key(d) # {'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2} sort_dict_by_key(d) # {'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2}
sort_dict_by_key(d, True) # {'two': 2, 'three': 3, 'one': 1, 'four': 4, 'five': 5} sort_dict_by_key(d, True)
# {'two': 2, 'three': 3, 'one': 1, 'four': 4, 'five': 5}
``` ```

View File

@ -18,5 +18,6 @@ def sort_dict_by_value(d, reverse = False):
```py ```py
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
sort_dict_by_value(d) # {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} sort_dict_by_value(d) # {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
sort_dict_by_value(d, True) # {'five': 5, 'four': 4, 'three': 3, 'two': 2, 'one': 1} sort_dict_by_value(d, True)
# {'five': 5, 'four': 4, 'three': 3, 'two': 2, 'one': 1}
``` ```

View File

@ -5,7 +5,7 @@ tags: string,beginner
Splits a multiline string into a list of lines. Splits a multiline string into a list of lines.
- Use `s.split()` and `'\n'` to match line breaks and create a list. - Use `str.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. - [`str.splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) provides similar functionality to this snippet.
```py ```py
@ -14,5 +14,6 @@ def split_lines(s):
``` ```
```py ```py
split_lines('This\nis a\nmultiline\nstring.\n') # ['This', 'is a', 'multiline', 'string.' , ''] split_lines('This\nis a\nmultiline\nstring.\n')
# ['This', 'is a', 'multiline', 'string.' , '']
``` ```

View File

@ -1,11 +1,12 @@
--- ---
title: sum_by title: sum_by
tags: math,list,function,beginner tags: math,list,beginner
--- ---
Returns the sum of a list, after mapping each element to a value using the provided function. Calculates the sum of a list, after mapping each element to a value using the provided function.
- Use `map()` with `fn` to map each element to a value using the provided function, use `sum()` to return the sum of the values. - Use `map()` with `fn` to map each element to a value using the provided function.
- Use `sum()` to return the sum of the values.
```py ```py
def sum_by(lst, fn): def sum_by(lst, fn):

View File

@ -5,7 +5,8 @@ tags: math,intermediate
Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive). Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive).
- Use `range()` in combination with a list comprehension to create a list of elements in the desired range raised to the given `power`, `sum()` to add the values together. - Use `range()` in combination with a list comprehension to create a list of elements in the desired range raised to the given `power`.
- Use `sum()` to add the values together.
- Omit the second argument, `power`, to use a default power of `2`. - Omit the second argument, `power`, to use a default power of `2`.
- Omit the third argument, `start`, to use a default starting value of `1`. - Omit the third argument, `start`, to use a default starting value of `1`.

View File

@ -1,16 +1,18 @@
--- ---
title: symmetric_difference title: symmetric_difference
tags: list,beginner tags: list,intermediate
--- ---
Returns the symmetric difference between two iterables, without filtering out duplicate values. Returns the symmetric difference between two iterables, without filtering out duplicate values.
- Create a `set` from each list, then use list comprehension on each one to only keep values not contained in the previously created set of the other. - Create a `set` from each list.
- Use a list comprehension on each of them to only keep values not contained in the previously created set of the other.
```py ```py
def symmetric_difference(a, b): def symmetric_difference(a, b):
_a, _b = set(a), set(b) (_a, _b) = (set(a), set(b))
return [item for item in a if item not in _b] + [item for item in b if item not in _a] return [item for item in a if item not in _b] + [item for item in b
if item not in _a]
``` ```
```py ```py

View File

@ -1,19 +1,22 @@
--- ---
title: symmetric_difference_by title: symmetric_difference_by
tags: list,function,intermediate tags: list,intermediate
--- ---
Returns the symmetric difference between two lists, after applying the provided function to each list element of both. Returns the symmetric difference between two lists, after applying the provided function to each list element of both.
- Create a `set` by applying `fn` to each element in every list, then use list comprehension in combination with `fn` on each one to only keep values not contained in the previously created set of the other. - Create a `set` by applying `fn` to each element in every list.
- Use a list comprehension in combination with `fn` on each of them to only keep values not contained in the previously created set of the other.
```py ```py
def symmetric_difference_by(a, b, fn): def symmetric_difference_by(a, b, fn):
_a, _b = set(map(fn, a)), set(map(fn, b)) (_a, _b) = (set(map(fn, a)), set(map(fn, b)))
return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a] return [item for item in a if fn(item) not in _b] + [item
for item in b if fn(item) not in _a]
``` ```
```py ```py
from math import floor from math import floor
symmetric_difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2, 3.4]
symmetric_difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2, 3.4]
``` ```

View File

@ -5,7 +5,8 @@ tags: list,beginner
Returns all elements in a list except for the first one. Returns all elements in a list except for the first one.
- Return `lst[1:]` if the list's length is more than `1`, otherwise, return the whole list. - Use slice notation to return the last element if the list's length is more than `1`.
- Otherwise, return the whole list.
```py ```py
def tail(lst): def tail(lst):
@ -13,6 +14,6 @@ def tail(lst):
``` ```
```py ```py
tail([1, 2, 3]) # [2,3] tail([1, 2, 3]) # [2, 3]
tail([1]) # [1] tail([1]) # [1]
``` ```

View File

@ -6,7 +6,7 @@ tags: list,dictionary,intermediate
Combines two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values. Combines two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values.
The values of the first list need to be unique and hashable. The values of the first list need to be unique and hashable.
- Use `zip()` in combination with the `dict()` constructor to combine the values of the two lists into a dictionary. - Use `zip()` in combination with `dict()` to combine the values of the two lists into a dictionary.
```py ```py
def to_dictionary(keys, values): def to_dictionary(keys, values):

View File

@ -5,7 +5,7 @@ tags: date,intermediate
Converts a date to its ISO-8601 represenation. Converts a date to its ISO-8601 represenation.
- Use `datetime.datetime.isoformat()` to convert the given `datetime` object to an ISO-8601 date. - Use `datetime.datetime.isoformat()` to convert the given `datetime.datetime` object to an ISO-8601 date.
```py ```py
from datetime import datetime from datetime import datetime
@ -17,5 +17,5 @@ def to_iso_date(d):
```py ```py
from datetime import datetime from datetime import datetime
to_iso_date(datetime(2020,10,25)) # 2020-10-25T00:00:00 to_iso_date(datetime(2020, 10, 25)) # 2020-10-25T00:00:00
``` ```

View File

@ -7,7 +7,8 @@ Converts an integer to its roman numeral representation.
Accepts value between `1` and `3999` (both inclusive). Accepts value between `1` and `3999` (both inclusive).
- Create a lookup list containing tuples in the form of (roman value, integer). - Create a lookup list containing tuples in the form of (roman value, integer).
- Use a `for` loop to iterate over the values in `lookup`, `divmod()` to update `num` with the remainder, adding the roman numeral representation to the result. - Use a `for` loop to iterate over the values in `lookup`.
- Use `divmod()` to update `num` with the remainder, adding the roman numeral representation to the result.
```py ```py
def to_roman_numeral(num): def to_roman_numeral(num):

View File

@ -3,9 +3,9 @@ title: transpose
tags: list,intermediate tags: list,intermediate
--- ---
Returns the transpose of a two-dimensional list. Transposes a two-dimensional list.
- Use `*lst` to get the passed list as tuples. - Use `*lst` to get the provided list as tuples.
- Use `zip()` in combination with `list()` to create the transpose of the given two-dimensional list. - Use `zip()` in combination with `list()` to create the transpose of the given two-dimensional list.
```py ```py
@ -14,5 +14,6 @@ def transpose(lst):
``` ```
```py ```py
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) # [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
# [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
``` ```

View File

@ -7,7 +7,7 @@ Builds a list, using an iterator function and an initial seed value.
- The iterator function accepts one argument (`seed`) and must always return a list with two elements ([`value`, `nextSeed`]) or `False` to terminate. - The iterator function accepts one argument (`seed`) and must always return a list with two elements ([`value`, `nextSeed`]) or `False` to terminate.
- Use a generator function, `fn_generator`, that uses a `while` loop to call the iterator function and `yield` the `value` until it returns `False`. - Use a generator function, `fn_generator`, that uses a `while` loop to call the iterator function and `yield` the `value` until it returns `False`.
- Use list comprehension to return the list that is produced by the generator, using the iterator function. - Use a list comprehension to return the list that is produced by the generator, using the iterator function.
```py ```py
def unfold(fn, seed): def unfold(fn, seed):

View File

@ -13,5 +13,5 @@ def union(a, b):
``` ```
```py ```py
union([1, 2, 3], [4, 3, 2]) # [1,2,3,4] union([1, 2, 3], [4, 3, 2]) # [1, 2, 3, 4]
``` ```

View File

@ -1,11 +1,12 @@
--- ---
title: union_by title: union_by
tags: list,function,intermediate tags: list,intermediate
--- ---
Returns every element that exists in any of the two lists once, after applying the provided function to each element of both. Returns every element that exists in any of the two lists once, after applying the provided function to each element of both.
- Create a `set` by applying `fn` to each element in `a`, then use list comprehension in combination with `fn` on `b` to only keep values not contained in the previously created set, `_a`. - Create a `set` by applying `fn` to each element in `a`.
- Use a list comprehension in combination with `fn` on `b` to only keep values not contained in the previously created set, `_a`.
- Finally, create a `set` from the previous result and `a` and transform it into a `list` - Finally, create a `set` from the previous result and `a` and transform it into a `list`
```py ```py
@ -16,5 +17,6 @@ def union_by(a, b, fn):
```py ```py
from math import floor from math import floor
union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2] union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]
``` ```

View File

@ -15,9 +15,9 @@ def values_only(flat_dict):
```py ```py
ages = { ages = {
"Peter": 10, 'Peter': 10,
"Isabel": 11, 'Isabel': 11,
"Anna": 9, 'Anna': 9,
} }
values_only(ages) # [10, 11, 9] values_only(ages) # [10, 11, 9]
``` ```

View File

@ -14,5 +14,5 @@ def weighted_average(nums, weights):
``` ```
```py ```py
weighted_average([1, 2, 3], [0.6,0.2,0.3]) # 1.72727 weighted_average([1, 2, 3], [0.6, 0.2, 0.3]) # 1.72727
``` ```

View File

@ -3,7 +3,7 @@ title: words
tags: string,regexp,beginner tags: string,regexp,beginner
--- ---
Converts a given string into an array of words. Converts a given string into a list of words.
- Use `re.findall()` with the supplied `pattern` to find all matching substrings. - Use `re.findall()` with the supplied `pattern` to find all matching substrings.
- Omit the second argument to use the default regexp, which matches alphanumeric and hyphens. - Omit the second argument to use the default regexp, which matches alphanumeric and hyphens.
@ -18,5 +18,6 @@ def words(s, pattern = '[a-zA-Z-]+'):
```py ```py
words('I love Python!!') # ['I', 'love', 'Python'] words('I love Python!!') # ['I', 'love', 'Python']
words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee'] words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee']
words('build -q --out one-item', r'\b[a-zA-Z-]+\b') # ['build', 'q', 'out', 'one-item'] words('build -q --out one-item', r'\b[a-zA-Z-]+\b')
# ['build', 'q', 'out', 'one-item']
``` ```