Apply new format to snippets and template

This commit is contained in:
Angelos Chalaris
2020-09-15 16:13:06 +03:00
parent 39d3711994
commit a9aeadad64
117 changed files with 170 additions and 175 deletions

View File

@ -5,7 +5,9 @@ tags: utility,intermediate
Explain briefly what the snippet does. Explain briefly what the snippet does.
Explain briefly how the snippet works. - Explain briefly how the snippet works.
- Use bullet points for your snippet's explanation.
- Try to explain everything briefly but clearly.
```py ```py
def function_name(args): def function_name(args):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Checks if all elements in a list are equal. Checks if all elements in a list are equal.
Use `[1:]` and `[:-1]` to compare all the values in the given list. - Use `[1:]` and `[:-1]` to compare all the values in the given list.
```py ```py
def all_equal(lst): def all_equal(lst):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns `True` if all the values in a list are unique, `False` otherwise. Returns `True` if all the values in a list are unique, `False` otherwise.
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 remove duplicates, use `len()` to compare its length with the length of the list.
```py ```py
def all_unique(lst): def all_unique(lst):

View File

@ -5,7 +5,7 @@ tags: math,beginner
Returns a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit. Returns 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 ```py
def find_multiples(n, lim): def find_multiples(n, lim):

View File

@ -5,7 +5,7 @@ tags: math,list,beginner
Returns the average of two or more numbers. Returns 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(args)`.
```py ```py
def average(*args): def average(*args):

View File

@ -5,8 +5,8 @@ tags: math,list,function,intermediate
Returns the average of a list, after mapping each element to a value using the provided function. Returns 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 `map()` to map each element to the value returned by `fn`.
Use `sum()` to sum all of the mapped values, divide by `len(lst)`. - Use `sum()` to sum all of the mapped values, divide by `len(lst)`.
```py ```py
def average_by(lst, fn=lambda x: x): def average_by(lst, fn=lambda x: x):

View File

@ -6,7 +6,7 @@ tags: list,intermediate
Splits values into two groups. 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. 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.
Use list comprehension and `enumerate()` to add elements to groups, based on `filter`. - Use list comprehension and `enumerate()` to add elements to groups, based on `filter`.
```py ```py
def bifurcate(lst, filter): def bifurcate(lst, filter):

View File

@ -6,7 +6,7 @@ tags: list,function,intermediate
Splits values into two groups according to a function, which specifies which group an element in the input list belongs to. 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. If the function returns `True`, the element belongs to the first group; otherwise, it belongs to the second group.
Use list comprehension to add elements to groups, based on `fn`. - Use list comprehension to add elements to groups, based on `fn`.
```py ```py
def bifurcate_by(lst, fn): def bifurcate_by(lst, fn):

View File

@ -5,7 +5,7 @@ tags: string, beginner
Returns the length of a string in bytes. Returns the length of a string in bytes.
Use `s.encode('utf-8')` to encode the given string and return its length. - Use `s.encode('utf-8')` to encode the given string and return its length.
```py ```py
def byte_size(s): def byte_size(s):

View File

@ -5,9 +5,9 @@ tags: string,regexp,intermediate
Converts a string to camelcase. Converts a string to camelcase.
Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`. - 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. - Use `title()` to capitalize the first letter of each word convert the rest to lowercase.
Finally, use `replace()` to remove spaces between words. - Finally, use `replace()` to remove spaces between words.
```py ```py
from re import sub from re import sub

View File

@ -5,8 +5,8 @@ tags: string,intermediate
Capitalizes the first letter of a string. Capitalizes the first letter of a string.
Capitalize the first letter of the string and then add it with rest of the string. - Capitalize the first letter of the string and then add it with rest of the string.
Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase. - Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase.
```py ```py
def capitalize(s, lower_rest=False): def capitalize(s, lower_rest=False):

View File

@ -5,7 +5,7 @@ tags: string,beginner
Capitalizes the first letter of every word in a string. Capitalizes the first letter of every word in a string.
Use `s.title()` to capitalize first letter of every word in the string. - Use `s.title()` to capitalize first letter of every word in the string.
```py ```py
def capitalize_every_word(s): def capitalize_every_word(s):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Casts the provided value as a list if it's not one. 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 and return it by using `list()` or encapsulated in a list accordingly.
```py ```py
def cast_list(val): def cast_list(val):

View File

@ -5,7 +5,7 @@ tags: math,beginner
Converts Celsius to Fahrenheit. Converts Celsius to Fahrenheit.
Use the formula `fahrenheit = (celsius * 1.8) + 32` to convert from Celsius to Fahrenheit. - Use the formula `fahrenheit = (celsius * 1.8) + 32` to convert from Celsius to Fahrenheit.
```py ```py
def celsius_to_fahrenheit(celsius): def celsius_to_fahrenheit(celsius):

View File

@ -5,7 +5,7 @@ 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. 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.
Return a `lambda` function that takes an object and applies the predicate function, `fn` to the specified property. - Return a `lambda` function that takes an object and applies the predicate function, `fn` to the specified property.
```py ```py
def check_prop(fn, prop): def check_prop(fn, prop):

View File

@ -5,9 +5,9 @@ tags: list,intermediate
Chunks a list into smaller lists of a specified size. Chunks a list into smaller lists of a specified size.
Use `list()` and `range()` to create a list of the desired `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. - Use `map()` on the list and fill it with splices of the given list.
Finally, return the created list. - Finally, return the created list.
```py ```py
from math import ceil from math import ceil

View File

@ -5,8 +5,8 @@ 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 `a` and `b`.
If `num` falls within the range, return `num`. - If `num` falls within the range, return `num`.
Otherwise, return the nearest number in the range. - Otherwise, return the nearest number in the range.
```py ```py
def clamp_number(num,a,b): def clamp_number(num,a,b):

View File

@ -5,7 +5,7 @@ tags: dictionary,intermediate
Inverts a dictionary with non-unique hashable values. Inverts a dictionary with non-unique hashable values.
Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `dictionary.setdefault()`, `list()` and `append()` to create a list for each one. - Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `dictionary.setdefault()`, `list()` and `append()` to create a list for each one.
```py ```py
def collect_dictionary(obj): def collect_dictionary(obj):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Removes falsey values from a list. Removes falsey values from a list.
Use `filter()` to filter out falsey values (`False`, `None`, `0`, and `""`). - Use `filter()` to filter out falsey values (`False`, `None`, `0`, and `""`).
```py ```py
def compact(lst): def compact(lst):

View File

@ -5,8 +5,8 @@ tags: function,intermediate
Performs right-to-left function composition. Performs right-to-left function composition.
Use `functools.reduce()` to perform 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. - The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
```py ```py
from functools import reduce from functools import reduce

View File

@ -5,8 +5,8 @@ tags: function,intermediate
Performs left-to-right function composition. Performs left-to-right function composition.
Use `functools.reduce()` to perform 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. - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
```py ```py
from functools import reduce from functools import reduce

View File

@ -5,8 +5,8 @@ tags: list,intermediate
Groups the elements of a list based on the given function and returns the count of elements in each group. Groups the elements of a list based on the given function and returns the count of elements in each group.
Use `map()` to map the values of the given list using the given function. - 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. - Iterate over the map and increase the element count each time it occurs.
```py ```py
def count_by(arr, fn=lambda x: x): def count_by(arr, fn=lambda x: x):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Counts the occurrences of a value in a list. Counts the occurrences of a value in a list.
Increment a counter for every item in the list that has the given value and is of the same type. - Increment a counter for every item in the list that has the given value and is of the same type.
```py ```py
def count_occurrences(lst, val): def count_occurrences(lst, val):

View File

@ -5,7 +5,7 @@ tags: function,intermediate
Curries a function. Curries a function.
Use `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied. - Use `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied.
```py ```py
from functools import partial from functools import partial

View File

@ -5,8 +5,8 @@ tags: string,intermediate
Decapitalizes the first letter of a string. Decapitalizes the first letter of a string.
Decapitalize the first letter of the string and then add it with rest of the string. - Decapitalize the first letter of the string and then add it with rest of the string.
Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase. - Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase.
```py ```py
def decapitalize(s, upper_rest=False): def decapitalize(s, upper_rest=False):

View File

@ -5,9 +5,9 @@ tags: list,recursion,intermediate
Deep flattens a list. Deep flattens a list.
Use recursion. - Use recursion.
Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable. - Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable.
If it is, apply `deep_flatten()` recursively, otherwise return `[lst]`. - If it is, apply `deep_flatten()` recursively, otherwise return `[lst]`.
```py ```py
from collections.abc import Iterable from collections.abc import Iterable

View File

@ -5,7 +5,7 @@ tags: math,beginner
Converts an angle from degrees to radians. Converts an angle from degrees to radians.
Use `math.pi` and the degrees to radians formula to convert the angle from degrees to radians. - Use `math.pi` and the degrees to radians formula to convert the angle from degrees to radians.
```py ```py
from math import pi from math import pi

View File

@ -5,7 +5,7 @@ tags: function,intermediate
Invokes the provided function after `ms` milliseconds. Invokes the provided function after `ms` milliseconds.
Use `time.sleep()` to delay the execution of `fn` by `ms / 1000` seconds. - Use `time.sleep()` to delay the execution of `fn` by `ms / 1000` seconds.
```py ```py
from time import sleep from time import sleep

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the difference between two iterables. Returns the difference between two iterables.
Create a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`. - Create a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`.
```py ```py
def difference(a, b): def difference(a, b):

View File

@ -5,7 +5,7 @@ tags: list,function,intermediate
Returns the difference between two lists, after applying the provided function to each list element of both. Returns the difference between two lists, after applying the provided function to each list element of both.
Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with `fn` on `a` to only keep values not contained in the previously created set, `_b`. - Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with `fn` on `a` to only keep values not contained in the previously created set, `_b`.
```py ```py
def difference_by(a, b, fn): def difference_by(a, b, fn):

View File

@ -5,7 +5,7 @@ tags: math,list,beginner
Converts a number to a list of digits. 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. - Use `map()` combined with `int` on the string representation of `n` and return a list from the result.
```py ```py
def digitize(n): def digitize(n):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns a list with `n` elements removed from the left. Returns a list with `n` elements removed from the left.
Use slice notation to remove the specified number of elements from the left. - Use slice notation to remove the specified number of elements from the left.
```py ```py
def drop(a, n = 1): def drop(a, n = 1):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns a list with `n` elements removed from the right. Returns a list with `n` elements removed from the right.
Use slice notation to remove the specified number of elements from the right. - Use slice notation to remove the specified number of elements from the right.
```py ```py
def drop_right(a, n = 1): def drop_right(a, n = 1):

View File

@ -5,7 +5,7 @@ tags: list,function,intermediate
Returns `True` if the provided function returns `True` for every element in the list, `False` otherwise. Returns `True` if the provided function returns `True` for every element in the list, `False` otherwise.
Use `all()` in combination with `map` and `fn` to check if `fn` returns `True` for all elements in the list. - Use `all()` in combination with `map` and `fn` to check if `fn` returns `True` for all elements in the list.
```py ```py
def every(lst, fn=lambda x: x): def every(lst, fn=lambda x: x):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns every nth element in a list. Returns every nth element in a list.
Use `[nth-1::nth]` to create a new list that contains every nth element of the given list. - Use `[nth-1::nth]` to create a new list that contains every nth element of the given list.
```py ```py
def every_nth(lst, nth): def every_nth(lst, nth):

View File

@ -5,10 +5,10 @@ tags: math,recursion,beginner
Calculates the factorial of a number. Calculates the factorial of a number.
Use recursion. - Use recursion.
If `num` is less than or equal to `1`, return `1`. - If `num` is less than or equal to `1`, return `1`.
Otherwise, return the product of `num` and the factorial of `num - 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. - Throws an exception if `num` is a negative or a floating point number.
```py ```py
def factorial(num): def factorial(num):

View File

@ -5,7 +5,7 @@ tags: math,beginner
Converts Fahrenheit to Celsius. Converts Fahrenheit to Celsius.
Use the formula `celsius = (fahrenheit - 32) / 1.8` to convert from Fahrenheit to Celsius. - Use the formula `celsius = (fahrenheit - 32) / 1.8` to convert from Fahrenheit to Celsius.
```py ```py
def fahrenheit_to_celsius(fahrenheit): def fahrenheit_to_celsius(fahrenheit):

View File

@ -5,8 +5,8 @@ tags: math,list,intermediate
Generates a list, containing the Fibonacci sequence, up until the nth term. 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`. - 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`. - If `n` is less or equal to `0`, return a list containing `0`.
```py ```py
def fibonacci(n): def fibonacci(n):

View File

@ -5,8 +5,8 @@ tags: list,beginner
Filters out the non-unique values in a list. Filters out the non-unique values in a list.
Use a `collections.Counter` to get the count of each value in the list. - Use a `collections.Counter` to get the count of each value in the list.
Use list comprehension to create a list containing only the unique values. - Use list comprehension to create a list containing only the unique values.
```py ```py
from collections import Counter from collections import Counter

View File

@ -5,8 +5,8 @@ tags: list,beginner
Filters out the unique values in a list. Filters out the unique values in a list.
Use a `collections.Counter` to get the count of each value in the list. - Use a `collections.Counter` to get the count of each value in the list.
Use list comprehension to create a list containing only the non-unique values. - Use list comprehension to create a list containing only the non-unique values.
```py ```py
from collections import Counter from collections import Counter

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the value of the first element in the provided list that satisfies the provided testing function. Returns the value of the first element in the provided list that satisfies the provided testing function.
Use list comprehension and `next()` to return the first element in `lst` for which `fn` returns `True`. - Use list comprehension and `next()` to return the first element in `lst` for which `fn` returns `True`.
```py ```py
def find(lst, fn): def find(lst, fn):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the index of the first element in the provided list that satisfies the provided testing function. Returns the index of the first element in the provided list that satisfies the provided testing function.
Use list comprehension, `enumerate()` and `next()` to return the index of the first element in `lst` for which `fn` returns `True`. - Use list comprehension, `enumerate()` and `next()` to return the index of the first element in `lst` for which `fn` returns `True`.
```py ```py
def find_index(lst, fn): def find_index(lst, fn):

View File

@ -5,7 +5,7 @@ tags: dictionary,intermediate
Returns the first key in the provided dictionary that has the given value. Returns 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`. - Use `dictionary.items()` and `next()` to return the first key that has a value equal to `val`.
```py ```py
def find_key(dict, val): def find_key(dict, val):

View File

@ -5,7 +5,7 @@ tags: dictionary,intermediate
Returns all keys in the provided dictionary that have the given value. Returns 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`. - Use `dictionary.items()`, a generator and `list()` to return all keys that have a value equal to `val`.
```py ```py
def find_keys(dict, val): def find_keys(dict, val):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the value of the last element in the provided list that satisfies the provided testing function. Returns the value of the last element in the provided list that satisfies the provided testing function.
Use list comprehension and `next()` to return the last element in `lst` for which `fn` returns `True`. - Use list comprehension and `next()` to return the last element in `lst` for which `fn` returns `True`.
```py ```py
def find_last(lst, fn): def find_last(lst, fn):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the index of the last element in the provided list that satisfies the provided testing function. Returns the index of the last element in the provided list that satisfies the provided testing function.
Use list comprehension, `enumerate()` and `next()` to return the index of the last element in `lst` for which `fn` returns `True`. - Use list comprehension, `enumerate()` and `next()` to return the index of the last element in `lst` for which `fn` returns `True`.
```py ```py
def find_last_index(lst, fn): def find_last_index(lst, fn):

View File

@ -5,8 +5,8 @@ tags: list,math,intermediate
Given a list, returns the items that are parity outliers. Given a list, returns the items that are parity outliers.
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 `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. - Use a list comprehension to find all elements that do not match the most common parity.
```py ```py
from collections import Counter from collections import Counter

View File

@ -5,7 +5,7 @@ tags: list,intermediate
Flattens a list of lists once. Flattens a list of lists once.
Use nested list comprehension to extract each value from sub-lists in order. - Use nested list comprehension to extract each value from sub-lists in order.
```py ```py
def flatten(lst): def flatten(lst):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Executes the provided function once for each list element. Executes the provided function once for each list element.
Use a `for` loop to execute `fn` for each element in `itr`. - Use a `for` loop to execute `fn` for each element in `itr`.
```py ```py
def for_each(itr, fn): def for_each(itr, fn):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Executes the provided function once for each list element, starting from the list's last element. 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. - Use a `for` loop in combination with slice notation to execute `fn` for each element in `itr`, starting from the last one.
```py ```py
def for_each_right(itr, fn): def for_each_right(itr, fn):

View File

@ -5,7 +5,7 @@ tags: list,intermediate
Returns a dictionary with the unique values of a list as keys and their frequencies as the values. Returns a dictionary with the unique values of a list as keys and their frequencies as the values.
Use a `for` loop to populate a dictionary, `f`, with the unique values in `lst` as keys, adding to existing keys every time the same value is encountered. - Use a `for` loop to populate a dictionary, `f`, with the unique values in `lst` as keys, adding to existing keys every time the same value is encountered.
```py ```py
from functools import reduce from functools import reduce

View File

@ -5,7 +5,7 @@ tags: math,beginner
Calculates the greatest common divisor of a list of numbers. Calculates the greatest common divisor of a list of numbers.
Use `functools.reduce()` and `math.gcd()` over the given list. - Use `functools.reduce()` and `math.gcd()` over the given list.
```py ```py
from functools import reduce from functools import reduce

View File

@ -5,8 +5,8 @@ tags: list,dictionary,intermediate
Groups the elements of a list based on the given function. Groups the elements of a list based on the given function.
Use `map()` and `fn` to map the values of the list to the keys of a dictionary. - Use `map()` and `fn` to map the values of the list to the keys of a dictionary.
Use list comprehension to map each element to the appropriate `key`. - Use list comprehension to map each element to the appropriate `key`.
```py ```py
def group_by(lst, fn): def group_by(lst, fn):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns `True` if there are duplicate values in a flat list, `False` otherwise. Returns `True` if there are duplicate values in a flat list, `False` otherwise.
Use `set()` on the given list to remove duplicates, compare its length with the length of the list. - Use `set()` on the given list to remove duplicates, compare its length with the length of the list.
```py ```py
def has_duplicates(lst): def has_duplicates(lst):

View File

@ -5,9 +5,9 @@ tags: list,intermediate
Returns `True` if two lists contain the same elements regardless of order, `False` otherwise. Returns `True` if two lists contain the same elements regardless of order, `False` otherwise.
Use `set()` on the combination of both lists to find the unique values. - 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. - 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. - Return `False` if the counts do not match for any element, `True` otherwise.
```py ```py
def have_same_contents(a, b): def have_same_contents(a, b):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the head of a list. Returns the head of a list.
Use `lst[0]` to return the first element of the passed list. - Use `lst[0]` to return the first element of the passed list.
```py ```py
def head(lst): def head(lst):

View File

@ -5,8 +5,8 @@ tags: string,math,intermediate
Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components. 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 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. - Use `tuple()` to convert the resulting list to a tuple.
```py ```py
def hex_to_rgb(hex): def hex_to_rgb(hex):

View File

@ -5,8 +5,8 @@ tags: math,beginner
Checks if the given number falls within the given range. Checks if the given number falls within the given range.
Use arithmetic comparison to check if the given number is in the specified 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`. - If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.
```py ```py
def in_range(n, start, end = 0): def in_range(n, start, end = 0):

View File

@ -5,7 +5,7 @@ tags: list,intermediate
Returns `True` if all the elements in `values` are included in `lst`, `False` otherwise. Returns `True` if all the elements in `values` are included in `lst`, `False` otherwise.
Check if every value in `values` is contained in `lst` using a `for` loop, returning `False` if any one value is not found, `True` otherwise. - Check if every value in `values` is contained in `lst` using a `for` loop, returning `False` if any one value is not found, `True` otherwise.
```py ```py
def includes_all(lst, values): def includes_all(lst, values):

View File

@ -5,7 +5,7 @@ tags: list,intermediate
Returns `True` if any element in `values` is included in `lst`, `False` otherwise. Returns `True` if any element in `values` is included in `lst`, `False` otherwise.
Check if any value in `values` is contained in `lst` using a `for` loop, returning `True` if any one value is found, `False` otherwise. - Check if any value in `values` is contained in `lst` using a `for` loop, returning `True` if any one value is found, `False` otherwise.
```py ```py
def includes_any(lst, values): def includes_any(lst, values):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns all the elements of a list except the last one. Returns all the elements of a list except the last one.
Use `lst[0:-1]` to return all but the last element of the list. - Use `lst[0:-1]` to return all but the last element of the list.
```py ```py
def initial(lst): def initial(lst):

View File

@ -5,8 +5,8 @@ tags: list,intermediate
Initializes a 2D list of given width and height and value. Initializes a 2D list of given width and height and value.
Use list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`. - Use list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`.
If `val` is not provided, default to `None`. - If `val` is not provided, default to `None`.
```py ```py
def initialize_2d_list(w,h, val = None): def initialize_2d_list(w,h, val = None):

View File

@ -5,9 +5,9 @@ tags: list,beginner
Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. 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. - 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 `start` to use the default value of `0`.
Omit `step` to use the default value of `1`. - Omit `step` to use the default value of `1`.
```py ```py
def initialize_list_with_range(end, start=0, step=1): def initialize_list_with_range(end, start=0, step=1):

View File

@ -5,8 +5,8 @@ tags: list,beginner
Initializes and fills a list with the specified value. Initializes and fills a list with the specified value.
Use list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values. - Use 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`. - Omit `val` to use the default value of `0`.
```py ```py
def initialize_list_with_values(n, val = 0): def initialize_list_with_values(n, val = 0):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns a list of elements that exist in both lists. Returns a list of elements that exist in both lists.
Create a `set` from `a` and `b`, then use the built-in set operator `&` to only keep values contained in both sets, then transform the `set` back into a `list`. - Create a `set` from `a` and `b`, then use the built-in set operator `&` to only keep values contained in both sets, then transform the `set` back into a `list`.
```py ```py
def intersection(a, b): def intersection(a, b):

View File

@ -5,7 +5,7 @@ tags: list,function,intermediate
Returns a list of elements that exist in both lists, after applying the provided function to each list element of both. Returns a list of elements that exist in both lists, after applying the provided function to each list element of both.
Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with `fn` on `a` to only keep values contained in both lists. - Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with `fn` on `a` to only keep values contained in both lists.
```py ```py
def intersection_by(a, b, fn): def intersection_by(a, b, fn):

View File

@ -5,7 +5,7 @@ tags: dictionary,intermediate
Inverts a dictionary with unique hashable values. 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. - Use `dictionary.items()` in combination with a list comprehension to create a new dictionary with the values and keys inverted.
```py ```py
def invert_dictionary(obj): def invert_dictionary(obj):

View File

@ -5,8 +5,8 @@ tags: string,intermediate
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters). Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
Use `isalnum()` to filter out non-alphanumeric characters, `lower()` to transform each character to lowercase. - Use `isalnum()` to filter out non-alphanumeric characters, `lower()` to transform each character to lowercase.
Use `collections.Counter` to count the resulting characters for each string and compare the results. - Use `collections.Counter` to count the resulting characters for each string and compare the results.
```py ```py
from collections import Counter from collections import Counter

View File

@ -5,9 +5,7 @@ tags: list,intermediate
Returns `True` if the elements of the first list are contained in the second one regardless of order, `False` otherwise. Returns `True` if the elements of the first list are contained in the second one regardless of order, `False` otherwise.
- Use `count()` to check if any value in `a` has more occurences than it has in `b`, returning `False` if any such value is found, `True` otherwise.
Use `count()` to check if any value in `a` has more occurences than it has in `b`, returning `False` if any such value is found, `True` otherwise.
```py ```py
def is_contained_in(a, b): def is_contained_in(a, b):

View File

@ -5,7 +5,7 @@ tags: math,beginner
Checks if the first numeric argument is divisible by the second one. 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`. - Use the modulo operator (`%`) to check if the remainder is equal to `0`.
```py ```py
def is_divisible(dividend, divisor): def is_divisible(dividend, divisor):

View File

@ -5,8 +5,8 @@ tags: math,beginner
Returns `True` if the given number is even, `False` otherwise. Returns `True` if the given number is even, `False` otherwise.
Checks whether a number is odd or even using the modulo (`%`) operator. - Checks whether a number is odd or even using the modulo (`%`) operator.
Returns `True` if the number is even, `False` if the number is odd. - Returns `True` if the number is even, `False` if the number is odd.
```py ```py
def is_even(num): def is_even(num):

View File

@ -5,8 +5,8 @@ tags: math,beginner
Returns `True` if the given number is odd, `False` otherwise. Returns `True` if the given number is odd, `False` otherwise.
Checks whether a number is even or odd using the modulo (`%`) operator. - 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. - Returns `True` if the number is odd, `False` if the number is even.
```py ```py
def is_odd(num): def is_odd(num):

View File

@ -5,7 +5,7 @@ tags: string,regexp,intermediate
Converts a string to kebab case. Converts a string to kebab case.
Break the string into words and combine them adding `-` as a separator, using a regexp. - Break the string into words and combine them adding `-` as a separator, using a regexp.
```py ```py
from re import sub from re import sub

View File

@ -5,8 +5,8 @@ tags: dictionary,list,beginner
Returns a flat list of all the keys in a flat dictionary. Returns a flat list of all the keys in a flat dictionary.
Use `dict.keys()` to return the keys in the given dictionary. - Use `dict.keys()` to return the keys in the given dictionary.
Return a `list()` of the previous result. - Return a `list()` of the previous result.
```py ```py
def keys_only(flat_dict): def keys_only(flat_dict):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the last element in a list. Returns the last element in a list.
use `lst[-1]` to return the last element of the passed list. - use `lst[-1]` to return the last element of the passed list.
```py ```py
def last(lst): def last(lst):

View File

@ -5,7 +5,7 @@ tags: math,list,recursion,advanced
Returns the least common multiple of a list of numbers. 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. - Use `functools.reduce()`, `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` over the given list.
```py ```py
from functools import reduce from functools import reduce

View File

@ -6,7 +6,7 @@ tags: list,string,intermediate
Takes any number of iterable objects or objects with a length property and returns the longest one. Takes any number of iterable objects or objects with a length property and returns the longest one.
If multiple objects have the same length, the first one will be returned. If multiple objects have the same length, the first one will be returned.
Use `max()` with `len` as the `key` to return the item with the greatest length. - Use `max()` with `len` as the `key` to return the item with the greatest length.
```py ```py
def longest_item(*args): def longest_item(*args):

View File

@ -5,7 +5,7 @@ tags: list,intermediate
Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.
Use a `for` loop to iterate over the list's values, assigning the values produced by `fn` to each key of the dictionary. - Use a `for` loop to iterate over the list's values, assigning the values produced by `fn` to each key of the dictionary.
```py ```py
def map_dictionary(itr, fn): def map_dictionary(itr, fn):

View File

@ -5,7 +5,7 @@ tags: dictionary,function,intermediate
Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value. Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.
Use `dict.keys()` to iterate over the dictionary's keys, assigning the values produced by `fn` to each key of a new dictionary. - Use `dict.keys()` to iterate over the dictionary's keys, assigning the values produced by `fn` to each key of a new dictionary.
```py ```py
def map_values(obj, fn): def map_values(obj, fn):

View File

@ -5,7 +5,7 @@ tags: math,list,function,beginner
Returns the maximum value of a list, after mapping each element to a value using the provided function. Returns the maximum value of a list, after mapping each element to a value using the provided function.
Use `map()` with `fn` to map each element to a value using the provided function, use `max()` to return the maximum value. - Use `map()` with `fn` to map each element to a value using the provided function, use `max()` to return the maximum value.
```py ```py
def max_by(lst, fn): def max_by(lst, fn):

View File

@ -5,13 +5,13 @@ tags: list,beginner
Returns the index of the element with the maximum value in a list. Returns the index of the element with the maximum value in a list.
Use `max()` and `list.index()` to get the maximum value in the list and return its index. - Use `max()` and `list.index()` to get the maximum value in the list and return its index.
```py ```py
def max_element_index(arr): def max_element_index(arr):
return arr.index(max(arr)) return arr.index(max(arr))
``` ```
```python ```py
max_element_index([5, 8, 9, 7, 10, 3, 0]) # 4 max_element_index([5, 8, 9, 7, 10, 3, 0]) # 4
``` ```

View File

@ -6,8 +6,8 @@ tags: list,math,beginner
Returns the `n` maximum elements from the provided list. Returns the `n` maximum elements from the provided list.
If `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order). If `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order).
Use `sorted()` to sort the list, `[:n]` to get the specified number of elements. - Use `sorted()` to sort the list, `[:n]` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element list. - Omit the second argument, `n`, to get a one-element list.
```py ```py
def max_n(lst, n=1): def max_n(lst, n=1):

View File

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

View File

@ -5,11 +5,10 @@ tags: list,math,advanced
Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions. Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions.
Use `max` combined with list comprehension to get the length of the longest list in the arguments. - Use `max` combined with list comprehension to get the length of the longest list in the arguments.
Use `range()` in combination with the `max_length` variable to loop as many times as there are elements in the longest list. - Use `range()` in combination with the `max_length` variable to loop as many times as there are elements in the longest list.
If a list is shorter than `max_length`, use `fill_value` for the remaining items (defaults to `None`). - If a list is shorter than `max_length`, use `fill_value` for the remaining items (defaults to `None`).
- [`zip()`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.zip_longest()`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) provide similar functionality to this snippet.
[`zip()`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.zip_longest()`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) provide similar functionality to this snippet.
```py ```py
def merge(*args, fill_value=None): def merge(*args, fill_value=None):

View File

@ -5,7 +5,7 @@ tags: dictionary,intermediate
Merges two or more dictionaries. Merges two or more dictionaries.
Create a new `dict()` and loop over `dicts`, using `dictionary.update()` to add the key-value pairs from each one to the result. - Create a new `dict()` and loop over `dicts`, using `dictionary.update()` to add the key-value pairs from each one to the result.
```py ```py
def merge_dictionaries(*dicts): def merge_dictionaries(*dicts):

View File

@ -5,7 +5,7 @@ tags: math,list,function,beginner
Returns the minimum value of a list, after mapping each element to a value using the provided function. Returns the minimum value of a list, after mapping each element to a value using the provided function.
Use `map()` with `fn` to map each element to a value using the provided function, use `min()` to return the minimum value. - Use `map()` with `fn` to map each element to a value using the provided function, use `min()` to return the minimum value.
```py ```py
def min_by(lst, fn): def min_by(lst, fn):

View File

@ -6,8 +6,8 @@ tags: list,math,beginner
Returns the `n` minimum elements from the provided list. Returns the `n` minimum elements from the provided list.
If `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order). If `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order).
Use `sorted() to sort the list, `[:n]` to get the specified number of elements. - Use `sorted() to sort the list, `[:n]` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element list. - Omit the second argument, `n`, to get a one-element list.
```py ```py
def min_n(lst, n=1): def min_n(lst, n=1):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Returns the most frequent element in a list. Returns the most frequent element in a list.
Use `set(list)` to get the unique values in the `list` combined with `max()` to find the element that has the most appearances. - Use `set(list)` to get the unique values in the `list` combined with `max()` to find the element that has the most appearances.
```py ```py
def most_frequent(list): def most_frequent(list):

View File

@ -5,7 +5,7 @@ tags: string,beginner
Prints out the same string a defined number of times. Prints out the same string a defined number of times.
Repeat the string `n` times, using the `*` operator. - Repeat the string `n` times, using the `*` operator.
```py ```py
def n_times_string(s, n): def n_times_string(s, n):

View File

@ -5,7 +5,7 @@ tags: list,function,intermediate
Returns `False` if the provided function returns `True` for at least one element in the list, `True` otherwise. Returns `False` if the provided function returns `True` for at least one element in the list, `True` otherwise.
Use `all()` and `fn` to check if `fn` returns `False` for all the elements in the list. - Use `all()` and `fn` to check if `fn` returns `False` for all the elements in the list.
```py ```py
def none(lst, fn=lambda x: x): def none(lst, fn=lambda x: x):

View File

@ -5,7 +5,7 @@ tags: list,beginner
Moves the specified amount of elements to the end of the list. Moves the specified amount of elements to the end of the list.
Use `lst[offset:]` and `lst[:offset]` to get the two slices of the list and combine them before returning. - Use `lst[offset:]` and `lst[:offset]` to get the two slices of the list and combine them before returning.
```py ```py
def offset(lst, offset): def offset(lst, offset):

View File

@ -5,8 +5,8 @@ tags: string,intermediate
Returns `True` if the given string is a palindrome, `False` otherwise. Returns `True` if the given string is a palindrome, `False` otherwise.
Use `s.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string. - Use `s.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string.
Then, compare the new string with its reverse. - Then, compare the new string with its reverse.
```py ```py
from re import sub from re import sub

View File

@ -5,7 +5,7 @@ tags: math,beginner
Converts an angle from radians to degrees. Converts an angle from radians to degrees.
Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees. - Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees.
```py ```py
from math import pi from math import pi

View File

@ -5,7 +5,7 @@ tags: string,beginner
Returns the reverse of a string. Returns the reverse of a string.
Use string slicing to reverse the string. - Use string slicing to reverse the string.
```py ```py
def reverse_string(s): def reverse_string(s):

View File

@ -5,8 +5,8 @@ tags: string,math,intermediate
Converts the values of RGB components to a hexadecimal color code. Converts the values of RGB components to a hexadecimal color code.
Create a placeholder for a zero-padded hexadecimal value using `"{:02X}"`, copy it three times. - Create a placeholder for a zero-padded hexadecimal value using `"{:02X}"`, copy it three times.
Use `str.format()` on the resulting string to replace the placeholders with the given values. - Use `str.format()` on the resulting string to replace the placeholders with the given values.
```py ```py
def rgb_to_hex(r, g, b): def rgb_to_hex(r, g, b):

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@ tags: string,regexp,intermediate
Converts a string to snake case. Converts a string to snake case.
Break the string into words and combine them adding `_` as a separator, using a regexp. - Break the string into words and combine them adding `_` as a separator, using a regexp.
```py ```py
from re import sub from re import sub

View File

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

Some files were not shown because too many files have changed in this diff Show More