Merge pull request #173 from 30-seconds/fix-snippet-problems

Fix snippet problems
This commit is contained in:
Angelos Chalaris
2020-01-03 13:12:09 +02:00
committed by GitHub
47 changed files with 106 additions and 143 deletions

View File

@ -3,7 +3,7 @@ title: all_equal
tags: list,beginner
---
Check if all elements in a list are equal.
Checks if all elements in a list are equal.
Use `[1:]` and `[:-1]` to compare all the values in the given list.

View File

@ -3,9 +3,9 @@ title: all_unique
tags: list,beginner
---
Returns `True` if all the values in a flat list are unique, `False` otherwise.
Returns `True` if all the values in a list are unique, `False` otherwise.
Use `set()` on the given list to remove duplicates, compare its length with the length of the list.
Use `set()` on the given list to remove duplicates, use `len()` to compare its length with the length of the list.
```py
def all_unique(lst):
@ -13,8 +13,8 @@ def all_unique(lst):
```
```py
x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 2, 3, 4, 5]
all_unique(x) # True
all_unique(y) # False
```
```

View File

@ -11,8 +11,8 @@ Use list comprehension and `enumerate()` to add elements to groups, based on `fi
```py
def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
[x for i, x in enumerate(lst) if filter[i] == True],
[x for i, x in enumerate(lst) if filter[i] == False]
]
```

View File

@ -17,5 +17,8 @@ def bifurcate_by(lst, fn):
```
```py
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b') # [ ['beep', 'boop', 'bar'], ['foo'] ]
bifurcate_by(
['beep', 'boop', 'foo', 'bar'],
lambda x: x[0] == 'b'
) # [ ['beep', 'boop', 'bar'], ['foo'] ]
```

View File

@ -10,16 +10,16 @@ Use `title()` to capitalize the first letter of each word convert the rest to lo
Finally, use `replace()` to remove spaces between words.
```py
import re
from re import sub
def camel(s):
s = re.sub(r"(_|-)+", " ", s).title().replace(" ", "")
s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
return s[0].lower() + s[1:]
```
```py
camel('some_database_field_name'); # 'someDatabaseFieldName'
camel('Some label that needs to be camelized'); # 'someLabelThatNeedsToBeCamelized'
camel('some-javascript-property'); # 'someJavascriptProperty'
camel('some-mixed_string with spaces_underscores-and-hyphens'); # 'someMixedStringWithSpacesUnderscoresAndHyphens'
camel('some_database_field_name') # 'someDatabaseFieldName'
camel('Some label that needs to be camelized') # 'someLabelThatNeedsToBeCamelized'
camel('some-javascript-property') # 'someJavascriptProperty'
camel('some-mixed_string with spaces_underscores-and-hyphens') # 'someMixedStringWithSpacesUnderscoresAndHyphens'
```

View File

@ -3,7 +3,7 @@ title: cast_list
tags: utility,list,beginner
---
Casts the provided value as an array if it's not one.
Casts the provided value as a list if it's not one.
Use `isinstance()` to check if the given value is enumerable and return it by using `list()` or encapsulated in a list accordingly.

View File

@ -14,10 +14,7 @@ def check_prop(fn, prop):
```py
check_age = check_prop(lambda x: x >= 18, 'age')
user = {
'name': 'Mark',
'age': 18
}
user = {'name': 'Mark', 'age': 18}
check_age(user) # True
```

View File

@ -19,5 +19,5 @@ def chunk(lst, size):
```
```py
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
chunk([1, 2, 3, 4, 5], 2) # [[1,2],[3,4],5]
```

View File

@ -10,7 +10,7 @@ Otherwise, return the nearest number in the range.
```py
def clamp_number(num,a,b):
return max(min(num, max(a,b)),min(a,b))
return max(min(num, max(a, b)), min(a, b))
```
```py

View File

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

View File

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

View File

@ -5,7 +5,7 @@ tags: function,intermediate
Curries a function.
Use `partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied.
Use `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied.
```py
from functools import partial
@ -16,7 +16,7 @@ def curry(fn, *args):
```py
add = lambda x, y: x + y
add10 = curry(sum, 10)
add10 = curry(add, 10)
add10(20) # 30
```

View File

@ -6,25 +6,14 @@ tags: list,recursion,intermediate
Deep flattens a list.
Use recursion.
Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it.
Use `list.extend()` with an empty list and the `spread` function to flatten a list.
Recursively flatten each element that is a list.
Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable.
If it is, apply `deep_flatten()` recursively, otherwise return `[lst]`.
```py
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
from collections.abc import Iterable
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
def deep_flatten(lst):
return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]
```
```py

View File

@ -8,10 +8,10 @@ Converts an angle from degrees to radians.
Use `math.pi` and the degrees to radians formula to convert the angle from degrees to radians.
```py
import math
from math import pi
def degrees_to_rads(deg):
return (deg * math.pi) / 180.0
return (deg * pi) / 180.0
```
```py

View File

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

View File

@ -15,6 +15,6 @@ def difference_by(a, b, fn):
```py
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
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 } ]
```
```

View File

@ -3,7 +3,7 @@ title: digitize
tags: math,list,beginner
---
Converts a number to an array of digits.
Converts a number to a list of digits.
Use `map()` combined with `int` on the string representation of `n` and return a list from the result.

View File

@ -9,7 +9,7 @@ Use `[nth-1::nth]` to create a new list that contains every nth element of the g
```py
def every_nth(lst, nth):
return lst[nth-1::nth]
return lst[nth - 1::nth]
```
```py

View File

@ -13,8 +13,7 @@ Throws an exception if `num` is a negative or a floating point number.
```py
def factorial(num):
if not ((num >= 0) and (num % 1 == 0)):
raise Exception(
f"Number( {num} ) can't be floating point or negative ")
raise Exception("Number can't be floating point or negative.")
return 1 if num == 0 else num * factorial(num - 1)
```

View File

@ -3,7 +3,7 @@ title: fibonacci
tags: math,list,intermediate
---
Generates an array, containing the Fibonacci sequence, up until the nth term.
Generates a list, containing the Fibonacci sequence, up until the nth term.
Starting with `0` and `1`, use `list.append()` to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches `n`.
If `n` is less or equal to `0`, return a list containing `0`.

View File

@ -5,16 +5,16 @@ tags: math,beginner
Calculates the greatest common divisor of a list of numbers.
Use `reduce()` and `math.gcd` over the given list.
Use `functools.reduce()` and `math.gcd()` over the given list.
```py
from functools import reduce
import math
from math import gcd
def gcd(numbers):
return reduce(math.gcd, numbers)
return reduce(gcd, numbers)
```
```py
gcd([8,36,28]) # 4
```
gcd([8, 36, 28]) # 4
```

View File

@ -10,11 +10,11 @@ Use list comprehension to map each element to the appropriate `key`.
```py
def group_by(lst, fn):
return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}
return {key : [el for el in lst if fn(el) == key] for key in map(fn, lst)}
```
```py
import math
group_by([6.1, 4.2, 6.3], math.floor) # {4: [4.2], 6: [6.1, 6.3]}
from math import floor
group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}
```

View File

@ -13,8 +13,8 @@ def has_duplicates(lst):
```
```py
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
x = [1, 2, 3, 4, 5, 5]
y = [1, 2, 3, 4, 5]
has_duplicates(x) # True
has_duplicates(y) # False
```

View File

@ -13,5 +13,5 @@ def head(lst):
```
```py
head([1, 2, 3]); # 1
head([1, 2, 3]) # 1
```

View File

@ -10,14 +10,12 @@ If the second parameter, `end`, is not specified, the range is considered to be
```py
def in_range(n, start, end = 0):
if (start > end):
end, start = start, end
return start <= n <= end
return start <= n <= end if end >= start else end <= n <= start
```
```py
in_range(3, 2, 5); # True
in_range(3, 4); # True
in_range(2, 3, 5); # False
in_range(3, 2); # False
in_range(3, 2, 5) # True
in_range(3, 4) # True
in_range(2, 3, 5) # False
in_range(3, 2) # False
```

View File

@ -13,5 +13,5 @@ def initial(lst):
```
```py
initial([1, 2, 3]); # [1,2]
initial([1, 2, 3]) # [1,2]
```

View File

@ -10,12 +10,12 @@ Omit `start` to use the default value of `0`.
Omit `step` to use the default value of `1`.
```py
def initialize_list_with_range(end, start = 0, step = 1):
def initialize_list_with_range(end, start=0, step=1):
return list(range(start, end + 1, step))
```
```py
initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]
initialize_list_with_range(7,3) # [3, 4, 5, 6, 7]
initialize_list_with_range(9,0,2) # [0, 2, 4, 6, 8]
initialize_list_with_range(7, 3) # [3, 4, 5, 6, 7]
initialize_list_with_range(9, 0, 2) # [0, 2, 4, 6, 8]
```

View File

@ -12,11 +12,7 @@ Use `sorted()` on both strings and compare the results.
```py
def is_anagram(s1, s2):
_str1, _str2 = s1.replace(" ", ""), s2.replace(" ", "")
if len(_str1) != len(_str2):
return False
else:
return sorted(_str1.lower()) == sorted(_str2.lower())
return False if len(_str1) != len(_str2) else sorted(_str1.lower()) == sorted(_str2.lower())
```
```py

View File

@ -8,18 +8,19 @@ Converts a string to kebab case.
Break the string into words and combine them adding `-` as a separator, using a regexp.
```py
import re
from re import sub
def kebab(s):
return re.sub(r"(\s|_|-)+","-",
re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: mo.group(0).lower(), s)
)
return sub(
r"(\s|_|-)+","-",
sub(
r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: mo.group(0).lower(), s))
```
```py
kebab('camelCase'); # 'camel-case'
kebab('some text'); # 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens'); # 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things'); # "all-the-small-things"
kebab('camelCase') # 'camel-case'
kebab('some text') # 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens') # 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things') # "all-the-small-things"
```

View File

@ -3,35 +3,19 @@ title: lcm
tags: math,list,recursion,advanced
---
Returns the least common multiple of two or more numbers.
Returns the least common multiple of a list of numbers.
Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it.
Use `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple.
Use `functools.reduce()`, `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` over the given list.
```py
from functools import reduce
import math
from math import gcd
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def lcm(*args):
numbers = []
numbers.extend(spread(list(args)))
def _lcm(x, y):
return int(x * y / math.gcd(x, y))
return reduce((lambda x, y: _lcm(x, y)), numbers)
def lcm(numbers):
return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers)
```
```py
lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60
```
lcm([12, 7]) # 84
lcm([1, 3, 4, 5]) # 60
```

View File

@ -10,7 +10,7 @@ Use `max()` with `len` as the `key` to return the item with the greatest length.
```py
def longest_item(*args):
return max(args, key = len)
return max(args, key=len)
```
```py

View File

@ -9,7 +9,7 @@ Use `map()` with `fn` to map each element to a value using the provided function
```py
def max_by(lst, fn):
return max(map(fn,lst))
return max(map(fn, lst))
```
```py

View File

@ -9,7 +9,7 @@ Use `map()` with `fn` to map each element to a value using the provided function
```py
def min_by(lst, fn):
return min(map(fn,lst))
return min(map(fn, lst))
```
```py

View File

@ -9,9 +9,9 @@ Use `set(list)` to get the unique values in the `list` combined with `max()` to
```py
def most_frequent(list):
return max(set(list), key = list.count)
return max(set(list), key=list.count)
```
```py
most_frequent([1,2,1,2,3,2,1,4,2]) #2
most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2
```

View File

@ -14,5 +14,4 @@ def n_times_string(s, n):
```py
n_times_string('py', 4) #'pypypypy'
```
```

View File

@ -8,13 +8,13 @@ Converts an angle from radians to degrees.
Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees.
```py
import math
from math import pi
def rads_to_degrees(rad):
return (rad * 180.0) / math.pi
```
```py
import math
from math import pi
rads_to_degrees(math.pi / 2) # 90.0
```

View File

@ -8,8 +8,8 @@ Returns the reverse of a string.
Use string slicing to reverse the string.
```py
def reverse_string(string):
return string[::-1]
def reverse_string(s):
return s[::-1]
```
```py

View File

@ -3,9 +3,9 @@ title: sample
tags: list,random,beginner
---
Returns a random element from an array.
Returns a random element from a list.
Use `randint()` to generate a random number that corresponds to an index in the list, return the element at that index.
Use `random.randint()` to generate a random number that corresponds to an index in the list, return the element at that index.
```py
from random import randint

View File

@ -23,5 +23,5 @@ def shuffle(lst):
```py
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
shuffle(foo) # [2,3,1], foo = [1,2,3]
```

View File

@ -8,11 +8,12 @@ Converts a string to snake case.
Break the string into words and combine them adding `_` as a separator, using a regexp.
```py
import re
from re import sub
def snake(s):
return '_'.join(re.sub('([A-Z][a-z]+)', r' \1',
re.sub('([A-Z]+)', r' \1',
return '_'.join(
sub('([A-Z][a-z]+)', r' \1',
sub('([A-Z]+)', r' \1',
s.replace('-', ' '))).split()).lower()
```

View File

@ -11,13 +11,10 @@ Loop over elements, use `list.extend()` if the element is a list, `list.append()
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
ret.extend(i) if isinstance(i, list) else ret.append(i)
return ret
```
```py
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
```
spread([1, 2, 3, [4, 5, 6], [7], 8, 9]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

View File

@ -9,7 +9,7 @@ Use `map()` with `fn` to map each element to a value using the provided function
```py
def sum_by(lst, fn):
return sum(map(fn,lst))
return sum(map(fn, lst))
```
```py

View File

@ -13,6 +13,6 @@ def tail(lst):
```
```py
tail([1, 2, 3]); # [2,3]
tail([1]); # [1]
tail([1, 2, 3]) # [2,3]
tail([1]) # [1]
```

View File

@ -10,7 +10,7 @@ Use `zip()` in combination with `list()` to create the transpose of the given tw
```py
def transpose(lst):
return list(zip(*lst))
return list(zip(*lst))
```
```py

View File

@ -8,7 +8,7 @@ Returns every element that exists in any of the two lists once.
Create a `set` with all values of `a` and `b` and convert to a `list`.
```py
def union(a,b):
def union(a, b):
return list(set(a + b))
```

View File

@ -9,7 +9,7 @@ Create a `set` by applying `fn` to each element in `a`, then use list comprehens
Finally, create a `set` from the previous result and `a` and transform it into a `list`
```py
def union_by(a,b,fn):
def union_by(a, b, fn):
_a = set(map(fn, a))
return list(set(a + [item for item in b if fn(item) not in _a]))
```
@ -17,4 +17,4 @@ def union_by(a,b,fn):
```py
from math import floor
union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]
```
```

View File

@ -5,7 +5,6 @@ tags: list,math,intermediate
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.
Loop for `max_length` times grouping elements.
If lengths of `lists` vary, use `fill_value` (defaults to `None`).