Update snippet descriptions
This commit is contained in:
@ -3,9 +3,10 @@ title: all_unique
|
||||
tags: list,beginner
|
||||
---
|
||||
|
||||
Returns `True` if all the values in a list are unique, `False` otherwise.
|
||||
Checks if all the values in a list are unique.
|
||||
|
||||
- Use `set()` on the given list to remove duplicates, use `len()` to compare its length with the length of the list.
|
||||
- Use `set()` on the given list to keep only unique occurences.
|
||||
- Use `len()` to compare the length of the unique values to the original list.
|
||||
|
||||
```py
|
||||
def all_unique(lst):
|
||||
|
||||
@ -3,9 +3,9 @@ title: arithmetic_progression
|
||||
tags: math,beginner
|
||||
---
|
||||
|
||||
Returns a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit.
|
||||
Generates a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit.
|
||||
|
||||
- Use `range` and `list` with the appropriate start, step and end values.
|
||||
- Use `range()` and `list()` with the appropriate start, step and end values.
|
||||
|
||||
```py
|
||||
def arithmetic_progression(n, lim):
|
||||
|
||||
@ -3,9 +3,9 @@ title: average
|
||||
tags: math,list,beginner
|
||||
---
|
||||
|
||||
Returns the average of two or more numbers.
|
||||
Calculates the average of two or more numbers.
|
||||
|
||||
- Use `sum()` to sum all of the `args` provided, divide by `len(args)`.
|
||||
- Use `sum()` to sum all of the `args` provided, divide by `len()`.
|
||||
|
||||
```py
|
||||
def average(*args):
|
||||
|
||||
@ -1,18 +1,20 @@
|
||||
---
|
||||
title: average_by
|
||||
tags: math,list,function,intermediate
|
||||
tags: math,list,intermediate
|
||||
---
|
||||
|
||||
Returns the average of a list, after mapping each element to a value using the provided function.
|
||||
Calculates the average of a list, after mapping each element to a value using the provided function.
|
||||
|
||||
- Use `map()` to map each element to the value returned by `fn`.
|
||||
- Use `sum()` to sum all of the mapped values, divide by `len(lst)`.
|
||||
- Omit the last argument, `fn`, to use the default identity function.
|
||||
|
||||
```py
|
||||
def average_by(lst, fn=lambda x: x):
|
||||
def average_by(lst, fn = lambda x: x):
|
||||
return sum(map(fn, lst), 0.0) / len(lst)
|
||||
```
|
||||
|
||||
```py
|
||||
average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n']) # 5.0
|
||||
average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n'])
|
||||
# 5.0
|
||||
```
|
||||
|
||||
@ -3,10 +3,10 @@ title: bifurcate
|
||||
tags: list,intermediate
|
||||
---
|
||||
|
||||
Splits values into two groups.
|
||||
If an element in `filter` is `True`, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
|
||||
Splits values into two groups, based on the result of the given `filter` list.
|
||||
|
||||
- Use list comprehension and `zip()` to add elements to groups, based on `filter`.
|
||||
- Use a list comprehension and `zip()` to add elements to groups, based on `filter`.
|
||||
- If `filter` has a truthy value for any element, add it to the first group, otherwise add it to the second group.
|
||||
|
||||
```py
|
||||
def bifurcate(lst, filter):
|
||||
@ -17,5 +17,6 @@ def bifurcate(lst, filter):
|
||||
```
|
||||
|
||||
```py
|
||||
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ]
|
||||
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
|
||||
# [ ['beep', 'boop', 'bar'], ['foo'] ]
|
||||
```
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
---
|
||||
title: bifurcate_by
|
||||
tags: list,function,intermediate
|
||||
tags: list,intermediate
|
||||
---
|
||||
|
||||
Splits values into two groups according to a function, which specifies which group an element in the input list belongs to.
|
||||
If the function returns `True`, the element belongs to the first group; otherwise, it belongs to the second group.
|
||||
Splits values into two groups, based on the result of the given filtering function.
|
||||
|
||||
- Use list comprehension to add elements to groups, based on `fn`.
|
||||
- Use a list comprehension to add elements to groups, based on the value returned by `fn` for each element.
|
||||
- If `fn` returns a truthy value for any element, add it to the first group, otherwise add it to the second group.
|
||||
|
||||
```py
|
||||
def bifurcate_by(lst, fn):
|
||||
@ -17,8 +17,6 @@ def bifurcate_by(lst, fn):
|
||||
```
|
||||
|
||||
```py
|
||||
bifurcate_by(
|
||||
['beep', 'boop', 'foo', 'bar'],
|
||||
lambda x: x[0] == 'b'
|
||||
) # [ ['beep', 'boop', 'bar'], ['foo'] ]
|
||||
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
|
||||
# [ ['beep', 'boop', 'bar'], ['foo'] ]
|
||||
```
|
||||
|
||||
@ -3,7 +3,7 @@ title: binomial_coefficient
|
||||
tags: math,beginner
|
||||
---
|
||||
|
||||
Returns the number of ways to choose `k` items from `n` items without repetition and without order.
|
||||
Calculates the number of ways to choose `k` items from `n` items without repetition and without order.
|
||||
|
||||
- Use `math.comb()` to calculate the binomial coefficient.
|
||||
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,beginner
|
||||
|
||||
Returns the length of a string in bytes.
|
||||
|
||||
- Use `s.encode('utf-8')` to encode the given string and return its length.
|
||||
- Use `str.encode('utf-8')` to encode the given string and return its length.
|
||||
|
||||
```py
|
||||
def byte_size(s):
|
||||
|
||||
@ -6,20 +6,22 @@ tags: string,regexp,intermediate
|
||||
Converts a string to camelcase.
|
||||
|
||||
- Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`.
|
||||
- Use `title()` to capitalize the first letter of each word convert the rest to lowercase.
|
||||
- Finally, use `replace()` to remove spaces between words.
|
||||
- Use `str.title()` to capitalize the first letter of each word and convert the rest to lowercase.
|
||||
- Finally, use `str.replace()` to remove spaces between words.
|
||||
|
||||
```py
|
||||
from re import sub
|
||||
|
||||
def camel(s):
|
||||
s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
|
||||
return s[0].lower() + s[1:]
|
||||
return ''.join([s[0].lower(), s[1:]])
|
||||
```
|
||||
|
||||
```py
|
||||
camel('some_database_field_name') # 'someDatabaseFieldName'
|
||||
camel('Some label that needs to be camelized') # 'someLabelThatNeedsToBeCamelized'
|
||||
camel('Some label that needs to be camelized')
|
||||
# 'someLabelThatNeedsToBeCamelized'
|
||||
camel('some-javascript-property') # 'someJavascriptProperty'
|
||||
camel('some-mixed_string with spaces_underscores-and-hyphens') # 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
||||
camel('some-mixed_string with spaces_underscores-and-hyphens')
|
||||
# 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
||||
```
|
||||
|
||||
@ -5,15 +5,16 @@ tags: string,intermediate
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
- Capitalize the first letter of the string and then add it with rest of the string.
|
||||
- Use list slicing and `str.upper()` to capitalize the first letter of the string.
|
||||
- Use `str.join()` to combine the capitalized first letter with the rest of the characters.
|
||||
- Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase.
|
||||
|
||||
```py
|
||||
def capitalize(s, lower_rest=False):
|
||||
return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])
|
||||
def capitalize(s, lower_rest = False):
|
||||
return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])
|
||||
```
|
||||
|
||||
```py
|
||||
capitalize('fooBar') # 'FooBar'
|
||||
capitalize('fooBar', True) # 'Foobar'
|
||||
```
|
||||
```
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,beginner
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
- Use `s.title()` to capitalize first letter of every word in the string.
|
||||
- Use `str.title()` to capitalize the first letter of every word in the string.
|
||||
|
||||
```py
|
||||
def capitalize_every_word(s):
|
||||
@ -14,4 +14,4 @@ def capitalize_every_word(s):
|
||||
|
||||
```py
|
||||
capitalize_every_word('hello world!') # 'Hello World!'
|
||||
```
|
||||
```
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
---
|
||||
title: cast_list
|
||||
tags: list,beginner
|
||||
tags: list,intermediate
|
||||
---
|
||||
|
||||
Casts the provided value as a list if it's not one.
|
||||
|
||||
- Use `isinstance()` to check if the given value is enumerable and return it by using `list()` or encapsulated in a list accordingly.
|
||||
- Use `isinstance()` to check if the given value is enumerable.
|
||||
- Return it by using `list()` or encapsulated in a list accordingly.
|
||||
|
||||
```py
|
||||
def cast_list(val):
|
||||
|
||||
@ -5,11 +5,11 @@ tags: math,beginner
|
||||
|
||||
Converts Celsius to Fahrenheit.
|
||||
|
||||
- Use the formula `fahrenheit = (celsius * 1.8) + 32` to convert from Celsius to Fahrenheit.
|
||||
- Follow the conversion formula `F = 1.8 * C + 32`.
|
||||
|
||||
```py
|
||||
def celsius_to_fahrenheit(celsius):
|
||||
return ((celsius * 1.8) + 32)
|
||||
def celsius_to_fahrenheit(degrees):
|
||||
return ((degrees * 1.8) + 32)
|
||||
```
|
||||
|
||||
```py
|
||||
|
||||
@ -3,7 +3,7 @@ title: check_prop
|
||||
tags: function,intermediate
|
||||
---
|
||||
|
||||
Given a predicate function, `fn`, and a `prop` string, this curried function will then take an object to inspect by calling the property and passing it to the predicate.
|
||||
Creates a function that will invoke a predicate function for the specified property on a given object.
|
||||
|
||||
- Return a `lambda` function that takes an object and applies the predicate function, `fn` to the specified property.
|
||||
|
||||
@ -15,6 +15,5 @@ def check_prop(fn, prop):
|
||||
```py
|
||||
check_age = check_prop(lambda x: x >= 18, 'age')
|
||||
user = {'name': 'Mark', 'age': 18}
|
||||
|
||||
check_age(user) # True
|
||||
```
|
||||
|
||||
@ -19,5 +19,5 @@ def chunk(lst, size):
|
||||
```
|
||||
|
||||
```py
|
||||
chunk([1, 2, 3, 4, 5], 2) # [[1,2],[3,4],[5]]
|
||||
chunk([1, 2, 3, 4, 5], 2) # [[1, 2], [3, 4], [5]]
|
||||
```
|
||||
|
||||
@ -3,13 +3,13 @@ title: clamp_number
|
||||
tags: math,beginner
|
||||
---
|
||||
|
||||
Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.
|
||||
Clamps `num` within the inclusive range specified by the boundary values.
|
||||
|
||||
- If `num` falls within the range, return `num`.
|
||||
- If `num` falls within the range (`a`, `b`), return `num`.
|
||||
- Otherwise, return the nearest number in the range.
|
||||
|
||||
```py
|
||||
def clamp_number(num,a,b):
|
||||
def clamp_number(num, a, b):
|
||||
return max(min(num, max(a, b)), min(a, b))
|
||||
```
|
||||
|
||||
|
||||
@ -5,9 +5,9 @@ tags: dictionary,intermediate
|
||||
|
||||
Inverts a dictionary with non-unique hashable values.
|
||||
|
||||
- Create a `defaultdict` with `list` as the default value for each key.
|
||||
- Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `append()`.
|
||||
- Use `dict()` to convert the `defaultdict` to a regular dictionary.
|
||||
- Create a `collections.defaultdict` with `list` as the default value for each key.
|
||||
- Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `dict.append()`.
|
||||
- Use `dict()` to convert the `collections.defaultdict` to a regular dictionary.
|
||||
|
||||
```py
|
||||
from collections import defaultdict
|
||||
@ -21,9 +21,9 @@ def collect_dictionary(obj):
|
||||
|
||||
```py
|
||||
ages = {
|
||||
"Peter": 10,
|
||||
"Isabel": 10,
|
||||
"Anna": 9,
|
||||
'Peter': 10,
|
||||
'Isabel': 10,
|
||||
'Anna': 9,
|
||||
}
|
||||
collect_dictionary(ages) # { 10: ["Peter", "Isabel"], 9: ["Anna"] }
|
||||
collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }
|
||||
```
|
||||
|
||||
@ -3,9 +3,9 @@ title: compact
|
||||
tags: list,beginner
|
||||
---
|
||||
|
||||
Removes falsey values from a list.
|
||||
Removes falsy values from a list.
|
||||
|
||||
- Use `filter()` to filter out falsey values (`False`, `None`, `0`, and `""`).
|
||||
- Use `filter()` to filter out falsy values (`False`, `None`, `0`, and `""`).
|
||||
|
||||
```py
|
||||
def compact(lst):
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: compose
|
||||
tags: function,intermediate
|
||||
tags: function,advanced
|
||||
---
|
||||
|
||||
Performs right-to-left function composition.
|
||||
@ -19,6 +19,5 @@ def compose(*fns):
|
||||
add5 = lambda x: x + 5
|
||||
multiply = lambda x, y: x * y
|
||||
multiply_and_add_5 = compose(add5, multiply)
|
||||
|
||||
multiply_and_add_5(5, 2) # 15
|
||||
```
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: compose_right
|
||||
tags: function,intermediate
|
||||
tags: function,advanced
|
||||
---
|
||||
|
||||
Performs left-to-right function composition.
|
||||
@ -18,7 +18,6 @@ def compose_right(*fns):
|
||||
```py
|
||||
add = lambda x, y: x + y
|
||||
square = lambda x: x * x
|
||||
add_and_square = compose_right(add,square)
|
||||
|
||||
add_and_square = compose_right(add, square)
|
||||
add_and_square(1, 2) # 9
|
||||
```
|
||||
|
||||
@ -5,14 +5,14 @@ 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 `collections.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
|
||||
from collections import defaultdict
|
||||
|
||||
def count_by(lst, fn=lambda x: x):
|
||||
def count_by(lst, fn = lambda x: x):
|
||||
count = defaultdict(int)
|
||||
for val in map(fn, lst):
|
||||
count[val] += 1
|
||||
@ -21,6 +21,7 @@ def count_by(lst, fn=lambda x: x):
|
||||
|
||||
```py
|
||||
from math import floor
|
||||
|
||||
count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}
|
||||
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}
|
||||
```
|
||||
|
||||
@ -11,12 +11,11 @@ Curries a function.
|
||||
from functools import partial
|
||||
|
||||
def curry(fn, *args):
|
||||
return partial(fn,*args)
|
||||
return partial(fn, *args)
|
||||
```
|
||||
|
||||
```py
|
||||
add = lambda x, y: x + y
|
||||
add10 = curry(add, 10)
|
||||
|
||||
add10(20) # 30
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user