diff --git a/snippets/all_unique.md b/snippets/all_unique.md index 5f161525b..097b22310 100644 --- a/snippets/all_unique.md +++ b/snippets/all_unique.md @@ -1,17 +1,18 @@ --- title: all_unique -tags: list +tags: list,beginner --- -Checks a flat list for all unique values. Returns True if list values are all unique and False if list values aren't all unique. -This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list. +Returns `True` if all the values in a flat list are unique, `False` otherwise. -``` python +Use `set()` on the given list to remove duplicates, compare its length with the length of the list. + +```py def all_unique(lst): return len(lst) == len(set(lst)) ``` -``` python +```py x = [1,2,3,4,5,6] y = [1,2,2,3,4,5] all_unique(x) # True diff --git a/snippets/average.md b/snippets/average.md index 0b18b501b..0fda74d5c 100644 --- a/snippets/average.md +++ b/snippets/average.md @@ -8,12 +8,12 @@ Returns the average of two or more numbers. Takes the sum of all the `args` and divides it by `len(args)`. The second argument `0.0` in sum is to handle floating point division in `python3`. -```python +```py def average(*args): return sum(args, 0.0) / len(args) ``` -``` python +```py average(*[1, 2, 3]) # 2.0 average(1, 2, 3) # 2.0 ``` diff --git a/snippets/bubble_sort.md b/snippets/bubble_sort.md index 292b0a2e7..002a3a3d7 100644 --- a/snippets/bubble_sort.md +++ b/snippets/bubble_sort.md @@ -5,7 +5,7 @@ tags: list Bubble_sort uses the technique of comparing and swapping -```python +```py def bubble_sort(lst): for passnum in range(len(lst) - 1, 0, -1): for i in range(passnum): @@ -14,7 +14,7 @@ def bubble_sort(lst): ``` -```python +```py lst = [54,26,93,17,77,31,44,55,20] bubble_sort(lst) print("sorted %s" %lst) # [17,20,26,31,44,54,55,77,91] diff --git a/snippets/byte_size.md b/snippets/byte_size.md index 73e64b2a6..7cdc81c0f 100644 --- a/snippets/byte_size.md +++ b/snippets/byte_size.md @@ -6,12 +6,12 @@ Returns the length of a string in bytes. `utf-8` encodes a given string, then `len` finds the length of the encoded string. -```python +```py def byte_size(string): return(len(string.encode('utf-8'))) ``` -```python +```py byte_size('😀') # 4 byte_size('Hello World') # 11 ``` diff --git a/snippets/capitalize.md b/snippets/capitalize.md index 52c8e1f25..2c65e007f 100644 --- a/snippets/capitalize.md +++ b/snippets/capitalize.md @@ -6,12 +6,12 @@ Capitalizes the first letter of a string. Capitalizes the first letter of the string and then adds 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. -```python +```py def capitalize(string, lower_rest=False): return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) ``` -```python +```py capitalize('fooBar') # 'FooBar' capitalize('fooBar', True) # 'Foobar' ``` \ No newline at end of file diff --git a/snippets/capitalize_every_word.md b/snippets/capitalize_every_word.md index 3c9882206..d734b6f62 100644 --- a/snippets/capitalize_every_word.md +++ b/snippets/capitalize_every_word.md @@ -6,11 +6,11 @@ Capitalizes the first letter of every word in a string. Uses `str.title` to capitalize first letter of every word in the string. -```python +```py def capitalize_every_word(string): return string.title() ``` -```python +```py capitalize_every_word('hello world!') # 'Hello World!' ``` \ No newline at end of file diff --git a/snippets/chunk.md b/snippets/chunk.md index c80662acf..a998fa95b 100644 --- a/snippets/chunk.md +++ b/snippets/chunk.md @@ -6,7 +6,7 @@ Chunks an list into smaller lists of a specified size. Uses `range` to create a list of desired size. Then use `map` on this list and fill it with splices of `lst`. -```python +```py from math import ceil @@ -16,6 +16,6 @@ def chunk(lst, size): list(range(0, ceil(len(lst) / size))))) ``` -``` python +```py chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] ``` diff --git a/snippets/compact.md b/snippets/compact.md index 64aff2941..38186b48e 100644 --- a/snippets/compact.md +++ b/snippets/compact.md @@ -6,11 +6,11 @@ Removes falsey values from a list. Use `filter()` to filter out falsey values (False, None, 0, and ""). -```python +```py def compact(lst): return list(filter(bool, lst)) ``` -``` python +```py compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] ``` diff --git a/snippets/count_by.md b/snippets/count_by.md index beb29f8ca..e15e431a4 100644 --- a/snippets/count_by.md +++ b/snippets/count_by.md @@ -8,7 +8,7 @@ Groups the elements of a list based on the given function and returns the count Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs. -```python +```py def count_by(arr, fn=lambda x: x): key = {} for el in map(fn, arr): @@ -17,7 +17,7 @@ def count_by(arr, fn=lambda x: x): return key ``` -``` python +```py from math import floor count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2} count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1} diff --git a/snippets/count_occurences.md b/snippets/count_occurences.md index 7db32d840..87c5bb2be 100644 --- a/snippets/count_occurences.md +++ b/snippets/count_occurences.md @@ -8,11 +8,11 @@ Counts the occurrences of a value in a list. Uses the list comprehension to increment a counter each time you encounter the specific value inside the list. -```python +```py def count_occurrences(lst, val): return len([x for x in lst if x == val and type(x) == type(val)]) ``` -```python +```py count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 ``` diff --git a/snippets/count_vowels.md b/snippets/count_vowels.md index 4029ea98c..8198d120c 100644 --- a/snippets/count_vowels.md +++ b/snippets/count_vowels.md @@ -6,7 +6,7 @@ Retuns `number` of vowels in provided `string`. Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a string. -```python +```py import re def count_vowels(str): diff --git a/snippets/decapitalize.md b/snippets/decapitalize.md index a506fa5fa..cb5e53fca 100644 --- a/snippets/decapitalize.md +++ b/snippets/decapitalize.md @@ -6,12 +6,12 @@ Decapitalizes the first letter of a string. Decapitalizes the first letter of the string and then adds 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. -```python +```py def decapitalize(string, upper_rest=False): return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) ``` -```python +```py decapitalize('FooBar') # 'fooBar' decapitalize('FooBar', True) # 'fOOBAR' ``` \ No newline at end of file diff --git a/snippets/deep_flatten.md b/snippets/deep_flatten.md index 87860aff3..8a148fe1b 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -6,7 +6,7 @@ Deep flattens a list. Use recursion. Use `list.extend()` with an empty list (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list. -```python +```py def spread(arg): ret = [] for i in arg: @@ -24,6 +24,6 @@ def deep_flatten(lst): return result ``` -```python +```py deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] ``` diff --git a/snippets/difference.md b/snippets/difference.md index b19b063c5..afeb8cbcd 100644 --- a/snippets/difference.md +++ b/snippets/difference.md @@ -6,11 +6,11 @@ Returns the difference between two iterables. Use list comprehension to only keep values not contained in `b`. -```python +```py def difference(a, b): _b = set(b) return [item for item in a if item not in _b] ``` -``` python +```py difference([1, 2, 3], [1, 2, 4]) # [3] ``` diff --git a/snippets/difference_by.md b/snippets/difference_by.md index 96ce12e08..5fae2a2f6 100644 --- a/snippets/difference_by.md +++ b/snippets/difference_by.md @@ -6,13 +6,13 @@ Returns the difference between two list, after applying the provided function to 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`. -```python +```py def difference_by(a, b, fn): b = set(map(fn, b)) return [item for item in a if fn(item) not in b] ``` -```python +```py from math import floor difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2] difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ] diff --git a/snippets/factorial.md b/snippets/factorial.md index abbac44a2..bfb2368a6 100644 --- a/snippets/factorial.md +++ b/snippets/factorial.md @@ -6,13 +6,13 @@ Calculates the factorial of a number. Use recursion. If `num` is less than or equal to `1`, return `1`. Otherwise, return the product of `num` and the factorial of `num - 1`. Throws an exception if `num` is a negative or a floating point number. -```python +```py def factorial(num): if not ((num >= 0) & (num % 1 == 0)): raise Exception( f"Number( {num} ) can't be floating point or negative ") return 1 if num == 0 else num * factorial(num - 1) ``` -``` python +```py factorial(6) # 720 ``` diff --git a/snippets/fermat_test.md b/snippets/fermat_test.md index 112d1d9ed..b97e9c29f 100644 --- a/snippets/fermat_test.md +++ b/snippets/fermat_test.md @@ -9,7 +9,7 @@ First, it picks the number `A` in range `1`..`(n-1)`, then it checks if `A` to t If not, the number is not prime, else it's pseudoprime with probability 1/2. Applying this test `k `times we have probability `1/(2^k)`. For example, if the number passes the test `10` times, we have probability `0.00098`. -``` python +```py from random import randint @@ -24,7 +24,7 @@ def fermat_test(n, k=100): ``` -``` python +```py fermat_test(0) # False fermat_test(1) # False fermat_test(561) # False diff --git a/snippets/fibonacci.md b/snippets/fibonacci.md index 7b5b4e68a..9b0167e15 100644 --- a/snippets/fibonacci.md +++ b/snippets/fibonacci.md @@ -6,7 +6,7 @@ Generates an array, containing the Fibonacci sequence, up until the nth term. Starting with 0 and 1, adds the sum of the last two numbers of the list to the end of the list using ```list.append()``` until the length of the list reaches n. If the given nth value is 0 or less, the method will just return a list containing 0. -``` python +```py def fibonacci(n): if n <= 0: return [0] @@ -20,6 +20,6 @@ def fibonacci(n): return sequence ``` -``` python +```py fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13] ``` diff --git a/snippets/fibonacci_until_num.md b/snippets/fibonacci_until_num.md index 5402662d4..cdce04c9a 100644 --- a/snippets/fibonacci_until_num.md +++ b/snippets/fibonacci_until_num.md @@ -7,14 +7,14 @@ Returns the n-th term in a Fibonnaci sequence that starts with 1 A term in a Fibonnaci sequence is the sum of the two previous terms. This function recursively calls the function to find the n-th term. -``` python +```py def fibonacci_until_num(n): if n < 3: return 1 return fibonacci_until_num(n - 2) + fibonacci_until_num(n - 1) ``` -``` python +```py fibonnaci_until_num(5) # 5 fibonnaci_until_num(15) # 610 ``` diff --git a/snippets/gcd.md b/snippets/gcd.md index 01ec425b1..739f3d11e 100644 --- a/snippets/gcd.md +++ b/snippets/gcd.md @@ -6,7 +6,7 @@ Calculates the greatest common divisor of a list of numbers. Uses the reduce function from the inbuilt module `functools`. Also uses the `math.gcd` function over a list. -```python +```py from functools import reduce import math @@ -14,6 +14,6 @@ def gcd(numbers): return reduce(math.gcd, numbers) ``` -``` python +```py gcd([8,36,28]) # 4 ``` \ No newline at end of file diff --git a/snippets/has_duplicates.md b/snippets/has_duplicates.md index 8a829fb37..c8652828b 100644 --- a/snippets/has_duplicates.md +++ b/snippets/has_duplicates.md @@ -6,12 +6,12 @@ Checks a flat list for duplicate values. Returns True if duplicate values exist This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list. -``` python +```py def has_duplicates(lst): return len(lst) != len(set(lst)) ``` -``` python +```py x = [1,2,3,4,5,5] y = [1,2,3,4,5] has_duplicates(x) # True diff --git a/snippets/insertion_sort.md b/snippets/insertion_sort.md index 0bd7af75a..3584dd029 100644 --- a/snippets/insertion_sort.md +++ b/snippets/insertion_sort.md @@ -4,7 +4,7 @@ tags: list --- On a very basic level, an insertion sort algorithm contains the logic of shifting around and inserting elements in order to sort an unordered list of any size. The way that it goes about inserting elements, however, is what makes insertion sort so very interesting! -```python +```py def insertion_sort(lst): for i in range(1, len(lst)): @@ -16,7 +16,7 @@ def insertion_sort(lst): lst[j + 1] = key ``` -```python +```py lst = [7,4,9,2,6,3] insertionsort(lst) print('Sorted %s' %lst) # sorted [2, 3, 4, 6, 7, 9] diff --git a/snippets/is_anagram.md b/snippets/is_anagram.md index f6c14f914..48bcc0c32 100644 --- a/snippets/is_anagram.md +++ b/snippets/is_anagram.md @@ -7,7 +7,7 @@ Determine if 2 strings are anagrams. Returns true if 2 strings are anagrams of each other, false otherwise. Capital letters and whitespaces are ignored. -``` python +```py def is_anagram(str1, str2): str1, str2 = str1.replace(" ", ""), str2.replace(" ", "") @@ -17,6 +17,6 @@ def is_anagram(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) ``` -``` python +```py is_anagram("anagram", "Nag a ram") # True ``` diff --git a/snippets/is_lower_case.md b/snippets/is_lower_case.md index da9341288..cecdd0874 100644 --- a/snippets/is_lower_case.md +++ b/snippets/is_lower_case.md @@ -6,12 +6,12 @@ Checks if a string is lower case. Convert the given string to lower case, using `str.lower()` method and compare it to the original. -```python +```py def is_lower_case(string): return string == string.lower() ``` -```python +```py is_lower_case('abc') # True is_lower_case('a3@$') # True is_lower_case('Ab4') # False diff --git a/snippets/is_upper_case.md b/snippets/is_upper_case.md index 00554c297..5bc7405f6 100644 --- a/snippets/is_upper_case.md +++ b/snippets/is_upper_case.md @@ -6,12 +6,12 @@ Checks if a string is upper case. Convert the given string to upper case, using `str.upper()` method and compare it to the original. -```python +```py def is_upper_case(string): return string == string.upper() ``` -```python +```py is_upper_case('ABC') # True is_upper_case('a3@$') # False is_upper_case('aB4') # False diff --git a/snippets/keys_only.md b/snippets/keys_only.md index 8ca10d566..ff3aec32a 100644 --- a/snippets/keys_only.md +++ b/snippets/keys_only.md @@ -6,12 +6,12 @@ Function which accepts a dictionary of key value pairs and returns a new flat li Uses the .keys() method of "dict" objects. dict.keys() returns a view object that displays a list of all the keys. Then, list(dict.keys()) returns a list that stores all the keys of a dict. -``` python +```py def keys_only(flat_dict): return list(flat_dict.keys()) ``` -``` python +```py ages = { "Peter": 10, "Isabel": 11, diff --git a/snippets/lcm.md b/snippets/lcm.md index bdbf77938..92752479b 100644 --- a/snippets/lcm.md +++ b/snippets/lcm.md @@ -8,7 +8,7 @@ Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists. -```python +```py from functools import reduce @@ -36,7 +36,7 @@ def lcm(*args): ``` -``` python +```py lcm(12, 7) # 84 lcm([1, 3, 4], 5) # 60 ``` \ No newline at end of file diff --git a/snippets/max_n.md b/snippets/max_n.md index 81e3e5afa..76bbcdfe9 100644 --- a/snippets/max_n.md +++ b/snippets/max_n.md @@ -6,12 +6,12 @@ Returns the `n` maximum elements from the provided list. If `n` is greater than Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order and then use `list.reverse()` reverse it to make it descending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element list -```python +```py def max_n(lst, n=1, reverse=True): return sorted(lst, reverse=reverse)[:n] ``` -```python +```py max_n([1, 2, 3]) # [3] max_n([1, 2, 3], 2) # [3,2] ``` diff --git a/snippets/min_n.md b/snippets/min_n.md index 6b3326a03..d88f45847 100644 --- a/snippets/min_n.md +++ b/snippets/min_n.md @@ -6,7 +6,7 @@ Returns the `n` minimum elements from the provided list. If `n` is greater than Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element list -```python +```py from copy import deepcopy @@ -16,7 +16,7 @@ def min_n(lst, n=1): return numbers[:n] ``` -```python +```py min_n([1, 2, 3]) # [1] min_n([1, 2, 3], 2) # [1,2] ``` diff --git a/snippets/palindrome.md b/snippets/palindrome.md index 593208c6c..b4b8b2336 100644 --- a/snippets/palindrome.md +++ b/snippets/palindrome.md @@ -6,12 +6,12 @@ Returns `True` if the given string is a palindrome, `False` otherwise. Convert string `str.lower()` and use `re.sub` to remove non-alphanumeric characters from it. Then compare the new string to the reversed. -```python +```py def palindrome(string): from re import sub s = sub('[\W_]', '', string.lower()) return s == s[::-1] ``` -```python +```py palindrome('taco cat') # True ``` \ No newline at end of file diff --git a/snippets/shuffle.md b/snippets/shuffle.md index 6b7fe1362..7328f1aa2 100644 --- a/snippets/shuffle.md +++ b/snippets/shuffle.md @@ -8,7 +8,7 @@ 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. -```python +```py from copy import deepcopy from random import randint @@ -23,7 +23,7 @@ def shuffle(lst): return temp_lst ``` -``` python +```py foo = [1,2,3] shuffle(foo) # [2,3,1] , foo = [1,2,3] ``` diff --git a/snippets/spread.md b/snippets/spread.md index e261aa6a3..ae52aeb46 100644 --- a/snippets/spread.md +++ b/snippets/spread.md @@ -4,7 +4,7 @@ tags: list --- Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. -```python +```py def spread(arg): ret = [] for i in arg: @@ -16,6 +16,6 @@ def spread(arg): ``` -```python +```py spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] ``` \ No newline at end of file diff --git a/snippets/unique_elements.md b/snippets/unique_elements.md index 8b9b80a42..f18a038e2 100644 --- a/snippets/unique_elements.md +++ b/snippets/unique_elements.md @@ -6,11 +6,11 @@ Returns the unique elements in a given list. The given `list` is first converted to a `set` using the `set()` function. By definition, a `set` cannot have duplicate elements. So, the duplicate elements are automatically removed. Before returning, we convert it back to a `list` -``` python +```py def unique_elements(li): return list(set(li)) ``` -``` python +```py unique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4] ``` diff --git a/snippets/values_only.md b/snippets/values_only.md index 8a4d7b94f..9c56b1688 100644 --- a/snippets/values_only.md +++ b/snippets/values_only.md @@ -6,7 +6,7 @@ Function which accepts a dictionary of key value pairs and returns a new flat li Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not nested data-structures. -``` python +```py def values_only(dict): lst = [] for k, v in dict.items(): @@ -14,7 +14,7 @@ def values_only(dict): return lst ``` -``` python +```py ages = { "Peter": 10, "Isabel": 11, diff --git a/snippets/zip.md b/snippets/zip.md index 516cb7c49..fb948ec94 100644 --- a/snippets/zip.md +++ b/snippets/zip.md @@ -8,7 +8,7 @@ Creates a list of elements, grouped based on the position in the original lists. Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`. -```python +```py def zip(*args, fillvalue=None): max_length = max([len(lst) for lst in args]) result = [] @@ -19,7 +19,7 @@ def zip(*args, fillvalue=None): return result ``` -``` python +```py zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]] zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]] zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]