Files
30-seconds-of-code/snippet_data/snippets.json
30secondsofcode fb01ddce13 Travis build: 454
2020-04-07 17:03:51 +00:00

2594 lines
99 KiB
JSON

{
"data": [
{
"id": "all_equal",
"title": "all_equal",
"type": "snippet",
"attributes": {
"fileName": "all_equal.md",
"text": "Checks if all elements in a list are equal.\n\nUse `[1:]` and `[:-1]` to compare all the values in the given list.\n\n",
"codeBlocks": {
"code": "def all_equal(lst):\n return lst[1:] == lst[:-1]",
"example": "all_equal([1, 2, 3, 4, 5, 6]) # False\nall_equal([1, 1, 1, 1]) # True"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "a284d604fca0eba2637f80ff4612a08e114be8df54e9ad3d5c9978fa6b96f757",
"firstSeen": "1566290358",
"lastUpdated": "1578048956",
"updateCount": 4,
"authorCount": 3
}
},
{
"id": "all_unique",
"title": "all_unique",
"type": "snippet",
"attributes": {
"fileName": "all_unique.md",
"text": "Returns `True` if all the values in a list are unique, `False` otherwise.\n\nUse `set()` on the given list to remove duplicates, use `len()` to compare its length with the length of the list.\n\n",
"codeBlocks": {
"code": "def all_unique(lst):\n return len(lst) == len(set(lst))",
"example": "x = [1, 2, 3, 4, 5, 6]\ny = [1, 2, 2, 3, 4, 5]\nall_unique(x) # True\nall_unique(y) # False"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "85a0536056d343fefcc2e27f43e0de4c09df66c425827dd0bcfdc2331283f9d2",
"firstSeen": "1522569789",
"lastUpdated": "1578048997",
"updateCount": 7,
"authorCount": 3
}
},
{
"id": "average",
"title": "average",
"type": "snippet",
"attributes": {
"fileName": "average.md",
"text": "Returns the average of two or more numbers.\n\nUse `sum()` to sum all of the `args` provided, divide by `len(args)`.\n\n",
"codeBlocks": {
"code": "def average(*args):\n return sum(args, 0.0) / len(args)",
"example": "average(*[1, 2, 3]) # 2.0\naverage(1, 2, 3) # 2.0"
},
"tags": [
"math",
"list",
"beginner"
]
},
"meta": {
"hash": "78bfdea5946774504eea1ba100974ad48ce8cb0a1ce1404cee8d885f35bb93a1",
"firstSeen": "1517030201",
"lastUpdated": "1566285234",
"updateCount": 11,
"authorCount": 5
}
},
{
"id": "average_by",
"title": "average_by",
"type": "snippet",
"attributes": {
"fileName": "average_by.md",
"text": "Returns the average of a list, after mapping each element to a value using the provided function.\n\nUse `map()` to map each element to the value returned by `fn`.\nUse `sum()` to sum all of the mapped values, divide by `len(lst)`.\n\n",
"codeBlocks": {
"code": "def average_by(lst, fn=lambda x: x):\n return sum(map(fn, lst), 0.0) / len(lst)",
"example": "average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n']) # 5.0"
},
"tags": [
"math",
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "8de876b55fd8b75ec395a5d70c29d83c7515d3ae2d59b9c7848e66e6cb854af0",
"firstSeen": "1566291310",
"lastUpdated": "1566291310",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "bifurcate",
"title": "bifurcate",
"type": "snippet",
"attributes": {
"fileName": "bifurcate.md",
"text": "Splits values into two groups. \nIf an element in `filter` is `True`, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.\n\nUse list comprehension and `enumerate()` to add elements to groups, based on `filter`.\n\n",
"codeBlocks": {
"code": "def bifurcate(lst, filter):\n return [\n [x for i, x in enumerate(lst) if filter[i] == True],\n [x for i, x in enumerate(lst) if filter[i] == False]\n ]",
"example": "bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ]"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "1d1f03106bae33aabbb4956f0553a29d942b0bafeb9d14d0db787262d114a116",
"firstSeen": "1566293826",
"lastUpdated": "1578048759",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "bifurcate_by",
"title": "bifurcate_by",
"type": "snippet",
"attributes": {
"fileName": "bifurcate_by.md",
"text": "Splits values into two groups according to a function, which specifies which group an element in the input list belongs to. \nIf the function returns `True`, the element belongs to the first group; otherwise, it belongs to the second group.\n\nUse list comprehension to add elements to groups, based on `fn`.\n\n",
"codeBlocks": {
"code": "def bifurcate_by(lst, fn):\n return [\n [x for x in lst if fn(x)],\n [x for x in lst if not fn(x)]\n ]",
"example": "bifurcate_by(\n ['beep', 'boop', 'foo', 'bar'], \n lambda x: x[0] == 'b'\n) # [ ['beep', 'boop', 'bar'], ['foo'] ]"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "91c7bf77e761cdd1e5ab4832e3a394bb5c85426df375e5ff4ea45450aae6cdfc",
"firstSeen": "1566294081",
"lastUpdated": "1578048759",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "byte_size",
"title": "byte_size",
"type": "snippet",
"attributes": {
"fileName": "byte_size.md",
"text": "Returns the length of a string in bytes.\n\nUse `s.encode('utf-8')` to encode the given string and return its length.\n\n",
"codeBlocks": {
"code": "def byte_size(s):\n return len(s.encode('utf-8'))",
"example": "byte_size('😀') # 4\nbyte_size('Hello World') # 11"
},
"tags": [
"string",
"beginner"
]
},
"meta": {
"hash": "2fc0a269966270d98c8f1721dde96e027e8b6146c3b84c0ac68ff2a6fe75c84a",
"firstSeen": "1517473199",
"lastUpdated": "1570502638",
"updateCount": 12,
"authorCount": 5
}
},
{
"id": "camel",
"title": "camel",
"type": "snippet",
"attributes": {
"fileName": "camel.md",
"text": "Converts a string to camelcase.\n\nUse `re.sub()` to replace any `-` or `_` with a space, using the regexp `r\"(_|-)+\"`.\nUse `title()` to capitalize the first letter of each word convert the rest to lowercase.\nFinally, use `replace()` to remove spaces between words.\n\n",
"codeBlocks": {
"code": "from re import sub\n\ndef camel(s):\n s = sub(r\"(_|-)+\", \" \", s).title().replace(\" \", \"\")\n return s[0].lower() + s[1:]",
"example": "camel('some_database_field_name') # 'someDatabaseFieldName'\ncamel('Some label that needs to be camelized') # 'someLabelThatNeedsToBeCamelized'\ncamel('some-javascript-property') # 'someJavascriptProperty'\ncamel('some-mixed_string with spaces_underscores-and-hyphens') # 'someMixedStringWithSpacesUnderscoresAndHyphens'"
},
"tags": [
"string",
"regexp",
"intermediate"
]
},
"meta": {
"hash": "b9a88311529b43189ddf945f9c86b0f05cdb4c2894e7f3a4305bdb6aa22171d5",
"firstSeen": "1566367194",
"lastUpdated": "1578048970",
"updateCount": 8,
"authorCount": 4
}
},
{
"id": "capitalize",
"title": "capitalize",
"type": "snippet",
"attributes": {
"fileName": "capitalize.md",
"text": "Capitalizes the first letter of a string.\n\nCapitalize the first letter of the string and then add it with rest of the string. \nOmit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase.\n\n",
"codeBlocks": {
"code": "def capitalize(s, lower_rest=False):\n return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])",
"example": "capitalize('fooBar') # 'FooBar'\ncapitalize('fooBar', True) # 'Foobar'"
},
"tags": [
"string",
"intermediate"
]
},
"meta": {
"hash": "f33a94899dfa72134171367526a2e0068dc0a8fc3c0504d42740aec1110e494b",
"firstSeen": "1517473199",
"lastUpdated": "1570502638",
"updateCount": 10,
"authorCount": 5
}
},
{
"id": "capitalize_every_word",
"title": "capitalize_every_word",
"type": "snippet",
"attributes": {
"fileName": "capitalize_every_word.md",
"text": "Capitalizes the first letter of every word in a string.\n\nUse `s.title()` to capitalize first letter of every word in the string.\n\n",
"codeBlocks": {
"code": "def capitalize_every_word(s):\n return s.title()",
"example": "capitalize_every_word('hello world!') # 'Hello World!'"
},
"tags": [
"string",
"beginner"
]
},
"meta": {
"hash": "4fc1e5869d50178ba135d6b30d3add0d3f5031ab8e24c07959f0321c2f2d7d6a",
"firstSeen": "1517473199",
"lastUpdated": "1570502638",
"updateCount": 10,
"authorCount": 5
}
},
{
"id": "cast_list",
"title": "cast_list",
"type": "snippet",
"attributes": {
"fileName": "cast_list.md",
"text": "Casts the provided value as a list if it's not one.\n\nUse `isinstance()` to check if the given value is enumerable and return it by using `list()` or encapsulated in a list accordingly.\n\n",
"codeBlocks": {
"code": "def cast_list(val):\n return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]",
"example": "cast_list('foo') # ['foo']\ncast_list([1]) # [1]\ncast_list(('foo', 'bar')) # ['foo', 'bar']"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "0765b0134c5da933915f4c6a7c43dc50b004fd799514e66133e0cfe438af9171",
"firstSeen": "1566294463",
"lastUpdated": "1586278480",
"updateCount": 7,
"authorCount": 4
}
},
{
"id": "celsius_to_fahrenheit",
"title": "celsius_to_fahrenheit",
"type": "snippet",
"attributes": {
"fileName": "celsius_to_fahrenheit.md",
"text": "Converts Celsius to Fahrenheit.\n\nUse the formula `fahrenheit = (celsius * 1.8) + 32` to convert from Celsius to Fahrenheit.\n\n",
"codeBlocks": {
"code": "def celsius_to_fahrenheit(celsius):\r\n return ((celsius * 1.8) + 32)",
"example": "celsius_to_fahrenheit(180) # 356.0"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "e6ff3f171475a484b9345c4ec64bc50de7ae8dada2a12d5222a357923d7d874e",
"firstSeen": "1586078943",
"lastUpdated": "1586078943",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "check_prop",
"title": "check_prop",
"type": "snippet",
"attributes": {
"fileName": "check_prop.md",
"text": "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.\n\nReturn a `lambda` function that takes an object and applies the predicate function, `fn` to the specified property.\n\n",
"codeBlocks": {
"code": "def check_prop(fn, prop):\r\n return lambda obj: fn(obj[prop])",
"example": "check_age = check_prop(lambda x: x >= 18, 'age')\r\nuser = {'name': 'Mark', 'age': 18}\r\n\r\ncheck_age(user) # True"
},
"tags": [
"function",
"intermediate"
]
},
"meta": {
"hash": "ceb7dcb63cc7ec14237807b05a7cc47e7298969bd90fa1bd1ca96426a3cfa34f",
"firstSeen": "1577976565",
"lastUpdated": "1586278449",
"updateCount": 4,
"authorCount": 3
}
},
{
"id": "chunk",
"title": "chunk",
"type": "snippet",
"attributes": {
"fileName": "chunk.md",
"text": "Chunks a list into smaller lists of a specified size.\n\nUse `list()` and `range()` to create a list of the desired `size`.\nUse `map()` on the list and fill it with splices of the given list.\nFinally, return the created list.\n\n",
"codeBlocks": {
"code": "from math import ceil\n\ndef chunk(lst, size):\n return list(\n map(lambda x: lst[x * size:x * size + size],\n list(range(0, ceil(len(lst) / size)))))",
"example": "chunk([1, 2, 3, 4, 5], 2) # [[1,2],[3,4],5]"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "04539dabc7eda5659177d2c3170343646ba5e4575b5f0127a348eb5d7b4e359c",
"firstSeen": "1515472782",
"lastUpdated": "1578048759",
"updateCount": 15,
"authorCount": 4
}
},
{
"id": "clamp_number",
"title": "clamp_number",
"type": "snippet",
"attributes": {
"fileName": "clamp_number.md",
"text": "Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.\n\nIf `num` falls within the range, return `num`. \nOtherwise, return the nearest number in the range.\n\n",
"codeBlocks": {
"code": "def clamp_number(num,a,b):\n return max(min(num, max(a, b)), min(a, b))",
"example": "clamp_number(2, 3, 5) # 3\nclamp_number(1, -1, -5) # -1"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "4abb40db52960635289aa0c16e94763fccc89bba5f79dedee5332bdfd6df30c7",
"firstSeen": "1566294638",
"lastUpdated": "1578048759",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "compact",
"title": "compact",
"type": "snippet",
"attributes": {
"fileName": "compact.md",
"text": "Removes falsey values from a list.\n\nUse `filter()` to filter out falsey values (`False`, `None`, `0`, and `\"\"`).\n\n",
"codeBlocks": {
"code": "def compact(lst):\n return list(filter(None, lst))",
"example": "compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "49af477281165f9623eb1ad399be5f43705940587ba70ee5d4ac697fcb29c6cd",
"firstSeen": "1516357026",
"lastUpdated": "1583870374",
"updateCount": 14,
"authorCount": 5
}
},
{
"id": "compose",
"title": "compose",
"type": "snippet",
"attributes": {
"fileName": "compose.md",
"text": "Performs right-to-left function composition.\n\nUse `functools.reduce()` to perform right-to-left function composition. \nThe last (rightmost) function can accept one or more arguments; the remaining functions must be unary.\n\n",
"codeBlocks": {
"code": "from functools import reduce\r\n\r\ndef compose(*fns):\r\n return reduce(lambda f, g: lambda *args: f(g(*args)), fns)",
"example": "add5 = lambda x: x + 5\r\nmultiply = lambda x, y: x * y\r\nmultiply_and_add_5 = compose(add5, multiply)\r\n\r\nmultiply_and_add_5(5, 2) # 15"
},
"tags": [
"function",
"intermediate"
]
},
"meta": {
"hash": "a70d6ec0dc67eb97bcc951e4d0a9489065bf2bb861f993026b0b1ed8517c6c00",
"firstSeen": "1577973080",
"lastUpdated": "1578048908",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "compose_right",
"title": "compose_right",
"type": "snippet",
"attributes": {
"fileName": "compose_right.md",
"text": "Performs left-to-right function composition.\n\nUse `functools.reduce()` to perform left-to-right function composition. \nThe first (leftmost) function can accept one or more arguments; the remaining functions must be unary.\n\n",
"codeBlocks": {
"code": "from functools import reduce\r\n\r\ndef compose_right(*fns):\r\n return reduce(lambda f, g: lambda *args: g(f(*args)), fns)",
"example": "add = lambda x, y: x + y\r\nsquare = lambda x: x * x\r\nadd_and_square = compose_right(add,square)\r\n\r\nadd_and_square(1, 2) # 9"
},
"tags": [
"function",
"intermediate"
]
},
"meta": {
"hash": "7c16b51fea79fb9301d9e46cd512069bba1b332e0e1dad493249603ce0a50db4",
"firstSeen": "1577973086",
"lastUpdated": "1578048908",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "count_by",
"title": "count_by",
"type": "snippet",
"attributes": {
"fileName": "count_by.md",
"text": "Groups the elements of a list based on the given function and returns the count of elements in each group.\n\nUse `map()` to map the values of the given list using the given function.\nIterate over the map and increase the element count each time it occurs.\n\n",
"codeBlocks": {
"code": "def count_by(arr, fn=lambda x: x):\n key = {}\n for el in map(fn, arr):\n key[el] = 1 if el not in key else key[el] + 1\n return key",
"example": "from math import floor\ncount_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}\ncount_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "bcbf6bf4eea87d50914f20640482d6e25198357ac3ec5155276664905ac1e5e0",
"firstSeen": "1517992427",
"lastUpdated": "1569156104",
"updateCount": 10,
"authorCount": 3
}
},
{
"id": "count_occurences",
"title": "count_occurences",
"type": "snippet",
"attributes": {
"fileName": "count_occurences.md",
"text": "Counts the occurrences of a value in a list.\n\nIncrement a counter for every item in the list that has the given value and is of the same type.\n\n",
"codeBlocks": {
"code": "def count_occurrences(lst, val):\n return len([x for x in lst if x == val and type(x) == type(val)])",
"example": "count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "eee88217431699369070beb38ca0265d963c78321bfd98de9e3a38533c6ee90e",
"firstSeen": "1516104827",
"lastUpdated": "1566286689",
"updateCount": 15,
"authorCount": 5
}
},
{
"id": "curry",
"title": "curry",
"type": "snippet",
"attributes": {
"fileName": "curry.md",
"text": "Curries a function.\n\nUse `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied.\n\n",
"codeBlocks": {
"code": "from functools import partial\r\n\r\ndef curry(fn, *args):\r\n return partial(fn,*args)",
"example": "add = lambda x, y: x + y\r\nadd10 = curry(add, 10)\r\n\r\nadd10(20) # 30"
},
"tags": [
"function",
"intermediate"
]
},
"meta": {
"hash": "8b4d1654ec3fb0041fe2762ddf2834488e5161a3843bd3a6c659f1426385182f",
"firstSeen": "1577974490",
"lastUpdated": "1578048908",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "decapitalize",
"title": "decapitalize",
"type": "snippet",
"attributes": {
"fileName": "decapitalize.md",
"text": "Decapitalizes the first letter of a string.\n\nDecapitalize the first letter of the string and then add it with rest of the string. \nOmit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase.\n\n",
"codeBlocks": {
"code": "def decapitalize(s, upper_rest=False):\n return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])",
"example": "decapitalize('FooBar') # 'fooBar'\ndecapitalize('FooBar', True) # 'fOOBAR'"
},
"tags": [
"string",
"intermediate"
]
},
"meta": {
"hash": "3bb7b5142417d0d14ba76f2221802ff72824243f7dd4331a2bbe20d20c24f6cf",
"firstSeen": "1517473199",
"lastUpdated": "1570502638",
"updateCount": 11,
"authorCount": 6
}
},
{
"id": "deep_flatten",
"title": "deep_flatten",
"type": "snippet",
"attributes": {
"fileName": "deep_flatten.md",
"text": "Deep flattens a list.\n\nUse recursion. \nUse `isinstance()` with `collections.abc.Iterable` to check if an element is iterable.\nIf it is, apply `deep_flatten()` recursively, otherwise return `[lst]`.\n\n",
"codeBlocks": {
"code": "from collections.abc import Iterable\n\ndef deep_flatten(lst): \n return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]",
"example": "deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]"
},
"tags": [
"list",
"recursion",
"intermediate"
]
},
"meta": {
"hash": "2988946e5ef7486404d962bb5a19e6a8f5b845775688966e3133e3b33b86334a",
"firstSeen": "1516114454",
"lastUpdated": "1578049156",
"updateCount": 777,
"authorCount": 4
}
},
{
"id": "degrees_to_rads",
"title": "degrees_to_rads",
"type": "snippet",
"attributes": {
"fileName": "degrees_to_rads.md",
"text": "Converts an angle from degrees to radians.\n\nUse `math.pi` and the degrees to radians formula to convert the angle from degrees to radians.\n\n",
"codeBlocks": {
"code": "from math import pi\n\ndef degrees_to_rads(deg):\n return (deg * pi) / 180.0",
"example": "degrees_to_rads(180) # 3.141592653589793"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "16bf7a5b40622e18047609f198cbd4f584c184c2c65a06e7765fac1ff10f9a50",
"firstSeen": "1571139071",
"lastUpdated": "1578048779",
"updateCount": 4,
"authorCount": 3
}
},
{
"id": "delay",
"title": "delay",
"type": "snippet",
"attributes": {
"fileName": "delay.md",
"text": "Invokes the provided function after `ms` milliseconds.\n\nUse `time.sleep()` to delay the execution of `fn` by `ms / 1000` seconds.\n\n",
"codeBlocks": {
"code": "from time import sleep\r\n\r\ndef delay(fn, ms, *args):\r\n sleep(ms / 1000)\r\n return fn(*args)",
"example": "delay(\r\n lambda x: print(x),\r\n 1000,\r\n 'later'\r\n) # prints 'later' after one second"
},
"tags": [
"function",
"intermediate"
]
},
"meta": {
"hash": "4b6091531fe0add9456f887dd4c90b7f7839f0a63edea7439be3e7f051c97556",
"firstSeen": "1577975091",
"lastUpdated": "1578048908",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "difference",
"title": "difference",
"type": "snippet",
"attributes": {
"fileName": "difference.md",
"text": "Returns the difference between two iterables.\n\nCreate a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`.\n\n",
"codeBlocks": {
"code": "def difference(a, b):\n _b = set(b)\n return [item for item in a if item not in _b]",
"example": "difference([1, 2, 3], [1, 2, 4]) # [3]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "479fcdba73e7429ccb82649a354159ad9008c63f852c960d6733c10ecafceae3",
"firstSeen": "1516457804",
"lastUpdated": "1566303266",
"updateCount": 15,
"authorCount": 5
}
},
{
"id": "difference_by",
"title": "difference_by",
"type": "snippet",
"attributes": {
"fileName": "difference_by.md",
"text": "Returns the difference between two lists, after applying the provided function to each list element of both.\n\nCreate 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`.\n\n",
"codeBlocks": {
"code": "def difference_by(a, b, fn):\n _b = set(map(fn, b))\n return [item for item in a if fn(item) not in _b]",
"example": "from math import floor\ndifference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]\ndifference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "5044c943260d7d4e162b60000d2a8dc2f689a43af6be7946b05fefc616c51425",
"firstSeen": "1518098367",
"lastUpdated": "1578048759",
"updateCount": 10,
"authorCount": 3
}
},
{
"id": "digitize",
"title": "digitize",
"type": "snippet",
"attributes": {
"fileName": "digitize.md",
"text": "Converts a number to a list of digits.\n\nUse `map()` combined with `int` on the string representation of `n` and return a list from the result.\n\n",
"codeBlocks": {
"code": "def digitize(n):\n return list(map(int, str(n)))",
"example": "digitize(123) # [1, 2, 3]"
},
"tags": [
"math",
"list",
"beginner"
]
},
"meta": {
"hash": "90beb85f77896593c9d5a0fa23954d7bf0ea69edf769bc55f5125002e717f2f3",
"firstSeen": "1566295227",
"lastUpdated": "1578048908",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "drop",
"title": "drop",
"type": "snippet",
"attributes": {
"fileName": "drop.md",
"text": "Returns a list with `n` elements removed from the left.\n\nUse slice notation to remove the specified number of elements from the left.\n\n",
"codeBlocks": {
"code": "def drop(a, n = 1):\r\n return a[n:]",
"example": "drop([1, 2, 3]) # [2, 3]\r\ndrop([1, 2, 3], 2) # [3]\r\ndrop([1, 2, 3], 42) # []"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "39a98596a5f94242a3bed40282ed2785f6e7254148bcb5410c5028dcbf352095",
"firstSeen": "1583870381",
"lastUpdated": "1583870381",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "drop_right",
"title": "drop_right",
"type": "snippet",
"attributes": {
"fileName": "drop_right.md",
"text": "Returns a list with `n` elements removed from the right.\n\nUse slice notation to remove the specified number of elements from the right.\n\n",
"codeBlocks": {
"code": "def drop_right(a, n = 1):\r\n return a[:-n]",
"example": "drop_right([1, 2, 3]) # [1, 2]\r\ndrop_right([1, 2, 3], 2) # [1]\r\ndrop_right([1, 2, 3], 42) # []"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "b8166585e68a5b2b74af067029d1d8895edef94f745816c7e8d3b04a7bdc9792",
"firstSeen": "1583870381",
"lastUpdated": "1583870381",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "every",
"title": "every",
"type": "snippet",
"attributes": {
"fileName": "every.md",
"text": "Returns `True` if the provided function returns `True` for every element in the list, `False` otherwise.\n\nUse `all()` in combination with `map` and `fn` to check if `fn` returns `True` for all elements in the list.\n\n",
"codeBlocks": {
"code": "def every(lst, fn=lambda x: x):\n return all(map(fn, lst))",
"example": "every([4, 2, 3], lambda x: x > 1) # True\nevery([1, 2, 3]) # True"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "40b8ce30ab95e515b6814e602a7f0755124b792d6f9c664f58e0ee61c27148c1",
"firstSeen": "1566290064",
"lastUpdated": "1569155530",
"updateCount": 4,
"authorCount": 2
}
},
{
"id": "every_nth",
"title": "every_nth",
"type": "snippet",
"attributes": {
"fileName": "every_nth.md",
"text": "Returns every nth element in a list.\n\nUse `[nth-1::nth]` to create a new list that contains every nth element of the given list.\n\n",
"codeBlocks": {
"code": "def every_nth(lst, nth):\n return lst[nth - 1::nth]",
"example": "every_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "043215573487367b96603083e9803521e4c30e4aa30b762da95307328dd485b1",
"firstSeen": "1566295812",
"lastUpdated": "1578048759",
"updateCount": 4,
"authorCount": 2
}
},
{
"id": "factorial",
"title": "factorial",
"type": "snippet",
"attributes": {
"fileName": "factorial.md",
"text": "Calculates the factorial of a number.\n\nUse recursion. \nIf `num` is less than or equal to `1`, return `1`. \nOtherwise, return the product of `num` and the factorial of `num - 1`. \nThrows an exception if `num` is a negative or a floating point number.\n\n",
"codeBlocks": {
"code": "def factorial(num):\n if not ((num >= 0) and (num % 1 == 0)):\n raise Exception(\"Number can't be floating point or negative.\")\n return 1 if num == 0 else num * factorial(num - 1)",
"example": "factorial(6) # 720"
},
"tags": [
"math",
"recursion",
"beginner"
]
},
"meta": {
"hash": "c13c145eb46403345b747fb7ca9c378a0e7f00dcd9f033f0e414279fcb4fdb88",
"firstSeen": "1517030996",
"lastUpdated": "1578049233",
"updateCount": 12,
"authorCount": 4
}
},
{
"id": "fahrenheit_to_celsius",
"title": "fahrenheit_to_celsius",
"type": "snippet",
"attributes": {
"fileName": "fahrenheit_to_celsius.md",
"text": "Converts Fahrenheit to Celsius.\n\nUse the formula `celsius = (fahrenheit - 32) / 1.8` to convert from Fahrenheit to Celsius.\n\n",
"codeBlocks": {
"code": "def fahrenheit_to_celsius(fahrenheit):\r\n return ((fahrenheit - 32) / 1.8)",
"example": "fahrenheit_to_celsius(77) # 25.0"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "98e114e9302c0aa91880059dbae94141965386a1f464286d3e598d3972663ff2",
"firstSeen": "1586078943",
"lastUpdated": "1586078943",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "fibonacci",
"title": "fibonacci",
"type": "snippet",
"attributes": {
"fileName": "fibonacci.md",
"text": "Generates a list, containing the Fibonacci sequence, up until the nth term.\n\nStarting 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`. \nIf `n` is less or equal to `0`, return a list containing `0`.\n\n",
"codeBlocks": {
"code": "def fibonacci(n):\r\n if n <= 0:\r\n return [0]\r\n\r\n sequence = [0, 1]\r\n while len(sequence) <= n:\r\n next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]\r\n sequence.append(next_value)\r\n\r\n return sequence",
"example": "fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13]"
},
"tags": [
"math",
"list",
"intermediate"
]
},
"meta": {
"hash": "16760105f8db2ebeb984b63a9830d5b0293392e2f55fc13851b364f50e180f5b",
"firstSeen": "1538795193",
"lastUpdated": "1578048956",
"updateCount": 10,
"authorCount": 5
}
},
{
"id": "filter_non_unique",
"title": "filter_non_unique",
"type": "snippet",
"attributes": {
"fileName": "filter_non_unique.md",
"text": "Filters out the non-unique values in a list.\n\nUse a `collections.Counter` to get the count of each value in the list.\nUse list comprehension to create a list containing only the unique values.\n\n",
"codeBlocks": {
"code": "from collections import Counter\n\ndef filter_non_unique(lst):\n return [item for item, count in counter = Counter(lst).items() if count == 1]",
"example": "filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "fc7c8b72dd9c4f53cd5d8ffe4c2befd0f1a6807caf58c0a2ddced195c6fa6c4f",
"firstSeen": "1566296031",
"lastUpdated": "1578502657",
"updateCount": 5,
"authorCount": 4
}
},
{
"id": "filter_unique",
"title": "filter_unique",
"type": "snippet",
"attributes": {
"fileName": "filter_unique.md",
"text": "Filters out the unique values in a list.\n\nUse a `collections.Counter` to get the count of each value in the list.\nUse list comprehension to create a list containing only the non-unique values.\n\n",
"codeBlocks": {
"code": "from collections import Counter\n\ndef filter_unique(lst):\n return [item for item, count in Counter(lst).items() if count > 1]",
"example": "filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "d5680d2e4f63df60dbf4cef97de86a6e0aee70284aa2729ae69427e8231521e0",
"firstSeen": "1570035984",
"lastUpdated": "1578502673",
"updateCount": 8,
"authorCount": 5
}
},
{
"id": "find",
"title": "find",
"type": "snippet",
"attributes": {
"fileName": "find.md",
"text": "Returns the value of the first element in the provided list that satisfies the provided testing function.\n\nUse list comprehension and `next()` to return the first element in `lst` for which `fn` returns `True`.\n\n",
"codeBlocks": {
"code": "def find(lst, fn):\r\n return next(x for x in lst if fn(x))",
"example": "find([1, 2, 3, 4], lambda n: n % 2 == 1) # 1"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "3e879def3995b7bd2062230bdc8b87269eeb5dc9eb6ce9eb3f297d84dc5beb5e",
"firstSeen": "1583872728",
"lastUpdated": "1583872728",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "find_index",
"title": "find_index",
"type": "snippet",
"attributes": {
"fileName": "find_index.md",
"text": "Returns the index of the first element in the provided list that satisfies the provided testing function.\n\nUse list comprehension, `enumerate()` and `next()` to return the index of the first element in `lst` for which `fn` returns `True`.\n\n",
"codeBlocks": {
"code": "def find_index(lst, fn):\r\n return next(i for i, x in enumerate(lst) if fn(x))",
"example": "find_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 0"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "2270fdbf382af07bdc47d0dba84eec939885734cb17f015186547a1b9a26ecce",
"firstSeen": "1583872728",
"lastUpdated": "1583872728",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "find_last",
"title": "find_last",
"type": "snippet",
"attributes": {
"fileName": "find_last.md",
"text": "Returns the value of the last element in the provided list that satisfies the provided testing function.\n\nUse list comprehension and `next()` to return the last element in `lst` for which `fn` returns `True`.\n\n",
"codeBlocks": {
"code": "def find_last(lst, fn):\r\n return next(x for x in lst[::-1] if fn(x))",
"example": "find_last([1, 2, 3, 4], lambda n: n % 2 == 1) # 3"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "5a4ad2eca4edba75e139f8979bdb9eba7ab116e0c1f80d054261764d54e16957",
"firstSeen": "1583872728",
"lastUpdated": "1583872728",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "find_last_index",
"title": "find_last_index",
"type": "snippet",
"attributes": {
"fileName": "find_last_index.md",
"text": "Returns the index of the last element in the provided list that satisfies the provided testing function.\n\nUse list comprehension, `enumerate()` and `next()` to return the index of the last element in `lst` for which `fn` returns `True`.\n\n",
"codeBlocks": {
"code": "def find_last_index(lst, fn):\r\n return len(lst) - 1 - next(i for i, x in enumerate(lst[::-1]) if fn(x))",
"example": "find_last_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 2"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "de25fa799e8392834d484b1609eb02a68a46dd9833086e4fdf9690fe2516a858",
"firstSeen": "1583872728",
"lastUpdated": "1583872728",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "find_parity_outliers",
"title": "find_parity_outliers",
"type": "snippet",
"attributes": {
"fileName": "find_parity_outliers.md",
"text": "Given a list, returns the items that are parity outliers.\n\nUse `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.\nUse a list comprehension to find all elements that do not match the most common parity.\n\n",
"codeBlocks": {
"code": "from collections import Counter\n\ndef find_parity_outliers(nums):\n return [\n x for x in nums\n if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]\n ]",
"example": "find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]"
},
"tags": [
"list",
"math",
"intermediate"
]
},
"meta": {
"hash": "87bee9709b95c43c36718bc31f6f3c381c05159b7d33e0016ede29d4168d3843",
"firstSeen": "1578502475",
"lastUpdated": "1578502475",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "flatten",
"title": "flatten",
"type": "snippet",
"attributes": {
"fileName": "flatten.md",
"text": "Flattens a list of lists once.\n\nUse nested list comprehension to extract each value from sub-lists in order.\n\n",
"codeBlocks": {
"code": "def flatten(lst):\n return [x for y in lst for x in y]",
"example": "flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6, 7, 8]"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "49b4f976c9050c9cb6fe038653fc3dbc88135086255c06c4f46b746b21bfb544",
"firstSeen": "1568897170",
"lastUpdated": "1568915016",
"updateCount": 3,
"authorCount": 3
}
},
{
"id": "for_each",
"title": "for_each",
"type": "snippet",
"attributes": {
"fileName": "for_each.md",
"text": "Executes the provided function once for each list element.\n\nUse a `for` loop to execute `fn` for each element in `itr`.\n\n",
"codeBlocks": {
"code": "def for_each(itr, fn):\r\n for el in itr:\r\n fn(el)",
"example": "for_each([1, 2, 3], print) # 1 2 3"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "bbd13f90d710c3fa85d297d668f2db9de6e20ae87b5b85977126de92c9d2a508",
"firstSeen": "1584269648",
"lastUpdated": "1584269648",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "for_each_right",
"title": "for_each_right",
"type": "snippet",
"attributes": {
"fileName": "for_each_right.md",
"text": "Executes the provided function once for each list element, starting from the list's last element.\n\nUse a `for` loop in combination with slice notation to execute `fn` for each element in `itr`, starting from the last one.\n\n",
"codeBlocks": {
"code": "def for_each_right(itr, fn):\r\n for el in itr[::-1]:\r\n fn(el)",
"example": "for_each_right([1, 2, 3], print) # 3 2 1"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "96f4508f15d58e10c82959ab9aa5ec37860e051b5d211912f2b17ad968e10464",
"firstSeen": "1584269648",
"lastUpdated": "1584269648",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "frequencies",
"title": "frequencies",
"type": "snippet",
"attributes": {
"fileName": "frequencies.md",
"text": "Returns a dictionary with the unique values of a list as keys and their frequencies as the values.\n\nUse 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.\n\n",
"codeBlocks": {
"code": "from functools import reduce\r\n\r\ndef frequencies(lst):\r\n f = {}\r\n for x in lst:\r\n f[x] = f[x] + 1 if x in f else 1\r\n return f",
"example": "frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 }"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "e39e557aa6a70400a5e7b7a7ab5291e1937d93c0016c8fd0897cce32af315be6",
"firstSeen": "1584269648",
"lastUpdated": "1584269648",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "gcd",
"title": "gcd",
"type": "snippet",
"attributes": {
"fileName": "gcd.md",
"text": "Calculates the greatest common divisor of a list of numbers.\n\nUse `functools.reduce()` and `math.gcd()` over the given list.\n\n",
"codeBlocks": {
"code": "from functools import reduce\nfrom math import gcd\n\ndef gcd(numbers):\n return reduce(gcd, numbers)",
"example": "gcd([8, 36, 28]) # 4"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "fc9dfc759e41dc0d26ed4e339d7210e13c4cec8ed10b148d481a2d84fe0f63b8",
"firstSeen": "1515421595",
"lastUpdated": "1578048779",
"updateCount": 17,
"authorCount": 4
}
},
{
"id": "group_by",
"title": "group_by",
"type": "snippet",
"attributes": {
"fileName": "group_by.md",
"text": "Groups the elements of a list based on the given function.\n\nUse `map()` and `fn` to map the values of the list to the keys of a dictionary.\nUse list comprehension to map each element to the appropriate `key`.\n\n",
"codeBlocks": {
"code": "def group_by(lst, fn):\n return {key : [el for el in lst if fn(el) == key] for key in map(fn, lst)}",
"example": "from math import floor\ngroup_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}\ngroup_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}"
},
"tags": [
"list",
"dictionary",
"intermediate"
]
},
"meta": {
"hash": "024b31b493db85088428a449af3124901063e8507d76c7b36c898d5cd09bb9d6",
"firstSeen": "1566296940",
"lastUpdated": "1586278519",
"updateCount": 8,
"authorCount": 3
}
},
{
"id": "has_duplicates",
"title": "has_duplicates",
"type": "snippet",
"attributes": {
"fileName": "has_duplicates.md",
"text": "Returns `True` if there are duplicate values in a flat list, `False` otherwise.\n\nUse `set()` on the given list to remove duplicates, compare its length with the length of the list.\n\n",
"codeBlocks": {
"code": "def has_duplicates(lst):\n return len(lst) != len(set(lst))",
"example": "x = [1, 2, 3, 4, 5, 5]\ny = [1, 2, 3, 4, 5]\nhas_duplicates(x) # True\nhas_duplicates(y) # False"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "fb22c3f566fea0468c7331478cb216890de4af6b86b24f1ac41656bae949d99c",
"firstSeen": "1522569789",
"lastUpdated": "1581355826",
"updateCount": 8,
"authorCount": 4
}
},
{
"id": "have_same_contents",
"title": "have_same_contents",
"type": "snippet",
"attributes": {
"fileName": "have_same_contents.md",
"text": "Returns `True` if two lists contain the same elements regardless of order, `False` otherwise.\n\nUse `set()` on the combination of both lists to find the unique values.\nIterate over them with a `for` loop comparing the `count()` of each unique value in each list.\nReturn `False` if the counts do not match for any element, `True` otherwise.\n\n",
"codeBlocks": {
"code": "def have_same_contents(a, b):\r\n for v in set(a + b):\r\n if a.count(v) != b.count(v):\r\n return False\r\n return True",
"example": "have_same_contents([1, 2, 4], [2, 4, 1]) # True"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "3eb3a7c4b95e18bcd181965b01d6f46189735e0ada4a7e3e787026d9643792ed",
"firstSeen": "1584269648",
"lastUpdated": "1584269648",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "head",
"title": "head",
"type": "snippet",
"attributes": {
"fileName": "head.md",
"text": "Returns the head of a list.\n\nUse `lst[0]` to return the first element of the passed list.\n\n",
"codeBlocks": {
"code": "def head(lst):\n return lst[0]",
"example": "head([1, 2, 3]) # 1"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "967333852bd5578d4cb6bf8bfe20781b9137d5809320a6a000828456e32a1efe",
"firstSeen": "1566299332",
"lastUpdated": "1578048873",
"updateCount": 4,
"authorCount": 3
}
},
{
"id": "in_range",
"title": "in_range",
"type": "snippet",
"attributes": {
"fileName": "in_range.md",
"text": "Checks if the given number falls within the given range.\n\nUse arithmetic comparison to check if the given number is in the specified range.\nIf the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.\n\n",
"codeBlocks": {
"code": "def in_range(n, start, end = 0):\n return start <= n <= end if end >= start else end <= n <= start",
"example": "in_range(3, 2, 5) # True\nin_range(3, 4) # True\nin_range(2, 3, 5) # False\nin_range(3, 2) # False"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "dd49fd3dc6b7590a2607ded9b2f4b879ea56b93573e92376f669a1957ad9945b",
"firstSeen": "1566297700",
"lastUpdated": "1578049196",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "includes_all",
"title": "includes_all",
"type": "snippet",
"attributes": {
"fileName": "includes_all.md",
"text": "Returns `True` if all the elements in `values` are included in `lst`, `False` otherwise.\n\nCheck if every value in `values` is contained in `lst` using a `for` loop, returning `False` if any one value is not found, `True` otherwise.\n\n",
"codeBlocks": {
"code": "def includes_all(lst, values):\r\n for v in values:\r\n if v not in lst:\r\n return False\r\n return True",
"example": "includes_all([1, 2, 3, 4], [1, 4]) # True\r\nincludes_all([1, 2, 3, 4], [1, 5]) # False"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "dd6fe881dce1046713ff6fe1a9ee70cb3ff580b5b4f40a83f1cded8f1b2fc471",
"firstSeen": "1584269648",
"lastUpdated": "1584380100",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "includes_any",
"title": "includes_any",
"type": "snippet",
"attributes": {
"fileName": "includes_any.md",
"text": "Returns `True` if any element in `values` is included in `lst`, `False` otherwise.\n\nCheck if any value in `values` is contained in `lst` using a `for` loop, returning `True` if any one value is found, `False` otherwise.\n\n",
"codeBlocks": {
"code": "def includes_any(lst, values):\r\n for v in values:\r\n if v in lst:\r\n return True\r\n return False",
"example": "includes_any([1, 2, 3, 4], [2, 9]) # True\r\nincludes_any([1, 2, 3, 4], [8, 9]) # False"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "0207394cbc28148c73703db1298673049f9fe66936a59057955d3da180f3a0c4",
"firstSeen": "1584269648",
"lastUpdated": "1584269648",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "initial",
"title": "initial",
"type": "snippet",
"attributes": {
"fileName": "initial.md",
"text": "Returns all the elements of a list except the last one.\n\nUse `lst[0:-1]` to return all but the last element of the list.\n\n",
"codeBlocks": {
"code": "def initial(lst):\n return lst[0:-1]",
"example": "initial([1, 2, 3]) # [1,2]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "a55c33e2511216427f6b6f80d743f3fe4cd40a28f775c027d73352a04f531269",
"firstSeen": "1566299332",
"lastUpdated": "1578048873",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "initialize_2d_list",
"title": "initialize_2d_list",
"type": "snippet",
"attributes": {
"fileName": "initialize_2d_list.md",
"text": "Initializes a 2D list of given width and height and value.\n\nUse list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`.\nIf `val` is not provided, default to `None`.\n\n",
"codeBlocks": {
"code": "def initialize_2d_list(w,h, val = None):\n return [[val for x in range(w)] for y in range(h)]",
"example": "initialize_2d_list(2, 2, 0) # [[0,0], [0,0]]"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "0dea8eb7639aa7d0b2748ecfaeb80b1a93408340b6f697f604451b8e9442f477",
"firstSeen": "1571987511",
"lastUpdated": "1571987511",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "initialize_list_with_range",
"title": "initialize_list_with_range",
"type": "snippet",
"attributes": {
"fileName": "initialize_list_with_range.md",
"text": "Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.\n\nUse `list` and `range()` to generate a list of the appropriate length, filled with the desired values in the given range.\nOmit `start` to use the default value of `0`.\nOmit `step` to use the default value of `1`.\n\n",
"codeBlocks": {
"code": "def initialize_list_with_range(end, start=0, step=1):\n return list(range(start, end + 1, step))",
"example": "initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]\ninitialize_list_with_range(7, 3) # [3, 4, 5, 6, 7]\ninitialize_list_with_range(9, 0, 2) # [0, 2, 4, 6, 8]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "b7fa8130ef5c85aacb645b1e194073167f29a5ce234b5e13549dbb728ba09ca9",
"firstSeen": "1566303701",
"lastUpdated": "1578048759",
"updateCount": 4,
"authorCount": 3
}
},
{
"id": "initialize_list_with_values",
"title": "initialize_list_with_values",
"type": "snippet",
"attributes": {
"fileName": "initialize_list_with_values.md",
"text": "Initializes and fills a list with the specified value.\n\nUse list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values.\nOmit `val` to use the default value of `0`.\n\n",
"codeBlocks": {
"code": "def initialize_list_with_values(n, val = 0):\n return [val for x in range(n)]",
"example": "initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "87604b968fccbc3d60399619b388f5939d646059db467fc2c86f99138f68b952",
"firstSeen": "1566299526",
"lastUpdated": "1566299526",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "intersection",
"title": "intersection",
"type": "snippet",
"attributes": {
"fileName": "intersection.md",
"text": "Returns a list of elements that exist in both lists.\n\nCreate 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`.\n\n",
"codeBlocks": {
"code": "def intersection(a, b):\n _a, _b = set(a), set(b)\n return list(_a & _b)",
"example": "intersection([1, 2, 3], [4, 3, 2]) # [2, 3]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "d20f757b18d4368324bfa74bb907f5dc2df9262886ea3722edd5015418ce282d",
"firstSeen": "1566303266",
"lastUpdated": "1570026324",
"updateCount": 3,
"authorCount": 3
}
},
{
"id": "intersection_by",
"title": "intersection_by",
"type": "snippet",
"attributes": {
"fileName": "intersection_by.md",
"text": "Returns a list of elements that exist in both lists, after applying the provided function to each list element of both.\n\nCreate 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.\n\n",
"codeBlocks": {
"code": "def intersection_by(a, b, fn):\n _b = set(map(fn, b))\n return [item for item in a if fn(item) in _b]",
"example": "from math import floor\nintersection_by([2.1, 1.2], [2.3, 3.4],floor) # [2.1]"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "eb4bff1a92a7848c8184531fee590e8f060a6d4f6ffe214aec4ccda7a5e18031",
"firstSeen": "1566303387",
"lastUpdated": "1566303387",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "is_anagram",
"title": "is_anagram",
"type": "snippet",
"attributes": {
"fileName": "is_anagram.md",
"text": "Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).\n\nUse `isalnum()` to filter out non-alphanumeric characters, `lower()` to transform each character to lowercase.\nUse `collections.Counter` to count the resulting characters for each string and compare the results.\n\n",
"codeBlocks": {
"code": "from collections import Counter\n\ndef is_anagram(s1, s2):\n return Counter(\n c.lower() for c in s1 if c.isalnum()\n ) == Counter(\n c.lower() for c in s2 if c.isalnum()\n )",
"example": "is_anagram(\"#anagram\", \"Nag a ram!\") # True"
},
"tags": [
"string",
"intermediate"
]
},
"meta": {
"hash": "15833b3a98e905cf4cbac346028c5e6b5560d3b968800b94548e77a77098b7cc",
"firstSeen": "1538389049",
"lastUpdated": "1584622237",
"updateCount": 10,
"authorCount": 5
}
},
{
"id": "is_contained_in",
"title": "is_contained_in",
"type": "snippet",
"attributes": {
"fileName": "is_contained_in.md",
"text": "Returns `True` if the elements of the first list are contained in the second one regardless of order, `False` otherwise.\n\n\nUse `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.\n\n\n",
"codeBlocks": {
"code": "def is_contained_in(a, b):\r\n for v in set(a):\r\n if a.count(v) > b.count(v):\r\n return False\r\n return True",
"example": "is_contained_in([1, 4], [2, 4, 1]) # True"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "8fa2c19d9202502df8d26e461e9b02c4c47525dc79a91f4616b61d650cfb23ce",
"firstSeen": "1584380895",
"lastUpdated": "1584388846",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "is_divisible",
"title": "is_divisible",
"type": "snippet",
"attributes": {
"fileName": "is_divisible.md",
"text": "Checks if the first numeric argument is divisible by the second one.\n\nUse the modulo operator (`%`) to check if the remainder is equal to `0`.\n\n",
"codeBlocks": {
"code": "def is_divisible(dividend, divisor):\n return dividend % divisor == 0",
"example": "is_divisible(6, 3) # True"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "e6272becc36195e4b76f62baa61d43d9de5472201d1fb589e18bd5f47d6d57b0",
"firstSeen": "1566299995",
"lastUpdated": "1566299995",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "is_even",
"title": "is_even",
"type": "snippet",
"attributes": {
"fileName": "is_even.md",
"text": "Returns `True` if the given number is even, `False` otherwise.\n\nChecks whether a number is odd or even using the modulo (`%`) operator. \nReturns `True` if the number is even, `False` if the number is odd.\n\n",
"codeBlocks": {
"code": "def is_even(num):\n return num % 2 == 0",
"example": "is_even(3) # False"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "354d3fcfa67b5df106c0ff528246bfacd2d7cec4942a7c3a904d87e76d7dae11",
"firstSeen": "1566300104",
"lastUpdated": "1566300104",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "is_odd",
"title": "is_odd",
"type": "snippet",
"attributes": {
"fileName": "is_odd.md",
"text": "Returns `True` if the given number is odd, `False` otherwise.\n\nChecks whether a number is even or odd using the modulo (`%`) operator. \nReturns `True` if the number is odd, `False` if the number is even.\n\n",
"codeBlocks": {
"code": "def is_odd(num):\n return num % 2 != 0",
"example": "is_odd(3) # True"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "261771aa5fd9c9dcb60dd93c29afce0de3a51c505e474fa7c76789a1e0d8f5c8",
"firstSeen": "1566300104",
"lastUpdated": "1566542855",
"updateCount": 4,
"authorCount": 2
}
},
{
"id": "kebab",
"title": "kebab",
"type": "snippet",
"attributes": {
"fileName": "kebab.md",
"text": "Converts a string to kebab case.\n\nBreak the string into words and combine them adding `-` as a separator, using a regexp.\n\n",
"codeBlocks": {
"code": "from re import sub\n\ndef kebab(s):\n return sub(\n r\"(\\s|_|-)+\",\"-\",\n sub(\n r\"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+\",\n lambda mo: mo.group(0).lower(), s))",
"example": "kebab('camelCase') # 'camel-case'\nkebab('some text') # 'some-text'\nkebab('some-mixed_string With spaces_underscores-and-hyphens') # 'some-mixed-string-with-spaces-underscores-and-hyphens'\nkebab('AllThe-small Things') # \"all-the-small-things\""
},
"tags": [
"string",
"regexp",
"intermediate"
]
},
"meta": {
"hash": "db8a145f1dc53a254a9572fa47f76968b4381964b2291c5883c78f9337b7dbc9",
"firstSeen": "1566367194",
"lastUpdated": "1578048970",
"updateCount": 5,
"authorCount": 3
}
},
{
"id": "keys_only",
"title": "keys_only",
"type": "snippet",
"attributes": {
"fileName": "keys_only.md",
"text": "Returns a flat list of all the keys in a flat dictionary.\n\nUse `dict.keys()` to return the keys in the given dictionary.\nReturn a `list()` of the previous result.\n\n",
"codeBlocks": {
"code": "def keys_only(flat_dict):\n return list(flat_dict.keys())",
"example": "ages = {\n \"Peter\": 10,\n \"Isabel\": 11,\n \"Anna\": 9,\n}\nkeys_only(ages) # ['Peter', 'Isabel', 'Anna']"
},
"tags": [
"dictionary",
"list",
"beginner"
]
},
"meta": {
"hash": "4e4a5b4892fcccb2982e7ae352f9d61fa0234c209431c9461ea47d503feaaf49",
"firstSeen": "1522616191",
"lastUpdated": "1586278519",
"updateCount": 9,
"authorCount": 5
}
},
{
"id": "last",
"title": "last",
"type": "snippet",
"attributes": {
"fileName": "last.md",
"text": "Returns the last element in a list.\n\nuse `lst[-1]` to return the last element of the passed list.\n\n",
"codeBlocks": {
"code": "def last(lst):\n return lst[-1]",
"example": "last([1, 2, 3]) # 3"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "7fc339fbdb18e993fc93950b307fe2ec792c3f010f5dee0971d02288af16d67b",
"firstSeen": "1566303107",
"lastUpdated": "1566303107",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "lcm",
"title": "lcm",
"type": "snippet",
"attributes": {
"fileName": "lcm.md",
"text": "Returns the least common multiple of a list of numbers.\n\nUse `functools.reduce()`, `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` over the given list.\n\n",
"codeBlocks": {
"code": "from functools import reduce\nfrom math import gcd\n\ndef lcm(numbers):\n return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers)",
"example": "lcm([12, 7]) # 84\nlcm([1, 3, 4, 5]) # 60"
},
"tags": [
"math",
"list",
"recursion",
"advanced"
]
},
"meta": {
"hash": "030af844c409419551f3ce340666ad7b59949b54814fe50f3a474c2a06a211a5",
"firstSeen": "1515443417",
"lastUpdated": "1578049163",
"updateCount": 16,
"authorCount": 3
}
},
{
"id": "longest_item",
"title": "longest_item",
"type": "snippet",
"attributes": {
"fileName": "longest_item.md",
"text": "Takes any number of iterable objects or objects with a length property and returns the longest one. \nIf multiple objects have the same length, the first one will be returned.\n\nUse `max()` with `len` as the `key` to return the item with the greatest length.\n\n",
"codeBlocks": {
"code": "def longest_item(*args):\n return max(args, key=len)",
"example": "longest_item('this', 'is', 'a', 'testcase') # 'testcase'\nlongest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5]\nlongest_item([1, 2, 3], 'foobar') # 'foobar'"
},
"tags": [
"list",
"string",
"intermediate"
]
},
"meta": {
"hash": "af50f2096fef9a18346e3c220ff1957ab4218075e6c02ae05d8c3f6e3d269549",
"firstSeen": "1566304069",
"lastUpdated": "1586278551",
"updateCount": 4,
"authorCount": 3
}
},
{
"id": "map_dictionary",
"title": "map_dictionary",
"type": "snippet",
"attributes": {
"fileName": "map_dictionary.md",
"text": "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.\n\nUse a `for` loop to iterate over the list's values, assigning the values produced by `fn` to each key of the dictionary.\n\n",
"codeBlocks": {
"code": "def map_dictionary(itr, fn):\n ret = {}\n for x in itr:\n ret[x] = fn(x)\n return ret",
"example": "map_dictionary([1,2,3], lambda x: x * x) # { 1: 1, 2: 4, 3: 9 }"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "16139240bec2937cb771f0c63d0172d15e3d776efe32c8c52a03f6c8fa1db689",
"firstSeen": "1586278428",
"lastUpdated": "1586278428",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "map_values",
"title": "map_values",
"type": "snippet",
"attributes": {
"fileName": "map_values.md",
"text": "Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.\n\nUse `dict.keys()` to iterate over the dictionary's keys, assigning the values produced by `fn` to each key of a new dictionary.\n\n",
"codeBlocks": {
"code": "def map_values(obj, fn):\n ret = {}\n for key in obj.keys():\n ret[key] = fn(obj[key])\n return ret",
"example": "users = {\n 'fred': { 'user': 'fred', 'age': 40 },\n 'pebbles': { 'user': 'pebbles', 'age': 1 }\n}\n\nmap_values(users, lambda u : u['age']) # {'fred': 40, 'pebbles': 1}"
},
"tags": [
"dictionary",
"function",
"intermediate"
]
},
"meta": {
"hash": "bb8b57173fdb7084667db5aa6b608316b4ccf7ad8aed6a14f7bae9c5cf7e0dea",
"firstSeen": "1566304470",
"lastUpdated": "1586278519",
"updateCount": 3,
"authorCount": 3
}
},
{
"id": "max_by",
"title": "max_by",
"type": "snippet",
"attributes": {
"fileName": "max_by.md",
"text": "Returns the maximum value of a list, after mapping each element to a value using the provided function.\n\nUse `map()` with `fn` to map each element to a value using the provided function, use `max()` to return the maximum value.\n\n",
"codeBlocks": {
"code": "def max_by(lst, fn):\n return max(map(fn, lst))",
"example": "max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 8"
},
"tags": [
"math",
"list",
"function",
"beginner"
]
},
"meta": {
"hash": "53b802a4eb47675a404933430e2b7aa061d879d612607b79793080a47243d205",
"firstSeen": "1566304961",
"lastUpdated": "1578048759",
"updateCount": 5,
"authorCount": 2
}
},
{
"id": "max_element_index",
"title": "max_element_index",
"type": "snippet",
"attributes": {
"fileName": "max_element_index.md",
"text": "Returns the index of the element with the maximum value in a list.\n\nUse `max()` and `list.index()` to get the maximum value in the list and return its index.\n\n",
"codeBlocks": {
"code": "def max_element_index(arr):\r\n return arr.index(max(arr))",
"example": "thon\r\nmax_element_index([5, 8, 9, 7, 10, 3, 0]) # 4"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "efccd7f3d8767fa7c7759cab5eec415fdd51bf095dffe197861136b013623fe7",
"firstSeen": "1572507741",
"lastUpdated": "1578656508",
"updateCount": 3,
"authorCount": 3
}
},
{
"id": "max_n",
"title": "max_n",
"type": "snippet",
"attributes": {
"fileName": "max_n.md",
"text": "Returns the `n` maximum elements from the provided list. \nIf `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order).\n\nUse `sorted()` to sort the list, `[:n]` to get the specified number of elements.\nOmit the second argument, `n`, to get a one-element list.\n\n",
"codeBlocks": {
"code": "def max_n(lst, n=1):\n return sorted(lst, reverse=True)[:n]",
"example": "max_n([1, 2, 3]) # [3]\nmax_n([1, 2, 3], 2) # [3,2]"
},
"tags": [
"list",
"math",
"beginner"
]
},
"meta": {
"hash": "a87775ce6bd1590c7c7b31b7dfce03b00120e4e8183c65cec8fdd3841fa369d7",
"firstSeen": "1516353928",
"lastUpdated": "1566540214",
"updateCount": 14,
"authorCount": 5
}
},
{
"id": "median",
"title": "median",
"type": "snippet",
"attributes": {
"fileName": "median.md",
"text": "Finds the median of a list of numbers.\n\nSort 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.\n\n[`statistics.median()`](https://docs.python.org/3/library/statistics.html#statistics.median) provides similar functionality to this snippet.\n\n",
"codeBlocks": {
"code": "def median(list):\n list.sort()\n list_length = len(list)\n if list_length % 2 == 0:\n return (list[int(list_length / 2) - 1] + list[int(list_length / 2)]) / 2\n return list[int(list_length / 2)]",
"example": "median([1,2,3]) # 2\nmedian([1,2,3,4]) # 2.5"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "2cbdc2820f9bd452c3d9d7ec3ea72f449ffc57765145d997ad4b2f108e904bdf",
"firstSeen": "1570093337",
"lastUpdated": "1578227073",
"updateCount": 10,
"authorCount": 6
}
},
{
"id": "min_by",
"title": "min_by",
"type": "snippet",
"attributes": {
"fileName": "min_by.md",
"text": "Returns the minimum value of a list, after mapping each element to a value using the provided function.\n\nUse `map()` with `fn` to map each element to a value using the provided function, use `min()` to return the minimum value.\n\n",
"codeBlocks": {
"code": "def min_by(lst, fn):\n return min(map(fn, lst))",
"example": "min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 2"
},
"tags": [
"math",
"list",
"function",
"beginner"
]
},
"meta": {
"hash": "2a913d7608234d8988d44fa71e0477cdb2185f3d32f4cc22860ea2807255e585",
"firstSeen": "1566304961",
"lastUpdated": "1578048759",
"updateCount": 5,
"authorCount": 2
}
},
{
"id": "min_n",
"title": "min_n",
"type": "snippet",
"attributes": {
"fileName": "min_n.md",
"text": "Returns the `n` minimum elements from the provided list. \nIf `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order).\n\nUse `sorted() to sort the list, `[:n]` to get the specified number of elements.\nOmit the second argument, `n`, to get a one-element list.\n\n",
"codeBlocks": {
"code": "def min_n(lst, n=1):\n return sorted(lst, reverse=False)[:n]",
"example": "min_n([1, 2, 3]) # [1]\nmin_n([1, 2, 3], 2) # [1,2]"
},
"tags": [
"list",
"math",
"beginner"
]
},
"meta": {
"hash": "c920b58f01c63346e65eab83a60c4635d4c104e41767b9d41ad94029e662b902",
"firstSeen": "1516353928",
"lastUpdated": "1566288481",
"updateCount": 12,
"authorCount": 4
}
},
{
"id": "most_frequent",
"title": "most_frequent",
"type": "snippet",
"attributes": {
"fileName": "most_frequent.md",
"text": "Returns the most frequent element in a list.\n\nUse `set(list)` to get the unique values in the `list` combined with `max()` to find the element that has the most appearances.\n\n",
"codeBlocks": {
"code": "def most_frequent(list):\n return max(set(list), key=list.count)",
"example": "most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "e63217dfdd3ea87db1448e4178dffcf59ae3cff4138062c6e623896076d802db",
"firstSeen": "1570830049",
"lastUpdated": "1578048759",
"updateCount": 5,
"authorCount": 3
}
},
{
"id": "n_times_string",
"title": "n_times_string",
"type": "snippet",
"attributes": {
"fileName": "n_times_string.md",
"text": "Prints out the same string a defined number of times.\n\nRepeat the string `n` times, using the `*` operator.\n\n",
"codeBlocks": {
"code": "def n_times_string(s, n):\r\n return (s * n)",
"example": "n_times_string('py', 4) #'pypypypy'"
},
"tags": [
"string",
"beginner"
]
},
"meta": {
"hash": "8ecad31184e8b4e54f16a4107286d1d43cbc84608f19ccf472143a85c3a23908",
"firstSeen": "1569568045",
"lastUpdated": "1578048759",
"updateCount": 7,
"authorCount": 4
}
},
{
"id": "none",
"title": "none",
"type": "snippet",
"attributes": {
"fileName": "none.md",
"text": "Returns `False` if the provided function returns `True` for at least one element in the list, `True` otherwise.\n\nUse `all()` and `fn` to check if `fn` returns `False` for all the elements in the list.\n\n",
"codeBlocks": {
"code": "def none(lst, fn=lambda x: x):\n return all(not fn(x) for x in lst)",
"example": "none([0, 1, 2, 0], lambda x: x >= 2 ) # False\nnone([0, 0, 0]) # True"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "0dd3614b71e7a0b646a084e991eb6b4b2940492a14e6b8159d5d8a60a5abe04d",
"firstSeen": "1566305690",
"lastUpdated": "1569438934",
"updateCount": 5,
"authorCount": 3
}
},
{
"id": "offset",
"title": "offset",
"type": "snippet",
"attributes": {
"fileName": "offset.md",
"text": "Moves the specified amount of elements to the end of the list.\n\nUse `lst[offset:]` and `lst[:offset]` to get the two slices of the list and combine them before returning.\n\n",
"codeBlocks": {
"code": "def offset(lst, offset):\n return lst[offset:] + lst[:offset]",
"example": "offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]\noffset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "1be5e82e22a183c88351baa1cc14cab498e20dd17d6096de7915f6dcb16c76b9",
"firstSeen": "1566305595",
"lastUpdated": "1569151473",
"updateCount": 3,
"authorCount": 3
}
},
{
"id": "palindrome",
"title": "palindrome",
"type": "snippet",
"attributes": {
"fileName": "palindrome.md",
"text": "Returns `True` if the given string is a palindrome, `False` otherwise.\n\nUse `s.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string. \nThen, compare the new string with its reverse.\n\n",
"codeBlocks": {
"code": "from re import sub\n\ndef palindrome(s):\n s = sub('[\\W_]', '', s.lower())\n return s == s[::-1]",
"example": "palindrome('taco cat') # True"
},
"tags": [
"string",
"intermediate"
]
},
"meta": {
"hash": "e288ab1f10bef9dc735acdb5b6b6bf7f11dbe4381dea9a4710a797ffe15cf29a",
"firstSeen": "1517473199",
"lastUpdated": "1570502638",
"updateCount": 9,
"authorCount": 4
}
},
{
"id": "rads_to_degrees",
"title": "rads_to_degrees",
"type": "snippet",
"attributes": {
"fileName": "rads_to_degrees.md",
"text": "Converts an angle from radians to degrees.\n\nUse `math.pi` and the radian to degree formula to convert the angle from radians to degrees.\n\n",
"codeBlocks": {
"code": "from math import pi\n\ndef rads_to_degrees(rad):\n return (rad * 180.0) / math.pi",
"example": "from math import pi\nrads_to_degrees(math.pi / 2) # 90.0"
},
"tags": [
"math",
"beginner"
]
},
"meta": {
"hash": "b8397e39c3e1187f47c39402afb90f5d6108894ffddaac37e435803ee1274d3a",
"firstSeen": "1566305937",
"lastUpdated": "1578048779",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "reverse_string",
"title": "reverse_string",
"type": "snippet",
"attributes": {
"fileName": "reverse_string.md",
"text": "Returns the reverse of a string.\n\nUse string slicing to reverse the string.\n\n",
"codeBlocks": {
"code": "def reverse_string(s):\n return s[::-1]",
"example": "reverse_string(\"snippet\") #\"teppins\""
},
"tags": [
"string",
"beginner"
]
},
"meta": {
"hash": "beba9501ba22c14d92d1ea1c0be4686ad8e2e659b0945e066c1eb2a05d323d6c",
"firstSeen": "1570942024",
"lastUpdated": "1578048827",
"updateCount": 6,
"authorCount": 4
}
},
{
"id": "sample",
"title": "sample",
"type": "snippet",
"attributes": {
"fileName": "sample.md",
"text": "Returns a random element from a list.\n\nUse `random.randint()` to generate a random number that corresponds to an index in the list, return the element at that index.\n\n[`random.sample()`](https://docs.python.org/3/library/random.html#random.sample) provides similar functionality to this snippet.\n\n",
"codeBlocks": {
"code": "from random import randint\n\ndef sample(lst):\n return lst[randint(0, len(lst) - 1)]",
"example": "sample([3, 7, 9, 11]) # 9"
},
"tags": [
"list",
"random",
"beginner"
]
},
"meta": {
"hash": "0e0d74a26dfa80b19c0ba245235997c39cde44ff5385802cecc88f296c108e90",
"firstSeen": "1566306157",
"lastUpdated": "1578227114",
"updateCount": 5,
"authorCount": 3
}
},
{
"id": "shuffle",
"title": "shuffle",
"type": "snippet",
"attributes": {
"fileName": "shuffle.md",
"text": "Randomizes the order of the values of an list, returning a new list.\n\nUses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.\n\n[`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle) provides similar functionality to this snippet.\n\n",
"codeBlocks": {
"code": "from copy import deepcopy\nfrom random import randint\n\ndef shuffle(lst):\n temp_lst = deepcopy(lst)\n m = len(temp_lst)\n while (m):\n m -= 1\n i = randint(0, m)\n temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]\n return temp_lst",
"example": "foo = [1,2,3]\nshuffle(foo) # [2,3,1], foo = [1,2,3]"
},
"tags": [
"list",
"random",
"intermediate"
]
},
"meta": {
"hash": "817c98747813310506251815328e697f4032d8bab1ba87d3bfcc642b7b51d0cf",
"firstSeen": "1516355973",
"lastUpdated": "1578142820",
"updateCount": 15,
"authorCount": 5
}
},
{
"id": "similarity",
"title": "similarity",
"type": "snippet",
"attributes": {
"fileName": "similarity.md",
"text": "Returns a list of elements that exist in both lists.\n\nUse list comprehension on `a` to only keep values contained in both lists.\n\n",
"codeBlocks": {
"code": "def similarity(a, b):\n return [item for item in a if item in b]",
"example": "similarity([1, 2, 3], [1, 2, 4]) # [1, 2]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "51e5a4fc0b3376f24804b51f71c3daed109b1e60535aa39bca44c1918fedaacf",
"firstSeen": "1566306731",
"lastUpdated": "1566306731",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "snake",
"title": "snake",
"type": "snippet",
"attributes": {
"fileName": "snake.md",
"text": "Converts a string to snake case.\n\nBreak the string into words and combine them adding `_` as a separator, using a regexp.\n\n",
"codeBlocks": {
"code": "from re import sub\n\ndef snake(s):\n return '_'.join(\n sub('([A-Z][a-z]+)', r' \\1',\n sub('([A-Z]+)', r' \\1',\n s.replace('-', ' '))).split()).lower()",
"example": "snake('camelCase') # 'camel_case'\nsnake('some text') # 'some_text'\nsnake('some-mixed_string With spaces_underscores-and-hyphens') # 'some_mixed_string_with_spaces_underscores_and_hyphens'\nsnake('AllThe-small Things') # \"all_the_small_things\""
},
"tags": [
"string",
"regexp",
"intermediate"
]
},
"meta": {
"hash": "706341f0404965144fb066967ff6eda1d691b858decacbd1dfbba6759878b237",
"firstSeen": "1566367194",
"lastUpdated": "1578655914",
"updateCount": 14,
"authorCount": 7
}
},
{
"id": "some",
"title": "some",
"type": "snippet",
"attributes": {
"fileName": "some.md",
"text": "Returns `True` if the provided function returns `True` for at least one element in the list, `False` otherwise.\n\nUse `any()` in combination with `map()` and `fn` to check if `fn` returns `True` for any element in the list.\n\n",
"codeBlocks": {
"code": "def some(lst, fn=lambda x: x):\n return any(map(fn, lst))",
"example": "some([0, 1, 2, 0], lambda x: x >= 2 ) # True\nsome([0, 0, 1, 0]) # True"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "b104995e92213cbfeac2dce438e9d6f8fd13e18b8fb106789efa06f9285da2bb",
"firstSeen": "1566290550",
"lastUpdated": "1569155471",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "split_lines",
"title": "split_lines",
"type": "snippet",
"attributes": {
"fileName": "split_lines.md",
"text": "Splits a multiline string into a list of lines.\n\nUse `s.split()` and `'\\n'` to match line breaks and create a list.\n\n[`str.splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) provides similar functionality to this snippet.\n\n",
"codeBlocks": {
"code": "def split_lines(s):\n return s.split('\\n')",
"example": "split_lines('This\\nis a\\nmultiline\\nstring.\\n') # ['This', 'is a', 'multiline', 'string.' , '']"
},
"tags": [
"string",
"beginner"
]
},
"meta": {
"hash": "d3929f4b59663cac5b5f6bae84ee5a849b8ed291ffd80368025ab3c473f6a5b3",
"firstSeen": "1566306915",
"lastUpdated": "1578227131",
"updateCount": 8,
"authorCount": 5
}
},
{
"id": "spread",
"title": "spread",
"type": "snippet",
"attributes": {
"fileName": "spread.md",
"text": "Flattens a list, by spreading its elements into a new list.\n\nLoop over elements, use `list.extend()` if the element is a list, `list.append()` otherwise.\n\n",
"codeBlocks": {
"code": "def spread(arg):\n ret = []\n for i in arg:\n ret.extend(i) if isinstance(i, list) else ret.append(i)\n return ret",
"example": "spread([1, 2, 3, [4, 5, 6], [7], 8, 9]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "a483a7203d0ea1ceebbcbe05d50ad724798ebdb8c9786b4be46d671b03daebc8",
"firstSeen": "1515443885",
"lastUpdated": "1586278551",
"updateCount": 14,
"authorCount": 4
}
},
{
"id": "sum_by",
"title": "sum_by",
"type": "snippet",
"attributes": {
"fileName": "sum_by.md",
"text": "Returns the sum of a list, after mapping each element to a value using the provided function.\n\nUse `map()` with `fn` to map each element to a value using the provided function, use `sum()` to return the sum of the values.\n\n",
"codeBlocks": {
"code": "def sum_by(lst, fn):\n return sum(map(fn, lst))",
"example": "sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 20"
},
"tags": [
"math",
"list",
"function",
"beginner"
]
},
"meta": {
"hash": "2051bc61e1359b1fd9fb14defaac6e8014e8633a09de634f44172a6ac52568f5",
"firstSeen": "1566365404",
"lastUpdated": "1578048759",
"updateCount": 4,
"authorCount": 2
}
},
{
"id": "symmetric_difference",
"title": "symmetric_difference",
"type": "snippet",
"attributes": {
"fileName": "symmetric_difference.md",
"text": "Returns the symmetric difference between two iterables, without filtering out duplicate values.\n\nCreate a `set` from each list, then use list comprehension on each one to only keep values not contained in the previously created set of the other.\n\n",
"codeBlocks": {
"code": "def symmetric_difference(a, b):\n _a, _b = set(a), set(b)\n return [item for item in a if item not in _b] + [item for item in b if item not in _a]",
"example": "symmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "e5bb81e529740a7fbb9fe63eed33dc4ef390e7bc8c9c954a22ae3327f3d157ed",
"firstSeen": "1566365824",
"lastUpdated": "1566365824",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "symmetric_difference_by",
"title": "symmetric_difference_by",
"type": "snippet",
"attributes": {
"fileName": "symmetric_difference_by.md",
"text": "Returns the symmetric difference between two lists, after applying the provided function to each list element of both.\n\nCreate a `set` by applying `fn` to each element in every list, then use list comprehension in combination with `fn` on each one to only keep values not contained in the previously created set of the other.\n\n",
"codeBlocks": {
"code": "def symmetric_difference_by(a, b, fn):\n _a, _b = set(map(fn, a)), set(map(fn, b))\n return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a]",
"example": "from math import floor\nsymmetric_difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2, 3.4]"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "a3a978dbb2d7ffd0101b935484439b191fa432831f003faeefc05263eafc35e5",
"firstSeen": "1566365824",
"lastUpdated": "1566365824",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "tail",
"title": "tail",
"type": "snippet",
"attributes": {
"fileName": "tail.md",
"text": "Returns all elements in a list except for the first one.\n\nReturn `lst[1:]` if the list's length is more than `1`, otherwise, return the whole list.\n\n",
"codeBlocks": {
"code": "def tail(lst):\n return lst[1:] if len(lst) > 1 else lst",
"example": "tail([1, 2, 3]) # [2,3]\ntail([1]) # [1]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "d53c8932c4c9deebcd2f578b62b2a5f09a081885f848a2ea97721c15f2e7ded2",
"firstSeen": "1566299332",
"lastUpdated": "1578048873",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "take",
"title": "take",
"type": "snippet",
"attributes": {
"fileName": "take.md",
"text": "Returns a list with `n` elements removed from the beginning.\n\nUse slice notation to create a slice of the list with `n` elements taken from the beginning.\n\n",
"codeBlocks": {
"code": "def take(itr, n = 1):\r\n return itr[:n]",
"example": "take([1, 2, 3], 5) # [1, 2, 3]\r\ntake([1, 2, 3], 0) # []"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "ee77775f6d662576e60f839273bc23a1200d2e58d5f681ab8fc5a686b647bd81",
"firstSeen": "1584381164",
"lastUpdated": "1584381164",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "take_right",
"title": "take_right",
"type": "snippet",
"attributes": {
"fileName": "take_right.md",
"text": "Returns a list with `n` elements removed from the end.\n\nUse slice notation to create a slice of the list with `n` elements taken from the end.\n\n",
"codeBlocks": {
"code": "def take_right(itr, n = 1):\r\n return itr[-n:]",
"example": "take_right([1, 2, 3], 2) # [2, 3]\r\ntake_right([1, 2, 3]) # [3]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "5221a664a891ded456017072033baeb1bc25ee10e9556f64f09f6ebf0b5bf07b",
"firstSeen": "1584381164",
"lastUpdated": "1584381164",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "transpose",
"title": "transpose",
"type": "snippet",
"attributes": {
"fileName": "transpose.md",
"text": "Returns the transpose of a two-dimensional list.\n\nUse `*lst` to get the passed list as tuples.\nUse `zip()` in combination with `list()` to create the transpose of the given two-dimensional list.\n\n",
"codeBlocks": {
"code": "def transpose(lst):\n return list(zip(*lst))",
"example": "transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) # [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]"
},
"tags": [
"list",
"intermediate"
]
},
"meta": {
"hash": "d6148455c7451e290ad1edf5ac25bf79f8f20c56c829105322b3c4007d5ad20b",
"firstSeen": "1570517588",
"lastUpdated": "1578048759",
"updateCount": 5,
"authorCount": 3
}
},
{
"id": "unfold",
"title": "unfold",
"type": "snippet",
"attributes": {
"fileName": "unfold.md",
"text": "Builds a list, using an iterator function and an initial seed value.\n\nThe iterator function accepts one argument (`seed`) and must always return a list with two elements ([`value`, `nextSeed`]) or `False` to terminate.\nUse a generator function, `fn_generator`, that uses a `while` loop to call the iterator function and `yield` the `value` until it returns `False`.\nUse list comprehension to return the list that is produced by the generator, using the iterator function.\n\n",
"codeBlocks": {
"code": "def unfold(fn, seed):\n def fn_generator(val):\n while True: \n val = fn(val[1])\n if val == False: break\n yield val[0]\n return [i for i in fn_generator([None, seed])]",
"example": "f = lambda n: False if n > 50 else [-n, n + 10]\nunfold(f, 10) # [-10, -20, -30, -40, -50]"
},
"tags": [
"function",
"list",
"advanced"
]
},
"meta": {
"hash": "e9d027a02786f51db720328d695b20113c33fc8c96bbabb7d5d0fdcdf4993f9c",
"firstSeen": "1577989071",
"lastUpdated": "1577989071",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "union",
"title": "union",
"type": "snippet",
"attributes": {
"fileName": "union.md",
"text": "Returns every element that exists in any of the two lists once.\n\nCreate a `set` with all values of `a` and `b` and convert to a `list`.\n\n",
"codeBlocks": {
"code": "def union(a, b):\n return list(set(a + b))",
"example": "union([1, 2, 3], [4, 3, 2]) # [1,2,3,4]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "0402c6758ffea9463ef552eecdec587039543f67f74bf2c7208beca85be2ee81",
"firstSeen": "1566367839",
"lastUpdated": "1578048759",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "union_by",
"title": "union_by",
"type": "snippet",
"attributes": {
"fileName": "union_by.md",
"text": "Returns every element that exists in any of the two lists once, after applying the provided function to each element of both.\n\nCreate a `set` by applying `fn` to each element in `a`, then use list comprehension in combination with `fn` on `b` to only keep values not contained in the previously created set, `_a`.\nFinally, create a `set` from the previous result and `a` and transform it into a `list`\n\n",
"codeBlocks": {
"code": "def union_by(a, b, fn):\n _a = set(map(fn, a))\n return list(set(a + [item for item in b if fn(item) not in _a]))",
"example": "from math import floor\nunion_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]"
},
"tags": [
"list",
"function",
"intermediate"
]
},
"meta": {
"hash": "fe68011222e43bc49339c4b6204b14c9c61c2d16014ed3a5d007cd7629192ffa",
"firstSeen": "1566367839",
"lastUpdated": "1578048759",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "unique_elements",
"title": "unique_elements",
"type": "snippet",
"attributes": {
"fileName": "unique_elements.md",
"text": "Returns the unique elements in a given list.\n\nCreate a `set` from the list to discard duplicated values, then return a `list` from it.\n\n",
"codeBlocks": {
"code": "def unique_elements(li):\n return list(set(li))",
"example": "unique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4]"
},
"tags": [
"list",
"beginner"
]
},
"meta": {
"hash": "1f28461c8bbf4ce0195c756b2f013e519a43fbdef8b6a3640eafab2a6cb20bc9",
"firstSeen": "1539104479",
"lastUpdated": "1566289135",
"updateCount": 5,
"authorCount": 3
}
},
{
"id": "values_only",
"title": "values_only",
"type": "snippet",
"attributes": {
"fileName": "values_only.md",
"text": "Returns a flat list of all the values in a flat dictionary.\n\nUse `dict.values()` to return the values in the given dictionary.\nReturn a `list()` of the previous result.\n\n",
"codeBlocks": {
"code": "def values_only(flat_dict):\n return list(flat_dict.values())",
"example": "ages = {\n \"Peter\": 10,\n \"Isabel\": 11,\n \"Anna\": 9,\n}\nvalues_only(ages) # [10, 11, 9]"
},
"tags": [
"dictionary",
"list",
"beginner"
]
},
"meta": {
"hash": "ea3005a1cc4999d065fcf7141c14fd481f8384bc7d45ecf0eeaf04b6eb8adb66",
"firstSeen": "1522616191",
"lastUpdated": "1586278519",
"updateCount": 9,
"authorCount": 5
}
},
{
"id": "when",
"title": "when",
"type": "snippet",
"attributes": {
"fileName": "when.md",
"text": "Tests a value, `x`, against a `predicate` function, conditionally applying a function. \n\nCheck if the value of `predicate(x)` is `True` and if so return `when_true(x)`, otherwise return `x`.\n\n",
"codeBlocks": {
"code": "def when(predicate, when_true):\n return lambda x: when_true(x) if predicate(x) else x",
"example": "double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)\ndouble_even_numbers(2) # 4\ndouble_even_numbers(1) # 1"
},
"tags": [
"function",
"intermediate"
]
},
"meta": {
"hash": "8f04bf926446b8c1c73fe0127d3d9a59141d7287ea9e72e8fe4f71b1762f6049",
"firstSeen": "1577989545",
"lastUpdated": "1577989545",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "zip",
"title": "zip",
"type": "snippet",
"attributes": {
"fileName": "zip.md",
"text": "Creates a list of elements, grouped based on the position in the original lists.\n\nUse `max` combined with `list comprehension` to get the length of the longest list in the arguments. \nLoop for `max_length` times grouping elements. \nIf lengths of `lists` vary, use `fill_value` (defaults to `None`). \n\n[`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.\n\n",
"codeBlocks": {
"code": "def zip(*args, fill_value=None):\n max_length = max([len(lst) for lst in args])\n result = []\n for i in range(max_length):\n result.append([\n args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args))\n ])\n return result",
"example": "zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]\nzip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]\nzip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]"
},
"tags": [
"list",
"math",
"intermediate"
]
},
"meta": {
"hash": "a42a76e7a962aded1f6f30495095fe3c005be83d37f18e63285a3425184772ec",
"firstSeen": "1516462266",
"lastUpdated": "1578227158",
"updateCount": 19,
"authorCount": 6
}
}
],
"meta": {
"specification": "http://jsonapi.org/format/",
"type": "snippetArray",
"language": {
"short": "py",
"long": "Python"
}
}
}