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.
-
-
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)
-
-
factorial(6) # 720
-
-
-
gcd
-
ℹmath.gcd works with only two numbers
-
Calculates the greatest common divisor between two or more numbers/lists.
-
The helperGcdfunction uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.
-
Uses the reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.
-
-
from functools import reduce
-
-
-def spread(arg):
- ret = []
- for i in arg:
- if isinstance(i, list):
- ret.extend(i)
- else:
- ret.append(i)
- return ret
-
-
-def gcd(*args):
- numbers = []
- numbers.extend(spread(list(args)))
-
- def _gcd(x, y):
- return x if not y else gcd(y, x % y)
-
- return reduce((lambda x, y: _gcd(x, y)), numbers)
-
-
gcd(8,36) # 4
-
-
-
lcm
-
Returns the least common multiple of two or more numbers.
-
Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.
-
Uses reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.
-
-
from functools import reduce
-
-
-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 _gcd(x, y):
- return x if not y else gcd(y, x % y)
-
- def _lcm(x, y):
- return x * y / _gcd(x, y)
-
- return reduce((lambda x, y: _lcm(x, y)), numbers)
-
-
lcm(12, 7) # 84
-lcm([1, 3, 4], 5) # 60
-
-
-
max_n
-
Returns the n maximum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in descending order).
-
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 array
Returns the n minimum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).
-
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 array
Uses the reduce functin from built-in module functools to increment a counter each time you encounter the specific value inside the list.
-
-
def count_occurences(arr, val):
- return reduce(
- (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
- arr)
-
-
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
-
-
-
deep_flatten
-
Deep flattens a list.
-
Use recursion. Use list.extend() with an empty array (result) and the spread function to flatten a list. Recursively flatten each element that is a list.
-
-
def spread(arg):
- ret = []
- for i in arg:
- if isinstance(i, list):
- ret.extend(i)
- else:
- ret.append(i)
- return ret
-
-
-def deep_flatten(arr):
- result = []
- result.extend(
- spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
- return result
-
-
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
-
-
-
difference
-
Returns the difference between two arrays.
-
Create a set from b, then use list comprehension to only keep values not contained in b
-
-
def difference(a, b):
- b = set(b)
- return [item for item in a if item not in b]
-
-
difference([1, 2, 3], [1, 2, 4]) # [3]
-
-
-
shuffle
-
ℹ The same algorithm is already implemented via random.shuffle.
-
Randomizes the order of the values of an list, returning a new list.
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.
-
-
def zip(*args, fillvalue=None):
- max_length = max([len(arr) for arr in args])
- result = []
- for i in range(max_length):
- result.append([
- args[k][i] if i < len(args[k]) else None for k in range(len(args))
- ])
- return result
Returns the difference between two list, after applying the provided function to each list element of both.
-
Create a set by applying fn to each element in b, then use list comprehension in combination with fn on a to only keep values not contained in the previously created set.
-
-
def difference_by(a, b, fn):
- b = set(map(fn, b))
- return [item for item in a if fn(item) not in b]
Capitalizes the fist letter of the sring 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.
Decapitalizes the fist letter of the sring 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.
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.
+
+
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)
+
+
factorial(6) # 720
+
+
+
gcd
+
ℹmath.gcd works with only two numbers
+
Calculates the greatest common divisor between two or more numbers/lists.
+
The helperGcdfunction uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.
+
Uses the reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.
+
+
from functools import reduce
+
+
+def spread(arg):
+ ret = []
+ for i in arg:
+ if isinstance(i, list):
+ ret.extend(i)
+ else:
+ ret.append(i)
+ return ret
+
+
+def gcd(*args):
+ numbers = []
+ numbers.extend(spread(list(args)))
+
+ def _gcd(x, y):
+ return x if not y else gcd(y, x % y)
+
+ return reduce((lambda x, y: _gcd(x, y)), numbers)
+
+
gcd(8,36) # 4
+
+
+
lcm
+
Returns the least common multiple of two or more numbers.
+
Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.
+
Uses reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.
+
+
from functools import reduce
+
+
+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 _gcd(x, y):
+ return x if not y else _gcd(y, x % y)
+
+ def _lcm(x, y):
+ return x * y / _gcd(x, y)
+
+ return reduce((lambda x, y: _lcm(x, y)), numbers)
+
+
lcm(12, 7) # 84
+lcm([1, 3, 4], 5) # 60
+
+
+
max_n
+
Returns the n maximum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in descending order).
+
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 array
Returns the n minimum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).
+
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 array
Uses the reduce functin from built-in module functools to increment a counter each time you encounter the specific value inside the list.
+
+
from functools import reduce
+
+
+def count_occurences(arr, val):
+ return reduce(
+ (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
+ arr)
+
+
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
+
+
+
deep_flatten
+
Deep flattens a list.
+
Use recursion. Use list.extend() with an empty array (result) and the spread function to flatten a list. Recursively flatten each element that is a list.
+
+
def spread(arg):
+ ret = []
+ for i in arg:
+ if isinstance(i, list):
+ ret.extend(i)
+ else:
+ ret.append(i)
+ return ret
+
+
+def deep_flatten(arr):
+ result = []
+ result.extend(
+ spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, arr))))
+ return result
+
+
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
+
+
+
difference
+
Returns the difference between two arrays.
+
Create a set from b, then use list comprehension to only keep values not contained in b
+
+
def difference(a, b):
+ b = set(b)
+ return [item for item in a if item not in b]
+
+
difference([1, 2, 3], [1, 2, 4]) # [3]
+
+
+
shuffle
+
ℹ The same algorithm is already implemented via random.shuffle.
+
Randomizes the order of the values of an list, returning a new list.
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.
+
+
def zip(*args, fillvalue=None):
+ max_length = max([len(arr) for arr in args])
+ result = []
+ for i in range(max_length):
+ result.append([
+ args[k][i] if i < len(args[k]) else None for k in range(len(args))
+ ])
+ return result
Returns the difference between two list, after applying the provided function to each list element of both.
+
Create a set by applying fn to each element in b, then use list comprehension in combination with fn on a to only keep values not contained in the previously created set.
+
+
def difference_by(a, b, fn):
+ b = set(map(fn, b))
+ return [item for item in a if fn(item) not in b]
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!
+
+
def insertion_sort(arr):
+
+ for i in range(1, len(arr)):
+ key = arr[i]
+ j = i - 1
+ while j >= 0 and key < arr[j]:
+ arr[j + 1] = arr[j]
+ j -= 1
+ arr[j + 1] = key
Capitalizes the fist letter of the sring 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.
Decapitalizes the fist letter of the sring 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.