Merge 30-seconds-of-python
This commit is contained in:
23
python/snippet-template.md
Normal file
23
python/snippet-template.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Function name
|
||||
type: snippet
|
||||
tags: [utility]
|
||||
cover: image
|
||||
dateModified: 2021-06-13T05:00:00-04:00
|
||||
---
|
||||
|
||||
Explain briefly what the snippet does.
|
||||
|
||||
- Explain briefly how the snippet works.
|
||||
- Use bullet points for your snippet's explanation.
|
||||
- Try to explain everything briefly but clearly.
|
||||
|
||||
```py
|
||||
def function_name(args):
|
||||
# code
|
||||
return 0
|
||||
```
|
||||
|
||||
```py
|
||||
function_name(val) # result
|
||||
```
|
||||
26
python/snippets/add-days.md
Normal file
26
python/snippets/add-days.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Add days to date
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: orange-flower
|
||||
dateModified: 2020-10-28T16:19:04+02:00
|
||||
---
|
||||
|
||||
Calculates the date of `n` days from the given date.
|
||||
|
||||
- Use `datetime.timedelta` and the `+` operator to calculate the new `datetime.datetime` value after adding `n` days to `d`.
|
||||
- Omit the second argument, `d`, to use a default value of `datetime.today()`.
|
||||
|
||||
```py
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
def add_days(n, d = datetime.today()):
|
||||
return d + timedelta(n)
|
||||
```
|
||||
|
||||
```py
|
||||
from datetime import date
|
||||
|
||||
add_days(5, date(2020, 10, 25)) # date(2020, 10, 30)
|
||||
add_days(-5, date(2020, 10, 25)) # date(2020, 10, 20)
|
||||
```
|
||||
21
python/snippets/all-equal.md
Normal file
21
python/snippets/all-equal.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Check if list elements are identical
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: fallen-leaves
|
||||
dateModified: 2020-10-11T13:40:42+03:00
|
||||
---
|
||||
|
||||
Checks if all elements in a list are equal.
|
||||
|
||||
- Use `set()` to eliminate duplicate elements and then use `len()` to check if length is `1`.
|
||||
|
||||
```py
|
||||
def all_equal(lst):
|
||||
return len(set(lst)) == 1
|
||||
```
|
||||
|
||||
```py
|
||||
all_equal([1, 2, 3, 4, 5, 6]) # False
|
||||
all_equal([1, 1, 1, 1]) # True
|
||||
```
|
||||
24
python/snippets/all-unique.md
Normal file
24
python/snippets/all-unique.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Check if list has no duplicates
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: touch-flower
|
||||
dateModified: 2021-01-07T23:30:28+02:00
|
||||
---
|
||||
|
||||
Checks if all the values in a list are unique.
|
||||
|
||||
- Use `set()` on the given list to keep only unique occurrences.
|
||||
- Use `len()` to compare the length of the unique values to the original list.
|
||||
|
||||
```py
|
||||
def all_unique(lst):
|
||||
return len(lst) == len(set(lst))
|
||||
```
|
||||
|
||||
```py
|
||||
x = [1, 2, 3, 4, 5, 6]
|
||||
y = [1, 2, 2, 3, 4, 5]
|
||||
all_unique(x) # True
|
||||
all_unique(y) # False
|
||||
```
|
||||
20
python/snippets/arithmetic-progression.md
Normal file
20
python/snippets/arithmetic-progression.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Arithmetic progression
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: number-2
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
```py
|
||||
def arithmetic_progression(n, lim):
|
||||
return list(range(n, lim + 1, n))
|
||||
```
|
||||
|
||||
```py
|
||||
arithmetic_progression(5, 25) # [5, 10, 15, 20, 25]
|
||||
```
|
||||
23
python/snippets/average-by.md
Normal file
23
python/snippets/average-by.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Mapped list average
|
||||
type: snippet
|
||||
tags: [math,list]
|
||||
cover: flower-vase
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
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):
|
||||
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
|
||||
```
|
||||
21
python/snippets/average.md
Normal file
21
python/snippets/average.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Average
|
||||
type: snippet
|
||||
tags: [math,list]
|
||||
cover: digital-nomad-15
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Calculates the average of two or more numbers.
|
||||
|
||||
- Use `sum()` to sum all of the `args` provided, divide by `len()`.
|
||||
|
||||
```py
|
||||
def average(*args):
|
||||
return sum(args, 0.0) / len(args)
|
||||
```
|
||||
|
||||
```py
|
||||
average(*[1, 2, 3]) # 2.0
|
||||
average(1, 2, 3) # 2.0
|
||||
```
|
||||
25
python/snippets/bifurcate-by.md
Normal file
25
python/snippets/bifurcate-by.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Bifurcate list based on function
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: two-flower-vases
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Splits values into two groups, based on the result of the given filtering function.
|
||||
|
||||
- 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):
|
||||
return [
|
||||
[x for x in lst if fn(x)],
|
||||
[x for x in lst if not fn(x)]
|
||||
]
|
||||
```
|
||||
|
||||
```py
|
||||
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
|
||||
# [ ['beep', 'boop', 'bar'], ['foo'] ]
|
||||
```
|
||||
25
python/snippets/bifurcate.md
Normal file
25
python/snippets/bifurcate.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Bifurcate list based on values
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: mug-flower-book
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Splits values into two groups, based on the result of the given `filter` list.
|
||||
|
||||
- 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):
|
||||
return [
|
||||
[x for x, flag in zip(lst, filter) if flag],
|
||||
[x for x, flag in zip(lst, filter) if not flag]
|
||||
]
|
||||
```
|
||||
|
||||
```py
|
||||
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
|
||||
# [ ['beep', 'boop', 'bar'], ['foo'] ]
|
||||
```
|
||||
22
python/snippets/binomial-coefficient.md
Normal file
22
python/snippets/binomial-coefficient.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Binomial coefficient
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: digital-nomad-5
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
```py
|
||||
from math import comb
|
||||
|
||||
def binomial_coefficient(n, k):
|
||||
return comb(n, k)
|
||||
```
|
||||
|
||||
```py
|
||||
binomial_coefficient(8, 2) # 28
|
||||
```
|
||||
21
python/snippets/byte-size.md
Normal file
21
python/snippets/byte-size.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Byte size of string
|
||||
type: snippet
|
||||
tags: [string]
|
||||
cover: river-house-lights
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Returns the length of a string in bytes.
|
||||
|
||||
- Use `str.encode()` to encode the given string and return its length.
|
||||
|
||||
```py
|
||||
def byte_size(s):
|
||||
return len(s.encode('utf-8'))
|
||||
```
|
||||
|
||||
```py
|
||||
byte_size('😀') # 4
|
||||
byte_size('Hello World') # 11
|
||||
```
|
||||
30
python/snippets/camel.md
Normal file
30
python/snippets/camel.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Camelcase string
|
||||
type: snippet
|
||||
tags: [string,regexp]
|
||||
cover: digital-nomad-9
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Converts a string to camelcase.
|
||||
|
||||
- Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`.
|
||||
- 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 ''.join([s[0].lower(), s[1:]])
|
||||
```
|
||||
|
||||
```py
|
||||
camel('some_database_field_name') # 'someDatabaseFieldName'
|
||||
camel('Some label that needs to be camelized')
|
||||
# 'someLabelThatNeedsToBeCamelized'
|
||||
camel('some-javascript-property') # 'someJavascriptProperty'
|
||||
camel('some-mixed_string with spaces_underscores-and-hyphens')
|
||||
# 'someMixedStringWithSpacesUnderscoresAndHyphens'
|
||||
```
|
||||
20
python/snippets/capitalize-every-word.md
Normal file
20
python/snippets/capitalize-every-word.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Capitalize every word
|
||||
type: snippet
|
||||
tags: [string]
|
||||
cover: trippy-chemicals
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
- Use `str.title()` to capitalize the first letter of every word in the string.
|
||||
|
||||
```py
|
||||
def capitalize_every_word(s):
|
||||
return s.title()
|
||||
```
|
||||
|
||||
```py
|
||||
capitalize_every_word('hello world!') # 'Hello World!'
|
||||
```
|
||||
23
python/snippets/capitalize.md
Normal file
23
python/snippets/capitalize.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Capitalize string
|
||||
type: snippet
|
||||
tags: [string]
|
||||
cover: palm-tree-house
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Capitalizes the first letter of a 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 ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])
|
||||
```
|
||||
|
||||
```py
|
||||
capitalize('fooBar') # 'FooBar'
|
||||
capitalize('fooBar', True) # 'Foobar'
|
||||
```
|
||||
23
python/snippets/cast-list.md
Normal file
23
python/snippets/cast-list.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Cast to list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: colorful-pots
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Casts the provided value as a list if it's not one.
|
||||
|
||||
- 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):
|
||||
return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
|
||||
```
|
||||
|
||||
```py
|
||||
cast_list('foo') # ['foo']
|
||||
cast_list([1]) # [1]
|
||||
cast_list(('foo', 'bar')) # ['foo', 'bar']
|
||||
```
|
||||
21
python/snippets/celsius-to-fahrenheit.md
Normal file
21
python/snippets/celsius-to-fahrenheit.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Celsius to Fahrenheit
|
||||
type: snippet
|
||||
tags: [math]
|
||||
unlisted: true
|
||||
cover: last-light
|
||||
dateModified: 2021-01-04T12:47:04+02:00
|
||||
---
|
||||
|
||||
Converts Celsius to Fahrenheit.
|
||||
|
||||
- Follow the conversion formula `F = 1.8 * C + 32`.
|
||||
|
||||
```py
|
||||
def celsius_to_fahrenheit(degrees):
|
||||
return ((degrees * 1.8) + 32)
|
||||
```
|
||||
|
||||
```py
|
||||
celsius_to_fahrenheit(180) # 356.0
|
||||
```
|
||||
22
python/snippets/check-prop.md
Normal file
22
python/snippets/check-prop.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Check property
|
||||
type: snippet
|
||||
tags: [function]
|
||||
cover: lake-trees
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Creates a function that will invoke a predicate function for the specified property on a given dictionary.
|
||||
|
||||
- Return a `lambda` function that takes a dictionary and applies the predicate function, `fn` to the specified property.
|
||||
|
||||
```py
|
||||
def check_prop(fn, prop):
|
||||
return lambda obj: fn(obj[prop])
|
||||
```
|
||||
|
||||
```py
|
||||
check_age = check_prop(lambda x: x >= 18, 'age')
|
||||
user = {'name': 'Mark', 'age': 18}
|
||||
check_age(user) # True
|
||||
```
|
||||
29
python/snippets/chunk-into-n.md
Normal file
29
python/snippets/chunk-into-n.md
Normal file
@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Split list into n chunks
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: succulent-10
|
||||
dateModified: 2020-10-23T05:35:06+03:00
|
||||
---
|
||||
|
||||
Chunks a list into `n` smaller lists.
|
||||
|
||||
- Use `math.ceil()` and `len()` to get the size of each chunk.
|
||||
- Use `list()` and `range()` to create a new list of size `n`.
|
||||
- Use `map()` to map each element of the new list to a chunk the length of `size`.
|
||||
- If the original list can't be split evenly, the final chunk will contain the remaining elements.
|
||||
|
||||
```py
|
||||
from math import ceil
|
||||
|
||||
def chunk_into_n(lst, n):
|
||||
size = ceil(len(lst) / n)
|
||||
return list(
|
||||
map(lambda x: lst[x * size:x * size + size],
|
||||
list(range(n)))
|
||||
)
|
||||
```
|
||||
|
||||
```py
|
||||
chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4) # [[1, 2], [3, 4], [5, 6], [7]]
|
||||
```
|
||||
26
python/snippets/chunk.md
Normal file
26
python/snippets/chunk.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Split list into chunks
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: red-berries
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Chunks a list into smaller lists of a specified size.
|
||||
|
||||
- Use `list()` and `range()` to create a list of the desired `size`.
|
||||
- Use `map()` on the list and fill it with splices of the given list.
|
||||
- Finally, return the created list.
|
||||
|
||||
```py
|
||||
from math import ceil
|
||||
|
||||
def chunk(lst, size):
|
||||
return list(
|
||||
map(lambda x: lst[x * size:x * size + size],
|
||||
list(range(ceil(len(lst) / size)))))
|
||||
```
|
||||
|
||||
```py
|
||||
chunk([1, 2, 3, 4, 5], 2) # [[1, 2], [3, 4], [5]]
|
||||
```
|
||||
22
python/snippets/clamp-number.md
Normal file
22
python/snippets/clamp-number.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Clamp number
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: highlands
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Clamps `num` within the inclusive range specified by the boundary values.
|
||||
|
||||
- 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):
|
||||
return max(min(num, max(a, b)), min(a, b))
|
||||
```
|
||||
|
||||
```py
|
||||
clamp_number(2, 3, 5) # 3
|
||||
clamp_number(1, -1, -5) # -1
|
||||
```
|
||||
32
python/snippets/collect-dictionary.md
Normal file
32
python/snippets/collect-dictionary.md
Normal file
@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Invert dictionary
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: working-bee
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Inverts a dictionary with non-unique hashable values.
|
||||
|
||||
- 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
|
||||
|
||||
def collect_dictionary(obj):
|
||||
inv_obj = defaultdict(list)
|
||||
for key, value in obj.items():
|
||||
inv_obj[value].append(key)
|
||||
return dict(inv_obj)
|
||||
```
|
||||
|
||||
```py
|
||||
ages = {
|
||||
'Peter': 10,
|
||||
'Isabel': 10,
|
||||
'Anna': 9,
|
||||
}
|
||||
collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }
|
||||
```
|
||||
31
python/snippets/combine-values.md
Normal file
31
python/snippets/combine-values.md
Normal file
@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Combine dictionary values
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: fruit-feast
|
||||
dateModified: 2021-04-04T14:32:35+03:00
|
||||
---
|
||||
|
||||
Combines two or more dictionaries, creating a list of values for each key.
|
||||
|
||||
- Create a new `collections.defaultdict` with `list` as the default value for each key and loop over `dicts`.
|
||||
- Use `dict.append()` to map the values of the dictionary to keys.
|
||||
- Use `dict()` to convert the `collections.defaultdict` to a regular dictionary.
|
||||
|
||||
```py
|
||||
from collections import defaultdict
|
||||
|
||||
def combine_values(*dicts):
|
||||
res = defaultdict(list)
|
||||
for d in dicts:
|
||||
for key in d:
|
||||
res[key].append(d[key])
|
||||
return dict(res)
|
||||
```
|
||||
|
||||
```py
|
||||
d1 = {'a': 1, 'b': 'foo', 'c': 400}
|
||||
d2 = {'a': 3, 'b': 200, 'd': 400}
|
||||
|
||||
combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}
|
||||
```
|
||||
20
python/snippets/compact.md
Normal file
20
python/snippets/compact.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Compact list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: new-plant
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Removes falsy values from a list.
|
||||
|
||||
- Use `filter()` to filter out falsy values (`False`, `None`, `0`, and `""`).
|
||||
|
||||
```py
|
||||
def compact(lst):
|
||||
return list(filter(None, lst))
|
||||
```
|
||||
|
||||
```py
|
||||
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
|
||||
```
|
||||
26
python/snippets/compose-right.md
Normal file
26
python/snippets/compose-right.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Reverse compose functions
|
||||
type: snippet
|
||||
tags: [function]
|
||||
cover: lavender-shelf
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Performs left-to-right function composition.
|
||||
|
||||
- Use `functools.reduce()` to perform left-to-right function composition.
|
||||
- The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
```py
|
||||
from functools import reduce
|
||||
|
||||
def compose_right(*fns):
|
||||
return reduce(lambda f, g: lambda *args: g(f(*args)), fns)
|
||||
```
|
||||
|
||||
```py
|
||||
add = lambda x, y: x + y
|
||||
square = lambda x: x * x
|
||||
add_and_square = compose_right(add, square)
|
||||
add_and_square(1, 2) # 9
|
||||
```
|
||||
26
python/snippets/compose.md
Normal file
26
python/snippets/compose.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Compose functions
|
||||
type: snippet
|
||||
tags: [function]
|
||||
cover: tram-car-2
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Performs right-to-left function composition.
|
||||
|
||||
- Use `functools.reduce()` to perform right-to-left function composition.
|
||||
- The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
```py
|
||||
from functools import reduce
|
||||
|
||||
def compose(*fns):
|
||||
return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
|
||||
```
|
||||
|
||||
```py
|
||||
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
|
||||
```
|
||||
30
python/snippets/count-by.md
Normal file
30
python/snippets/count-by.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Count grouped elements
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: rabbit-call
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Groups the elements of a list based on the given function and returns the count of elements in each group.
|
||||
|
||||
- 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):
|
||||
count = defaultdict(int)
|
||||
for val in map(fn, lst):
|
||||
count[val] += 1
|
||||
return dict(count)
|
||||
```
|
||||
|
||||
```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}
|
||||
```
|
||||
20
python/snippets/count-occurrences.md
Normal file
20
python/snippets/count-occurrences.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Count occurrences
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: pineapple-at-work
|
||||
dateModified: 2021-01-10T00:00:36+02:00
|
||||
---
|
||||
|
||||
Counts the occurrences of a value in a list.
|
||||
|
||||
- Use `list.count()` to count the number of occurrences of `val` in `lst`.
|
||||
|
||||
```py
|
||||
def count_occurrences(lst, val):
|
||||
return lst.count(val)
|
||||
```
|
||||
|
||||
```py
|
||||
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
|
||||
```
|
||||
23
python/snippets/cumsum.md
Normal file
23
python/snippets/cumsum.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Partial sum list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: digital-nomad-16
|
||||
dateModified: 2021-01-13T23:30:41+02:00
|
||||
---
|
||||
|
||||
Creates a list of partial sums.
|
||||
|
||||
- Use `itertools.accumulate()` to create the accumulated sum for each element.
|
||||
- Use `list()` to convert the result into a list.
|
||||
|
||||
```py
|
||||
from itertools import accumulate
|
||||
|
||||
def cumsum(lst):
|
||||
return list(accumulate(lst))
|
||||
```
|
||||
|
||||
```py
|
||||
cumsum(range(0, 15, 3)) # [0, 3, 9, 18, 30]
|
||||
```
|
||||
24
python/snippets/curry.md
Normal file
24
python/snippets/curry.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Curry function
|
||||
type: snippet
|
||||
tags: [function]
|
||||
cover: leaves-read
|
||||
dateModified: 2020-11-02T19:27:07+02:00
|
||||
---
|
||||
|
||||
Curries a function.
|
||||
|
||||
- Use `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied.
|
||||
|
||||
```py
|
||||
from functools import partial
|
||||
|
||||
def curry(fn, *args):
|
||||
return partial(fn, *args)
|
||||
```
|
||||
|
||||
```py
|
||||
add = lambda x, y: x + y
|
||||
add10 = curry(add, 10)
|
||||
add10(20) # 30
|
||||
```
|
||||
27
python/snippets/daterange.md
Normal file
27
python/snippets/daterange.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Date range
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: maple-leaf-palette
|
||||
dateModified: 2021-01-07T23:30:28+02:00
|
||||
---
|
||||
|
||||
Creates a list of dates between `start` (inclusive) and `end` (not inclusive).
|
||||
|
||||
- Use `datetime.timedelta.days` to get the days between `start` and `end`.
|
||||
- Use `int()` to convert the result to an integer and `range()` to iterate over each day.
|
||||
- Use a list comprehension and `datetime.timedelta` to create a list of `datetime.date` objects.
|
||||
|
||||
```py
|
||||
from datetime import timedelta, date
|
||||
|
||||
def daterange(start, end):
|
||||
return [start + timedelta(n) for n in range(int((end - start).days))]
|
||||
```
|
||||
|
||||
```py
|
||||
from datetime import date
|
||||
|
||||
daterange(date(2020, 10, 1), date(2020, 10, 5))
|
||||
# [date(2020, 10, 1), date(2020, 10, 2), date(2020, 10, 3), date(2020, 10, 4)]
|
||||
```
|
||||
23
python/snippets/days-ago.md
Normal file
23
python/snippets/days-ago.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Days ago
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: cup-of-orange
|
||||
dateModified: 2020-10-28T16:19:30+02:00
|
||||
---
|
||||
|
||||
Calculates the date of `n` days ago from today.
|
||||
|
||||
- Use `datetime.date.today()` to get the current day.
|
||||
- Use `datetime.timedelta` to subtract `n` days from today's date.
|
||||
|
||||
```py
|
||||
from datetime import timedelta, date
|
||||
|
||||
def days_ago(n):
|
||||
return date.today() - timedelta(n)
|
||||
```
|
||||
|
||||
```py
|
||||
days_ago(5) # date(2020, 10, 23)
|
||||
```
|
||||
22
python/snippets/days-diff.md
Normal file
22
python/snippets/days-diff.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Date difference in days
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: succulent-9
|
||||
dateModified: 2020-10-28T16:19:39+02:00
|
||||
---
|
||||
|
||||
Calculates the day difference between two dates.
|
||||
|
||||
- Subtract `start` from `end` and use `datetime.timedelta.days` to get the day difference.
|
||||
|
||||
```py
|
||||
def days_diff(start, end):
|
||||
return (end - start).days
|
||||
```
|
||||
|
||||
```py
|
||||
from datetime import date
|
||||
|
||||
days_diff(date(2020, 10, 25), date(2020, 10, 28)) # 3
|
||||
```
|
||||
23
python/snippets/days-from-now.md
Normal file
23
python/snippets/days-from-now.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Days from now
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: clutter
|
||||
dateModified: 2020-10-28T16:19:51+02:00
|
||||
---
|
||||
|
||||
Calculates the date of `n` days from today.
|
||||
|
||||
- Use `datetime.date.today()` to get the current day.
|
||||
- Use `datetime.timedelta` to add `n` days from today's date.
|
||||
|
||||
```py
|
||||
from datetime import timedelta, date
|
||||
|
||||
def days_from_now(n):
|
||||
return date.today() + timedelta(n)
|
||||
```
|
||||
|
||||
```py
|
||||
days_from_now(5) # date(2020, 11, 02)
|
||||
```
|
||||
23
python/snippets/decapitalize.md
Normal file
23
python/snippets/decapitalize.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Decapitalize string
|
||||
type: snippet
|
||||
tags: [string]
|
||||
cover: succulent-crowd
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Decapitalizes the first letter of a string.
|
||||
|
||||
- Use list slicing and `str.lower()` to decapitalize the first letter of the string.
|
||||
- Use `str.join()` to combine the lowercase first letter with the rest of the characters.
|
||||
- Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase.
|
||||
|
||||
```py
|
||||
def decapitalize(s, upper_rest = False):
|
||||
return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])
|
||||
```
|
||||
|
||||
```py
|
||||
decapitalize('FooBar') # 'fooBar'
|
||||
decapitalize('FooBar', True) # 'fOOBAR'
|
||||
```
|
||||
25
python/snippets/deep-flatten.md
Normal file
25
python/snippets/deep-flatten.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Deep flatten list
|
||||
type: snippet
|
||||
tags: [list,recursion]
|
||||
cover: mask-quiet
|
||||
dateModified: 2020-12-29T19:53:45+02:00
|
||||
---
|
||||
|
||||
Deep flattens a list.
|
||||
|
||||
- Use recursion.
|
||||
- Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable.
|
||||
- If it is iterable, apply `deep_flatten()` recursively, otherwise return `[lst]`.
|
||||
|
||||
```py
|
||||
from collections.abc import Iterable
|
||||
|
||||
def deep_flatten(lst):
|
||||
return ([a for i in lst for a in
|
||||
deep_flatten(i)] if isinstance(lst, Iterable) else [lst])
|
||||
```
|
||||
|
||||
```py
|
||||
deep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5]
|
||||
```
|
||||
22
python/snippets/degrees-to-rads.md
Normal file
22
python/snippets/degrees-to-rads.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Degrees to radians
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: digital-nomad-6
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Converts an angle from degrees to radians.
|
||||
|
||||
- Use `math.pi` and the degrees to radians formula to convert the angle from degrees to radians.
|
||||
|
||||
```py
|
||||
from math import pi
|
||||
|
||||
def degrees_to_rads(deg):
|
||||
return (deg * pi) / 180.0
|
||||
```
|
||||
|
||||
```py
|
||||
degrees_to_rads(180) # ~3.1416
|
||||
```
|
||||
23
python/snippets/delay.md
Normal file
23
python/snippets/delay.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Delayed function execution
|
||||
type: snippet
|
||||
tags: [function]
|
||||
cover: succulent-10
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Invokes the provided function after `ms` milliseconds.
|
||||
|
||||
- Use `time.sleep()` to delay the execution of `fn` by `ms / 1000` seconds.
|
||||
|
||||
```py
|
||||
from time import sleep
|
||||
|
||||
def delay(fn, ms, *args):
|
||||
sleep(ms / 1000)
|
||||
return fn(*args)
|
||||
```
|
||||
|
||||
```py
|
||||
delay(lambda x: print(x), 1000, 'later') # prints 'later' after one second
|
||||
```
|
||||
22
python/snippets/dict-to-list.md
Normal file
22
python/snippets/dict-to-list.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Dictionary to list
|
||||
type: snippet
|
||||
tags: [dictionary,list]
|
||||
cover: new-york
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Converts a dictionary to a list of tuples.
|
||||
|
||||
- Use `dict.items()` and `list()` to get a list of tuples from the given dictionary.
|
||||
|
||||
```py
|
||||
def dict_to_list(d):
|
||||
return list(d.items())
|
||||
```
|
||||
|
||||
```py
|
||||
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
|
||||
dict_to_list(d)
|
||||
# [('one', 1), ('three', 3), ('five', 5), ('two', 2), ('four', 4)]
|
||||
```
|
||||
26
python/snippets/difference-by.md
Normal file
26
python/snippets/difference-by.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: List difference based on function
|
||||
type: snippet
|
||||
tags: [list,function]
|
||||
cover: coconuts
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Returns the difference between two lists, after applying the provided function to each list element of both.
|
||||
|
||||
- Create a `set`, using `map()` to apply `fn` to each element in `b`.
|
||||
- Use a list comprehension in combination with `fn` on `a` to only keep values not contained in the previously created set, `_b`.
|
||||
|
||||
```py
|
||||
def difference_by(a, b, fn):
|
||||
_b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) not in _b]
|
||||
```
|
||||
|
||||
```py
|
||||
from math import floor
|
||||
|
||||
difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]
|
||||
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])
|
||||
# [ { x: 2 } ]
|
||||
```
|
||||
22
python/snippets/difference.md
Normal file
22
python/snippets/difference.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: List difference
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: frog-blue-flower
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Calculates the difference between two iterables, without filtering duplicate values.
|
||||
|
||||
- Create a `set` from `b`.
|
||||
- Use a list comprehension on `a` to only keep values not contained in the previously created set, `_b`.
|
||||
|
||||
```py
|
||||
def difference(a, b):
|
||||
_b = set(b)
|
||||
return [item for item in a if item not in _b]
|
||||
```
|
||||
|
||||
```py
|
||||
difference([1, 2, 3], [1, 2, 4]) # [3]
|
||||
```
|
||||
20
python/snippets/digitize.md
Normal file
20
python/snippets/digitize.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Digitize number
|
||||
type: snippet
|
||||
tags: [math,list]
|
||||
cover: laptop-with-code
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Converts a number to a list of digits.
|
||||
|
||||
- Use `map()` combined with `int` on the string representation of `n` and return a list from the result.
|
||||
|
||||
```py
|
||||
def digitize(n):
|
||||
return list(map(int, str(n)))
|
||||
```
|
||||
|
||||
```py
|
||||
digitize(123) # [1, 2, 3]
|
||||
```
|
||||
24
python/snippets/drop-right.md
Normal file
24
python/snippets/drop-right.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Drop list elements from the right
|
||||
type: snippet
|
||||
tags: [list]
|
||||
author: chalarangelo
|
||||
cover: digital-nomad-7
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Returns a list with `n` elements removed from the right.
|
||||
|
||||
- Use slice notation to remove the specified number of elements from the right.
|
||||
- Omit the last argument, `n`, to use a default value of `1`.
|
||||
|
||||
```py
|
||||
def drop_right(a, n = 1):
|
||||
return a[:-n]
|
||||
```
|
||||
|
||||
```py
|
||||
drop_right([1, 2, 3]) # [1, 2]
|
||||
drop_right([1, 2, 3], 2) # [1]
|
||||
drop_right([1, 2, 3], 42) # []
|
||||
```
|
||||
24
python/snippets/drop.md
Normal file
24
python/snippets/drop.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Drop list elements from the left
|
||||
type: snippet
|
||||
tags: [list]
|
||||
author: chalarangelo
|
||||
cover: pink-flower
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Returns a list with `n` elements removed from the left.
|
||||
|
||||
- Use slice notation to remove the specified number of elements from the left.
|
||||
- Omit the last argument, `n`, to use a default value of `1`.
|
||||
|
||||
```py
|
||||
def drop(a, n = 1):
|
||||
return a[n:]
|
||||
```
|
||||
|
||||
```py
|
||||
drop([1, 2, 3]) # [2, 3]
|
||||
drop([1, 2, 3], 2) # [3]
|
||||
drop([1, 2, 3], 42) # []
|
||||
```
|
||||
20
python/snippets/every-nth.md
Normal file
20
python/snippets/every-nth.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Every nth element in list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: cherry-trees
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Returns every `nth` element in a list.
|
||||
|
||||
- Use slice notation to create a new list that contains every `nth` element of the given list.
|
||||
|
||||
```py
|
||||
def every_nth(lst, nth):
|
||||
return lst[nth - 1::nth]
|
||||
```
|
||||
|
||||
```py
|
||||
every_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ]
|
||||
```
|
||||
21
python/snippets/every.md
Normal file
21
python/snippets/every.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Test if every list element is truthy
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: walking
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Checks if the provided function returns `True` for every element in the list.
|
||||
|
||||
- Use `all()` in combination with `map()` and `fn` to check if `fn` returns `True` for all elements in the list.
|
||||
|
||||
```py
|
||||
def every(lst, fn = lambda x: x):
|
||||
return all(map(fn, lst))
|
||||
```
|
||||
|
||||
```py
|
||||
every([4, 2, 3], lambda x: x > 1) # True
|
||||
every([1, 2, 3]) # True
|
||||
```
|
||||
25
python/snippets/factorial.md
Normal file
25
python/snippets/factorial.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Factorial
|
||||
type: snippet
|
||||
tags: [math,recursion]
|
||||
cover: succulent-11
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
- Use recursion.
|
||||
- If `num` is less than or equal to `1`, return `1`.
|
||||
- Otherwise, return the product of `num` and the factorial of `num - 1`.
|
||||
- Throws an exception if `num` is a negative or a floating point number.
|
||||
|
||||
```py
|
||||
def factorial(num):
|
||||
if not ((num >= 0) and (num % 1 == 0)):
|
||||
raise Exception("Number can't be floating point or negative.")
|
||||
return 1 if num == 0 else num * factorial(num - 1)
|
||||
```
|
||||
|
||||
```py
|
||||
factorial(6) # 720
|
||||
```
|
||||
21
python/snippets/fahrenheit-to-celsius.md
Normal file
21
python/snippets/fahrenheit-to-celsius.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Fahrenheit to Celsius
|
||||
type: snippet
|
||||
tags: [math]
|
||||
unlisted: true
|
||||
cover: last-light
|
||||
dateModified: 2021-01-04T12:47:04+02:00
|
||||
---
|
||||
|
||||
Converts Fahrenheit to Celsius.
|
||||
|
||||
- Follow the conversion formula `C = (F - 32) * 5 / 9`.
|
||||
|
||||
```py
|
||||
def fahrenheit_to_celsius(degrees):
|
||||
return ((degrees - 32) * 5 / 9)
|
||||
```
|
||||
|
||||
```py
|
||||
fahrenheit_to_celsius(77) # 25.0
|
||||
```
|
||||
27
python/snippets/fibonacci.md
Normal file
27
python/snippets/fibonacci.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Fibonacci
|
||||
type: snippet
|
||||
tags: [math,list]
|
||||
cover: san-francisco-skyline
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Generates a list, containing the Fibonacci sequence, up until the nth term.
|
||||
|
||||
- Starting with `0` and `1`, use `list.append()` to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches `n`.
|
||||
- If `n` is less or equal to `0`, return a list containing `0`.
|
||||
|
||||
```py
|
||||
def fibonacci(n):
|
||||
if n <= 0:
|
||||
return [0]
|
||||
sequence = [0, 1]
|
||||
while len(sequence) <= n:
|
||||
next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
|
||||
sequence.append(next_value)
|
||||
return sequence
|
||||
```
|
||||
|
||||
```py
|
||||
fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13]
|
||||
```
|
||||
23
python/snippets/filter-non-unique.md
Normal file
23
python/snippets/filter-non-unique.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Filter non-unique list values
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: cobbled-street
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Creates a list with the non-unique values filtered out.
|
||||
|
||||
- Use `collections.Counter` to get the count of each value in the list.
|
||||
- Use a list comprehension to create a list containing only the unique values.
|
||||
|
||||
```py
|
||||
from collections import Counter
|
||||
|
||||
def filter_non_unique(lst):
|
||||
return [item for item, count in Counter(lst).items() if count == 1]
|
||||
```
|
||||
|
||||
```py
|
||||
filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]
|
||||
```
|
||||
23
python/snippets/filter-unique.md
Normal file
23
python/snippets/filter-unique.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Filter unique list values
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: feathers
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Creates a list with the unique values filtered out.
|
||||
|
||||
- Use `collections.Counter` to get the count of each value in the list.
|
||||
- Use a list comprehension to create a list containing only the non-unique values.
|
||||
|
||||
```py
|
||||
from collections import Counter
|
||||
|
||||
def filter_unique(lst):
|
||||
return [item for item, count in Counter(lst).items() if count > 1]
|
||||
```
|
||||
|
||||
```py
|
||||
filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]
|
||||
```
|
||||
20
python/snippets/find-index-of-all.md
Normal file
20
python/snippets/find-index-of-all.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Find all matching indexes
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: tree-roots
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the indexes of all elements in the given list that satisfy the provided testing function.
|
||||
|
||||
- Use `enumerate()` and a list comprehension to return the indexes of the all element in `lst` for which `fn` returns `True`.
|
||||
|
||||
```py
|
||||
def find_index_of_all(lst, fn):
|
||||
return [i for i, x in enumerate(lst) if fn(x)]
|
||||
```
|
||||
|
||||
```py
|
||||
find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1) # [0, 2]
|
||||
```
|
||||
20
python/snippets/find-index.md
Normal file
20
python/snippets/find-index.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Find matching index
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: book-chair
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the index of the first element in the given list that satisfies the provided testing function.
|
||||
|
||||
- Use a list comprehension, `enumerate()` and `next()` to return the index of the first element in `lst` for which `fn` returns `True`.
|
||||
|
||||
```py
|
||||
def find_index(lst, fn):
|
||||
return next(i for i, x in enumerate(lst) if fn(x))
|
||||
```
|
||||
|
||||
```py
|
||||
find_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 0
|
||||
```
|
||||
25
python/snippets/find-key.md
Normal file
25
python/snippets/find-key.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Find key of value
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: blue-red-mountain
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the first key in the provided dictionary that has the given value.
|
||||
|
||||
- Use `dictionary.items()` and `next()` to return the first key that has a value equal to `val`.
|
||||
|
||||
```py
|
||||
def find_key(dict, val):
|
||||
return next(key for key, value in dict.items() if value == val)
|
||||
```
|
||||
|
||||
```py
|
||||
ages = {
|
||||
'Peter': 10,
|
||||
'Isabel': 11,
|
||||
'Anna': 9,
|
||||
}
|
||||
find_key(ages, 11) # 'Isabel'
|
||||
```
|
||||
25
python/snippets/find-keys.md
Normal file
25
python/snippets/find-keys.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Find keys with value
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: laptop-plants-2
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds all keys in the provided dictionary that have the given value.
|
||||
|
||||
- Use `dictionary.items()`, a generator and `list()` to return all keys that have a value equal to `val`.
|
||||
|
||||
```py
|
||||
def find_keys(dict, val):
|
||||
return list(key for key, value in dict.items() if value == val)
|
||||
```
|
||||
|
||||
```py
|
||||
ages = {
|
||||
'Peter': 10,
|
||||
'Isabel': 11,
|
||||
'Anna': 10,
|
||||
}
|
||||
find_keys(ages, 10) # [ 'Peter', 'Anna' ]
|
||||
```
|
||||
20
python/snippets/find-last-index.md
Normal file
20
python/snippets/find-last-index.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Find last matching index
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: succulent-8
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the index of the last element in the given list that satisfies the provided testing function.
|
||||
|
||||
- Use a list comprehension, `enumerate()` and `next()` to return the index of the last element in `lst` for which `fn` returns `True`.
|
||||
|
||||
```py
|
||||
def find_last_index(lst, fn):
|
||||
return len(lst) - 1 - next(i for i, x in enumerate(lst[::-1]) if fn(x))
|
||||
```
|
||||
|
||||
```py
|
||||
find_last_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 2
|
||||
```
|
||||
20
python/snippets/find-last.md
Normal file
20
python/snippets/find-last.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Find last matching value
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: tropical-waterfall
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the value of the last element in the given list that satisfies the provided testing function.
|
||||
|
||||
- Use a list comprehension and `next()` to return the last element in `lst` for which `fn` returns `True`.
|
||||
|
||||
```py
|
||||
def find_last(lst, fn):
|
||||
return next(x for x in lst[::-1] if fn(x))
|
||||
```
|
||||
|
||||
```py
|
||||
find_last([1, 2, 3, 4], lambda n: n % 2 == 1) # 3
|
||||
```
|
||||
27
python/snippets/find-parity-outliers.md
Normal file
27
python/snippets/find-parity-outliers.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Find parity outliers
|
||||
type: snippet
|
||||
tags: [list,math]
|
||||
cover: beach-pineapple
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the items that are parity outliers in a given list.
|
||||
|
||||
- Use `collections.Counter` with a list comprehension to count even and odd values in the list.
|
||||
- Use `collections.Counter.most_common()` to get the most common parity.
|
||||
- Use a list comprehension to find all elements that do not match the most common parity.
|
||||
|
||||
```py
|
||||
from collections import Counter
|
||||
|
||||
def find_parity_outliers(nums):
|
||||
return [
|
||||
x for x in nums
|
||||
if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]
|
||||
]
|
||||
```
|
||||
|
||||
```py
|
||||
find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]
|
||||
```
|
||||
20
python/snippets/find.md
Normal file
20
python/snippets/find.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Find matching value
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: duck-plants
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Finds the value of the first element in the given list that satisfies the provided testing function.
|
||||
|
||||
- Use a list comprehension and `next()` to return the first element in `lst` for which `fn` returns `True`.
|
||||
|
||||
```py
|
||||
def find(lst, fn):
|
||||
return next(x for x in lst if fn(x))
|
||||
```
|
||||
|
||||
```py
|
||||
find([1, 2, 3, 4], lambda n: n % 2 == 1) # 1
|
||||
```
|
||||
20
python/snippets/flatten.md
Normal file
20
python/snippets/flatten.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Flatten list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: jars-on-shelf
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Flattens a list of lists once.
|
||||
|
||||
- Use a list comprehension to extract each value from sub-lists in order.
|
||||
|
||||
```py
|
||||
def flatten(lst):
|
||||
return [x for y in lst for x in y]
|
||||
```
|
||||
|
||||
```py
|
||||
flatten([[1, 2, 3, 4], [5, 6, 7, 8]]) # [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
```
|
||||
21
python/snippets/for-each-right.md
Normal file
21
python/snippets/for-each-right.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Execute function for each list element in reverse
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: bridge-drop
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Executes the provided function once for each list element, starting from the list's last element.
|
||||
|
||||
- Use a `for` loop in combination with slice notation to execute `fn` for each element in `itr`, starting from the last one.
|
||||
|
||||
```py
|
||||
def for_each_right(itr, fn):
|
||||
for el in itr[::-1]:
|
||||
fn(el)
|
||||
```
|
||||
|
||||
```py
|
||||
for_each_right([1, 2, 3], print) # 3 2 1
|
||||
```
|
||||
21
python/snippets/for-each.md
Normal file
21
python/snippets/for-each.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Execute function for each list element
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: green-plant
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Executes the provided function once for each list element.
|
||||
|
||||
- Use a `for` loop to execute `fn` for each element in `itr`.
|
||||
|
||||
```py
|
||||
def for_each(itr, fn):
|
||||
for el in itr:
|
||||
fn(el)
|
||||
```
|
||||
|
||||
```py
|
||||
for_each([1, 2, 3], print) # 1 2 3
|
||||
```
|
||||
26
python/snippets/frequencies.md
Normal file
26
python/snippets/frequencies.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Value frequencies
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: succulent-6
|
||||
dateModified: 2020-11-02T19:27:53+02:00
|
||||
---
|
||||
|
||||
Creates a dictionary with the unique values of a list as keys and their frequencies as the values.
|
||||
|
||||
- Use `collections.defaultdict` to store the frequencies of each unique element.
|
||||
- Use `dict()` to return a dictionary with the unique elements of the list as keys and their frequencies as the values.
|
||||
|
||||
```py
|
||||
from collections import defaultdict
|
||||
|
||||
def frequencies(lst):
|
||||
freq = defaultdict(int)
|
||||
for val in lst:
|
||||
freq[val] += 1
|
||||
return dict(freq)
|
||||
```
|
||||
|
||||
```py
|
||||
frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 }
|
||||
```
|
||||
22
python/snippets/from-iso-date.md
Normal file
22
python/snippets/from-iso-date.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Date from ISO format
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: purple-leaves
|
||||
dateModified: 2021-01-07T23:30:28+02:00
|
||||
---
|
||||
|
||||
Converts a date from its ISO-8601 representation.
|
||||
|
||||
- Use `datetime.datetime.fromisoformat()` to convert the given ISO-8601 date to a `datetime.datetime` object.
|
||||
|
||||
```py
|
||||
from datetime import datetime
|
||||
|
||||
def from_iso_date(d):
|
||||
return datetime.fromisoformat(d)
|
||||
```
|
||||
|
||||
```py
|
||||
from_iso_date('2020-10-28T12:30:59.000000') # 2020-10-28 12:30:59
|
||||
```
|
||||
23
python/snippets/gcd.md
Normal file
23
python/snippets/gcd.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Greatest common divisor
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: digital-nomad-12
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Calculates the greatest common divisor of a list of numbers.
|
||||
|
||||
- Use `functools.reduce()` and `math.gcd()` over the given list.
|
||||
|
||||
```py
|
||||
from functools import reduce
|
||||
from math import gcd as _gcd
|
||||
|
||||
def gcd(numbers):
|
||||
return reduce(_gcd, numbers)
|
||||
```
|
||||
|
||||
```py
|
||||
gcd([8, 36, 28]) # 4
|
||||
```
|
||||
29
python/snippets/geometric-progression.md
Normal file
29
python/snippets/geometric-progression.md
Normal file
@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Geometric progression
|
||||
type: snippet
|
||||
tags: [math,list]
|
||||
cover: kettle-laptop
|
||||
excerpt: Initializes a list containing the numbers in the specified geometric progression range.
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
|
||||
|
||||
- Use `range()`, `math.log()` and `math.floor()` and a list comprehension to create a list of the appropriate length, applying the step for each element.
|
||||
- Returns an error if `step` equals `1`.
|
||||
- Omit the second argument, `start`, to use a default value of `1`.
|
||||
- Omit the third argument, `step`, to use a default value of `2`.
|
||||
|
||||
```py
|
||||
from math import floor, log
|
||||
|
||||
def geometric_progression(end, start=1, step=2):
|
||||
return [start * step ** i for i in range(floor(log(end / start)
|
||||
/ log(step)) + 1)]
|
||||
```
|
||||
|
||||
```py
|
||||
geometric_progression(256) # [1, 2, 4, 8, 16, 32, 64, 128, 256]
|
||||
geometric_progression(256, 3) # [3, 6, 12, 24, 48, 96, 192]
|
||||
geometric_progression(256, 1, 4) # [1, 4, 16, 64, 256]
|
||||
```
|
||||
34
python/snippets/get.md
Normal file
34
python/snippets/get.md
Normal file
@ -0,0 +1,34 @@
|
||||
---
|
||||
title: Get nested value
|
||||
type: snippet
|
||||
tags: [dictionary,list]
|
||||
cover: digital-nomad-2
|
||||
dateModified: 2020-10-28T12:21:39+02:00
|
||||
---
|
||||
|
||||
Retrieves the value of the nested key indicated by the given selector list from a dictionary or list.
|
||||
|
||||
- Use `functools.reduce()` to iterate over the `selectors` list.
|
||||
- Apply `operator.getitem()` for each key in `selectors`, retrieving the value to be used as the iteratee for the next iteration.
|
||||
|
||||
```py
|
||||
from functools import reduce
|
||||
from operator import getitem
|
||||
|
||||
def get(d, selectors):
|
||||
return reduce(getitem, selectors, d)
|
||||
```
|
||||
|
||||
```py
|
||||
users = {
|
||||
'freddy': {
|
||||
'name': {
|
||||
'first': 'fred',
|
||||
'last': 'smith'
|
||||
},
|
||||
'postIds': [1, 2, 3]
|
||||
}
|
||||
}
|
||||
get(users, ['freddy', 'name', 'last']) # 'smith'
|
||||
get(users, ['freddy', 'postIds', 1]) # 2
|
||||
```
|
||||
30
python/snippets/group-by.md
Normal file
30
python/snippets/group-by.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Group list elements
|
||||
type: snippet
|
||||
tags: [list,dictionary]
|
||||
cover: body-of-water
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Groups the elements of a list based on the given function.
|
||||
|
||||
- Use `collections.defaultdict` to initialize a dictionary.
|
||||
- Use `fn` in combination with a `for` loop and `dict.append()` to populate the dictionary.
|
||||
- Use `dict()` to convert it to a regular dictionary.
|
||||
|
||||
```py
|
||||
from collections import defaultdict
|
||||
|
||||
def group_by(lst, fn):
|
||||
d = defaultdict(list)
|
||||
for el in lst:
|
||||
d[fn(el)].append(el)
|
||||
return dict(d)
|
||||
```
|
||||
|
||||
```py
|
||||
from math import floor
|
||||
|
||||
group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
|
||||
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}
|
||||
```
|
||||
22
python/snippets/hamming-distance.md
Normal file
22
python/snippets/hamming-distance.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Hamming distance
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: tulips-and-reeds
|
||||
dateModified: 2021-02-18T14:22:25+02:00
|
||||
---
|
||||
|
||||
Calculates the Hamming distance between two values.
|
||||
|
||||
- Use the XOR operator (`^`) to find the bit difference between the two numbers.
|
||||
- Use `bin()` to convert the result to a binary string.
|
||||
- Convert the string to a list and use `count()` of `str` class to count and return the number of `1`s in it.
|
||||
|
||||
```py
|
||||
def hamming_distance(a, b):
|
||||
return bin(a ^ b).count('1')
|
||||
```
|
||||
|
||||
```py
|
||||
hamming_distance(2, 3) # 1
|
||||
```
|
||||
23
python/snippets/has-duplicates.md
Normal file
23
python/snippets/has-duplicates.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Check for duplicates in list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: jars-on-shelf-2
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if there are duplicate values in a flat list.
|
||||
|
||||
- Use `set()` on the given list to remove duplicates, compare its length with the length of the list.
|
||||
|
||||
```py
|
||||
def has_duplicates(lst):
|
||||
return len(lst) != len(set(lst))
|
||||
```
|
||||
|
||||
```py
|
||||
x = [1, 2, 3, 4, 5, 5]
|
||||
y = [1, 2, 3, 4, 5]
|
||||
has_duplicates(x) # True
|
||||
has_duplicates(y) # False
|
||||
```
|
||||
25
python/snippets/have-same-contents.md
Normal file
25
python/snippets/have-same-contents.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Check lists have same contents
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: racoon
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if two lists contain the same elements regardless of order.
|
||||
|
||||
- Use `set()` on the combination of both lists to find the unique values.
|
||||
- Iterate over them with a `for` loop comparing the `count()` of each unique value in each list.
|
||||
- Return `False` if the counts do not match for any element, `True` otherwise.
|
||||
|
||||
```py
|
||||
def have_same_contents(a, b):
|
||||
for v in set(a + b):
|
||||
if a.count(v) != b.count(v):
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
```py
|
||||
have_same_contents([1, 2, 4], [2, 4, 1]) # True
|
||||
```
|
||||
20
python/snippets/head.md
Normal file
20
python/snippets/head.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: List head
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: purple-laptop
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Returns the head of a list.
|
||||
|
||||
- Use `lst[0]` to return the first element of the passed list.
|
||||
|
||||
```py
|
||||
def head(lst):
|
||||
return lst[0]
|
||||
```
|
||||
|
||||
```py
|
||||
head([1, 2, 3]) # 1
|
||||
```
|
||||
21
python/snippets/hex-to-rgb.md
Normal file
21
python/snippets/hex-to-rgb.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Hex to RGB
|
||||
type: snippet
|
||||
tags: [string,math]
|
||||
cover: sleepy-cat
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.
|
||||
|
||||
- Use a list comprehension in combination with `int()` and list slice notation to get the RGB components from the hexadecimal string.
|
||||
- Use `tuple()` to convert the resulting list to a tuple.
|
||||
|
||||
```py
|
||||
def hex_to_rgb(hex):
|
||||
return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
|
||||
```
|
||||
|
||||
```py
|
||||
hex_to_rgb('FFA501') # (255, 165, 1)
|
||||
```
|
||||
24
python/snippets/in-range.md
Normal file
24
python/snippets/in-range.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Number in range
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: pineapple-on-green
|
||||
dateModified: 2020-09-15T16:13:06+03:00
|
||||
---
|
||||
|
||||
Checks if the given number falls within the given range.
|
||||
|
||||
- Use arithmetic comparison to check if the given number is in the specified range.
|
||||
- If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.
|
||||
|
||||
```py
|
||||
def in_range(n, start, end = 0):
|
||||
return start <= n <= end if end >= start else end <= n <= start
|
||||
```
|
||||
|
||||
```py
|
||||
in_range(3, 2, 5) # True
|
||||
in_range(3, 4) # True
|
||||
in_range(2, 3, 5) # False
|
||||
in_range(3, 2) # False
|
||||
```
|
||||
25
python/snippets/includes-all.md
Normal file
25
python/snippets/includes-all.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: List includes all values
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: switzerland-night
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if all the elements in `values` are included in `lst`.
|
||||
|
||||
- Check if every value in `values` is contained in `lst` using a `for` loop.
|
||||
- Return `False` if any one value is not found, `True` otherwise.
|
||||
|
||||
```py
|
||||
def includes_all(lst, values):
|
||||
for v in values:
|
||||
if v not in lst:
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
```py
|
||||
includes_all([1, 2, 3, 4], [1, 4]) # True
|
||||
includes_all([1, 2, 3, 4], [1, 5]) # False
|
||||
```
|
||||
25
python/snippets/includes-any.md
Normal file
25
python/snippets/includes-any.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: List includes any values
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: forest-balcony
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if any element in `values` is included in `lst`.
|
||||
|
||||
- Check if any value in `values` is contained in `lst` using a `for` loop.
|
||||
- Return `True` if any one value is found, `False` otherwise.
|
||||
|
||||
```py
|
||||
def includes_any(lst, values):
|
||||
for v in values:
|
||||
if v in lst:
|
||||
return True
|
||||
return False
|
||||
```
|
||||
|
||||
```py
|
||||
includes_any([1, 2, 3, 4], [2, 9]) # True
|
||||
includes_any([1, 2, 3, 4], [8, 9]) # False
|
||||
```
|
||||
21
python/snippets/index-of-all.md
Normal file
21
python/snippets/index-of-all.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: All indexes of value
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: purple-flower-bunch
|
||||
dateModified: 2020-10-11T13:45:19+03:00
|
||||
---
|
||||
|
||||
Returns a list of indexes of all the occurrences of an element in a list.
|
||||
|
||||
- Use `enumerate()` and a list comprehension to check each element for equality with `value` and adding `i` to the result.
|
||||
|
||||
```py
|
||||
def index_of_all(lst, value):
|
||||
return [i for i, x in enumerate(lst) if x == value]
|
||||
```
|
||||
|
||||
```py
|
||||
index_of_all([1, 2, 1, 4, 5, 1], 1) # [0, 2, 5]
|
||||
index_of_all([1, 2, 3, 4], 6) # []
|
||||
```
|
||||
20
python/snippets/initial.md
Normal file
20
python/snippets/initial.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: List without last element
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: pop-of-green
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Returns all the elements of a list except the last one.
|
||||
|
||||
- Use `lst[:-1]` to return all but the last element of the list.
|
||||
|
||||
```py
|
||||
def initial(lst):
|
||||
return lst[:-1]
|
||||
```
|
||||
|
||||
```py
|
||||
initial([1, 2, 3]) # [1, 2]
|
||||
```
|
||||
21
python/snippets/initialize-2-d-list.md
Normal file
21
python/snippets/initialize-2-d-list.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Initialize 2D list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: succulent-7
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Initializes a 2D list of given width and height and value.
|
||||
|
||||
- Use a list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`.
|
||||
- Omit the last argument, `val`, to set the default value to `None`.
|
||||
|
||||
```py
|
||||
def initialize_2d_list(w, h, val = None):
|
||||
return [[val for x in range(w)] for y in range(h)]
|
||||
```
|
||||
|
||||
```py
|
||||
initialize_2d_list(2, 2, 0) # [[0, 0], [0, 0]]
|
||||
```
|
||||
24
python/snippets/initialize-list-with-range.md
Normal file
24
python/snippets/initialize-list-with-range.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Initialize list with range
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: succulent-3
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.
|
||||
|
||||
- Use `list()` and `range()` to generate a list of the appropriate length, filled with the desired values in the given range.
|
||||
- Omit `start` to use the default value of `0`.
|
||||
- Omit `step` to use the default value of `1`.
|
||||
|
||||
```py
|
||||
def initialize_list_with_range(end, start = 0, step = 1):
|
||||
return list(range(start, end + 1, step))
|
||||
```
|
||||
|
||||
```py
|
||||
initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]
|
||||
initialize_list_with_range(7, 3) # [3, 4, 5, 6, 7]
|
||||
initialize_list_with_range(9, 0, 2) # [0, 2, 4, 6, 8]
|
||||
```
|
||||
21
python/snippets/initialize-list-with-values.md
Normal file
21
python/snippets/initialize-list-with-values.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Initialize list with values
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: dog-waiting
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Initializes and fills a list with the specified value.
|
||||
|
||||
- Use a list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values.
|
||||
- Omit `val` to use the default value of `0`.
|
||||
|
||||
```py
|
||||
def initialize_list_with_values(n, val = 0):
|
||||
return [val for x in range(n)]
|
||||
```
|
||||
|
||||
```py
|
||||
initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]
|
||||
```
|
||||
24
python/snippets/intersection-by.md
Normal file
24
python/snippets/intersection-by.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: List intersection based on function
|
||||
type: snippet
|
||||
tags: [list,function]
|
||||
cover: duck-plants
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Returns a list of elements that exist in both lists, after applying the provided function to each list element of both.
|
||||
|
||||
- Create a `set`, using `map()` to apply `fn` to each element in `b`.
|
||||
- Use a list comprehension in combination with `fn` on `a` to only keep values contained in both lists.
|
||||
|
||||
```py
|
||||
def intersection_by(a, b, fn):
|
||||
_b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) in _b]
|
||||
```
|
||||
|
||||
```py
|
||||
from math import floor
|
||||
|
||||
intersection_by([2.1, 1.2], [2.3, 3.4], floor) # [2.1]
|
||||
```
|
||||
22
python/snippets/intersection.md
Normal file
22
python/snippets/intersection.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: List intersection
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: wooden-bowl
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Returns a list of elements that exist in both lists.
|
||||
|
||||
- Create a `set` from `a` and `b`.
|
||||
- Use the built-in set operator `&` to only keep values contained in both sets, then transform the `set` back into a `list`.
|
||||
|
||||
```py
|
||||
def intersection(a, b):
|
||||
_a, _b = set(a), set(b)
|
||||
return list(_a & _b)
|
||||
```
|
||||
|
||||
```py
|
||||
intersection([1, 2, 3], [4, 3, 2]) # [2, 3]
|
||||
```
|
||||
25
python/snippets/invert-dictionary.md
Normal file
25
python/snippets/invert-dictionary.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Invert dictionary
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: rustic-cup
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Inverts a dictionary with unique hashable values.
|
||||
|
||||
- Use `dictionary.items()` in combination with a list comprehension to create a new dictionary with the values and keys inverted.
|
||||
|
||||
```py
|
||||
def invert_dictionary(obj):
|
||||
return { value: key for key, value in obj.items() }
|
||||
```
|
||||
|
||||
```py
|
||||
ages = {
|
||||
'Peter': 10,
|
||||
'Isabel': 11,
|
||||
'Anna': 9,
|
||||
}
|
||||
invert_dictionary(ages) # { 10: 'Peter', 11: 'Isabel', 9: 'Anna' }
|
||||
```
|
||||
27
python/snippets/is-anagram.md
Normal file
27
python/snippets/is-anagram.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: String is anagram
|
||||
type: snippet
|
||||
tags: [string]
|
||||
cover: digital-nomad-8
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
|
||||
|
||||
- Use `str.isalnum()` to filter out non-alphanumeric characters, `str.lower()` to transform each character to lowercase.
|
||||
- Use `collections.Counter` to count the resulting characters for each string and compare the results.
|
||||
|
||||
```py
|
||||
from collections import Counter
|
||||
|
||||
def is_anagram(s1, s2):
|
||||
return Counter(
|
||||
c.lower() for c in s1 if c.isalnum()
|
||||
) == Counter(
|
||||
c.lower() for c in s2 if c.isalnum()
|
||||
)
|
||||
```
|
||||
|
||||
```py
|
||||
is_anagram('#anagram', 'Nag a ram!') # True
|
||||
```
|
||||
24
python/snippets/is-contained-in.md
Normal file
24
python/snippets/is-contained-in.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: List is contained in other list
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: tropical-bike
|
||||
dateModified: 2021-01-07T23:30:28+02:00
|
||||
---
|
||||
|
||||
Checks if the elements of the first list are contained in the second one regardless of order.
|
||||
|
||||
- Use `count()` to check if any value in `a` has more occurrences than it has in `b`.
|
||||
- Return `False` if any such value is found, `True` otherwise.
|
||||
|
||||
```py
|
||||
def is_contained_in(a, b):
|
||||
for v in set(a):
|
||||
if a.count(v) > b.count(v):
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
```py
|
||||
is_contained_in([1, 4], [2, 4, 1]) # True
|
||||
```
|
||||
21
python/snippets/is-divisible.md
Normal file
21
python/snippets/is-divisible.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Number is divisible
|
||||
type: snippet
|
||||
tags: [math]
|
||||
unlisted: true
|
||||
cover: interior-9
|
||||
dateModified: 2021-01-04T12:47:04+02:00
|
||||
---
|
||||
|
||||
Checks if the first numeric argument is divisible by the second one.
|
||||
|
||||
- Use the modulo operator (`%`) to check if the remainder is equal to `0`.
|
||||
|
||||
```py
|
||||
def is_divisible(dividend, divisor):
|
||||
return dividend % divisor == 0
|
||||
```
|
||||
|
||||
```py
|
||||
is_divisible(6, 3) # True
|
||||
```
|
||||
30
python/snippets/is-empty.md
Normal file
30
python/snippets/is-empty.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Collection is empty
|
||||
type: snippet
|
||||
tags: [list,dictionary,string]
|
||||
author: chalarangelo
|
||||
cover: salad-1
|
||||
dateModified: 2023-01-12T05:00:00-04:00
|
||||
---
|
||||
|
||||
Checks if the a value is an empty sequence or collection.
|
||||
|
||||
- Use `not` to test the truth value of the provided sequence or collection.
|
||||
|
||||
```py
|
||||
def is_empty(val):
|
||||
return not val
|
||||
```
|
||||
|
||||
```py
|
||||
is_empty([]) # True
|
||||
is_empty({}) # True
|
||||
is_empty('') # True
|
||||
is_empty(set()) # True
|
||||
is_empty(range(0)) # True
|
||||
is_empty([1, 2]) # False
|
||||
is_empty({ 'a': 1, 'b': 2 }) # False
|
||||
is_empty('text') # False
|
||||
is_empty(set([1, 2])) # False
|
||||
is_empty(range(2)) # False
|
||||
```
|
||||
22
python/snippets/is-even.md
Normal file
22
python/snippets/is-even.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Number is even
|
||||
type: snippet
|
||||
tags: [math]
|
||||
unlisted: true
|
||||
cover: interior-3
|
||||
dateModified: 2021-01-04T12:47:04+02:00
|
||||
---
|
||||
|
||||
Checks if the given number is even.
|
||||
|
||||
- Check whether a number is odd or even using the modulo (`%`) operator.
|
||||
- Return `True` if the number is even, `False` if the number is odd.
|
||||
|
||||
```py
|
||||
def is_even(num):
|
||||
return num % 2 == 0
|
||||
```
|
||||
|
||||
```py
|
||||
is_even(3) # False
|
||||
```
|
||||
22
python/snippets/is-odd.md
Normal file
22
python/snippets/is-odd.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Number is odd
|
||||
type: snippet
|
||||
tags: [math]
|
||||
unlisted: true
|
||||
cover: interior-6
|
||||
dateModified: 2021-01-04T12:47:04+02:00
|
||||
---
|
||||
|
||||
Checks if the given number is odd.
|
||||
|
||||
- Checks whether a number is even or odd using the modulo (`%`) operator.
|
||||
- Returns `True` if the number is odd, `False` if the number is even.
|
||||
|
||||
```py
|
||||
def is_odd(num):
|
||||
return num % 2 != 0
|
||||
```
|
||||
|
||||
```py
|
||||
is_odd(3) # True
|
||||
```
|
||||
26
python/snippets/is-prime.md
Normal file
26
python/snippets/is-prime.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Number is prime
|
||||
type: snippet
|
||||
tags: [math]
|
||||
cover: carrots
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if the provided integer is a prime number.
|
||||
|
||||
- Return `False` if the number is `0`, `1`, a negative number or a multiple of `2`.
|
||||
- Use `all()` and `range()` to check numbers from `3` to the square root of the given number.
|
||||
- Return `True` if none divides the given number, `False` otherwise.
|
||||
|
||||
```py
|
||||
from math import sqrt
|
||||
|
||||
def is_prime(n):
|
||||
if n <= 1 or (n % 2 == 0 and n > 2):
|
||||
return False
|
||||
return all(n % i for i in range(3, int(sqrt(n)) + 1, 2))
|
||||
```
|
||||
|
||||
```py
|
||||
is_prime(11) # True
|
||||
```
|
||||
27
python/snippets/is-weekday.md
Normal file
27
python/snippets/is-weekday.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Date is weekday
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: succulent-4
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if the given date is a weekday.
|
||||
|
||||
- Use `datetime.datetime.weekday()` to get the day of the week as an integer.
|
||||
- Check if the day of the week is less than or equal to `4`.
|
||||
- Omit the second argument, `d`, to use a default value of `datetime.today()`.
|
||||
|
||||
```py
|
||||
from datetime import datetime
|
||||
|
||||
def is_weekday(d = datetime.today()):
|
||||
return d.weekday() <= 4
|
||||
```
|
||||
|
||||
```py
|
||||
from datetime import date
|
||||
|
||||
is_weekday(date(2020, 10, 25)) # False
|
||||
is_weekday(date(2020, 10, 28)) # True
|
||||
```
|
||||
27
python/snippets/is-weekend.md
Normal file
27
python/snippets/is-weekend.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Date is weekend
|
||||
type: snippet
|
||||
tags: [date]
|
||||
cover: two-lighthouses
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Checks if the given date is a weekend.
|
||||
|
||||
- Use `datetime.datetime.weekday()` to get the day of the week as an integer.
|
||||
- Check if the day of the week is greater than `4`.
|
||||
- Omit the second argument, `d`, to use a default value of `datetime.today()`.
|
||||
|
||||
```py
|
||||
from datetime import datetime
|
||||
|
||||
def is_weekend(d = datetime.today()):
|
||||
return d.weekday() > 4
|
||||
```
|
||||
|
||||
```py
|
||||
from datetime import date
|
||||
|
||||
is_weekend(date(2020, 10, 25)) # True
|
||||
is_weekend(date(2020, 10, 28)) # False
|
||||
```
|
||||
31
python/snippets/kebab.md
Normal file
31
python/snippets/kebab.md
Normal file
@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Kebabcase string
|
||||
type: snippet
|
||||
tags: [string,regexp]
|
||||
cover: mask-quiet
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Converts a string to kebab case.
|
||||
|
||||
- Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`.
|
||||
- Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them.
|
||||
- Finally, use `str.join()` to combine all word using `-` as the separator.
|
||||
|
||||
```py
|
||||
from re import sub
|
||||
|
||||
def kebab(s):
|
||||
return '-'.join(
|
||||
sub(r"(\s|_|-)+"," ",
|
||||
sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
|
||||
lambda mo: ' ' + mo.group(0).lower(), s)).split())
|
||||
```
|
||||
|
||||
```py
|
||||
kebab('camelCase') # 'camel-case'
|
||||
kebab('some text') # 'some-text'
|
||||
kebab('some-mixed_string With spaces_underscores-and-hyphens')
|
||||
# 'some-mixed-string-with-spaces-underscores-and-hyphens'
|
||||
kebab('AllThe-small Things') # 'all-the-small-things'
|
||||
```
|
||||
21
python/snippets/key-in-dict.md
Normal file
21
python/snippets/key-in-dict.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Key in dictionary
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: rocky-mountains
|
||||
dateModified: 2020-10-16T21:30:49+03:00
|
||||
---
|
||||
|
||||
Checks if the given key exists in a dictionary.
|
||||
|
||||
- Use the `in` operator to check if `d` contains `key`.
|
||||
|
||||
```py
|
||||
def key_in_dict(d, key):
|
||||
return (key in d)
|
||||
```
|
||||
|
||||
```py
|
||||
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
|
||||
key_in_dict(d, 'three') # True
|
||||
```
|
||||
20
python/snippets/key-of-max.md
Normal file
20
python/snippets/key-of-max.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Key of max value
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: succulent-7
|
||||
dateModified: 2021-01-07T23:15:48+02:00
|
||||
---
|
||||
|
||||
Finds the key of the maximum value in a dictionary.
|
||||
|
||||
- Use `max()` with the `key` parameter set to `dict.get()` to find and return the key of the maximum value in the given dictionary.
|
||||
|
||||
```py
|
||||
def key_of_max(d):
|
||||
return max(d, key = d.get)
|
||||
```
|
||||
|
||||
```py
|
||||
key_of_max({'a':4, 'b':0, 'c':13}) # c
|
||||
```
|
||||
20
python/snippets/key-of-min.md
Normal file
20
python/snippets/key-of-min.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Key of min value
|
||||
type: snippet
|
||||
tags: [dictionary]
|
||||
cover: goat-wooden-cottage
|
||||
dateModified: 2021-01-07T23:15:48+02:00
|
||||
---
|
||||
|
||||
Finds the key of the minimum value in a dictionary.
|
||||
|
||||
- Use `min()` with the `key` parameter set to `dict.get()` to find and return the key of the minimum value in the given dictionary.
|
||||
|
||||
```py
|
||||
def key_of_min(d):
|
||||
return min(d, key = d.get)
|
||||
```
|
||||
|
||||
```py
|
||||
key_of_min({'a':4, 'b':0, 'c':13}) # b
|
||||
```
|
||||
26
python/snippets/keys-only.md
Normal file
26
python/snippets/keys-only.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Dictionary keys
|
||||
type: snippet
|
||||
tags: [dictionary,list]
|
||||
cover: succulent-5
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Creates a flat list of all the keys in a flat dictionary.
|
||||
|
||||
- Use `dict.keys()` to return the keys in the given dictionary.
|
||||
- Return a `list()` of the previous result.
|
||||
|
||||
```py
|
||||
def keys_only(flat_dict):
|
||||
return list(flat_dict.keys())
|
||||
```
|
||||
|
||||
```py
|
||||
ages = {
|
||||
'Peter': 10,
|
||||
'Isabel': 11,
|
||||
'Anna': 9,
|
||||
}
|
||||
keys_only(ages) # ['Peter', 'Isabel', 'Anna']
|
||||
```
|
||||
21
python/snippets/km-to-miles.md
Normal file
21
python/snippets/km-to-miles.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Km to miles
|
||||
type: snippet
|
||||
tags: [math]
|
||||
unlisted: true
|
||||
cover: interior-5
|
||||
dateModified: 2021-01-04T12:47:04+02:00
|
||||
---
|
||||
|
||||
Converts kilometers to miles.
|
||||
|
||||
- Follows the conversion formula `mi = km * 0.621371`.
|
||||
|
||||
```py
|
||||
def km_to_miles(km):
|
||||
return km * 0.621371
|
||||
```
|
||||
|
||||
```py
|
||||
km_to_miles(8.1) # 5.0331051
|
||||
```
|
||||
20
python/snippets/last.md
Normal file
20
python/snippets/last.md
Normal file
@ -0,0 +1,20 @@
|
||||
---
|
||||
title: Last list element
|
||||
type: snippet
|
||||
tags: [list]
|
||||
cover: lake-runner
|
||||
dateModified: 2020-11-02T19:28:05+02:00
|
||||
---
|
||||
|
||||
Returns the last element in a list.
|
||||
|
||||
- Use `lst[-1]` to return the last element of the passed list.
|
||||
|
||||
```py
|
||||
def last(lst):
|
||||
return lst[-1]
|
||||
```
|
||||
|
||||
```py
|
||||
last([1, 2, 3]) # 3
|
||||
```
|
||||
24
python/snippets/lcm.md
Normal file
24
python/snippets/lcm.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Least common multiple
|
||||
type: snippet
|
||||
tags: [math,list]
|
||||
cover: fruit-feast
|
||||
dateModified: 2020-11-02T19:31:15+02:00
|
||||
---
|
||||
|
||||
Returns the least common multiple of a list of numbers.
|
||||
|
||||
- Use `functools.reduce()`, `math.gcd()` and `lcm(x, y) = x * y / gcd(x, y)` over the given list.
|
||||
|
||||
```py
|
||||
from functools import reduce
|
||||
from math import gcd
|
||||
|
||||
def lcm(numbers):
|
||||
return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers)
|
||||
```
|
||||
|
||||
```py
|
||||
lcm([12, 7]) # 84
|
||||
lcm([1, 3, 4, 5]) # 60
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user