update insertion_sort
This commit is contained in:
@ -22,5 +22,4 @@ is_upper_case:[Rohit Tanwar](@kriadmin)
|
|||||||
is_lower_case:[Rohit Tanwar](@kriadmin)
|
is_lower_case:[Rohit Tanwar](@kriadmin)
|
||||||
count_by:[Rohit Tanwar](@kriadmin)
|
count_by:[Rohit Tanwar](@kriadmin)
|
||||||
insertion_sort:[Meet Zaveri](@meetzaveri)
|
insertion_sort:[Meet Zaveri](@meetzaveri)
|
||||||
difference_by:[Rohit Tanwar](@kriadmin)
|
difference_by:[Rohit Tanwar](@kriadmin)
|
||||||
|
|
||||||
@ -1,17 +1,17 @@
|
|||||||
### average
|
### average
|
||||||
|
|
||||||
:information_source: Already implemented via `statistics.mean`. `statistics.mean` takes an array as an argument whereas this function takes variadic arguments.
|
:information_source: Already implemented via `statistics.mean`. `statistics.mean` takes an array as an argument whereas this function takes variadic arguments.
|
||||||
|
|
||||||
Returns the average of two or more numbers.
|
Returns the average of two or more numbers.
|
||||||
|
|
||||||
Takes the sum of all the `args` and divides it by `len(args)`. The secind argument `0.0` in sum is to handle floating point division in `python2`.
|
Takes the sum of all the `args` and divides it by `len(args)`. The secind argument `0.0` in sum is to handle floating point division in `python2`.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def average(*args):
|
def average(*args):
|
||||||
return sum(args, 0.0) / len(args)
|
return sum(args, 0.0) / len(args)
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
average(*[1, 2, 3]) # 2.0
|
average(*[1, 2, 3]) # 2.0
|
||||||
average(1, 2, 3) # 2.0
|
average(1, 2, 3) # 2.0
|
||||||
```
|
```
|
||||||
@ -1,15 +1,15 @@
|
|||||||
### byte_size
|
### byte_size
|
||||||
|
|
||||||
Returns the length of a string in bytes.
|
Returns the length of a string in bytes.
|
||||||
|
|
||||||
`utf-8` encodes a given string and find its length.
|
`utf-8` encodes a given string and find its length.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def byte_size(string):
|
def byte_size(string):
|
||||||
return(len(string.encode('utf-8')))
|
return(len(string.encode('utf-8')))
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
byte_size('😀') # 4
|
byte_size('😀') # 4
|
||||||
byte_size('Hello World') # 11
|
byte_size('Hello World') # 11
|
||||||
```
|
```
|
||||||
@ -1,15 +1,15 @@
|
|||||||
### capitalize
|
### capitalize
|
||||||
|
|
||||||
Capitalizes the first letter of a string.
|
Capitalizes the first letter of a string.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def capitalize(string, lower_rest=False):
|
def capitalize(string, lower_rest=False):
|
||||||
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
|
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
capitalize('fooBar') # 'FooBar'
|
capitalize('fooBar') # 'FooBar'
|
||||||
capitalize('fooBar', True) # 'Foobar'
|
capitalize('fooBar', True) # 'Foobar'
|
||||||
```
|
```
|
||||||
@ -1,14 +1,14 @@
|
|||||||
### capitalize_every_word
|
### capitalize_every_word
|
||||||
|
|
||||||
Capitalizes the first letter of every word in a string.
|
Capitalizes the first letter of every word in a string.
|
||||||
|
|
||||||
Uses `str.title` to capitalize first letter of evry word in the string.
|
Uses `str.title` to capitalize first letter of evry word in the string.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def capitalize_every_word(string):
|
def capitalize_every_word(string):
|
||||||
return string.title()
|
return string.title()
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
capitalize_every_word('hello world!') # 'Hello World!'
|
capitalize_every_word('hello world!') # 'Hello World!'
|
||||||
```
|
```
|
||||||
@ -1,19 +1,19 @@
|
|||||||
### chunk
|
### chunk
|
||||||
|
|
||||||
Chunks an array into smaller lists of a specified size.
|
Chunks an array 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 `arr`.
|
Uses `range` to create a list of desired size. Then use `map` on this list and fill it with splices of `arr`.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from math import ceil
|
from math import ceil
|
||||||
|
|
||||||
|
|
||||||
def chunk(arr, size):
|
def chunk(arr, size):
|
||||||
return list(
|
return list(
|
||||||
map(lambda x: arr[x * size:x * size + size],
|
map(lambda x: arr[x * size:x * size + size],
|
||||||
list(range(0, ceil(len(arr) / size)))))
|
list(range(0, ceil(len(arr) / size)))))
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
|
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
### compact
|
### compact
|
||||||
|
|
||||||
Removes falsey values from a list.
|
Removes falsey values from a list.
|
||||||
|
|
||||||
Use `filter()` to filter out falsey values (False, None, 0, and "").
|
Use `filter()` to filter out falsey values (False, None, 0, and "").
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def compact(arr):
|
def compact(arr):
|
||||||
return list(filter(lambda x: bool(x), arr))
|
return list(filter(lambda x: bool(x), arr))
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
|
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
|
||||||
```
|
```
|
||||||
@ -1,22 +1,22 @@
|
|||||||
### count_by
|
### count_by
|
||||||
|
|
||||||
:information_source: Already implemented via `collections.Counter`
|
:information_source: Already implemented via `collections.Counter`
|
||||||
|
|
||||||
Groups the elements of a list based on the given function and returns the count of elements in each group.
|
Groups the elements of a list based on the given function and returns the count of elements in each group.
|
||||||
|
|
||||||
Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.
|
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
|
```python
|
||||||
def count_by(arr, fn=lambda x: x):
|
def count_by(arr, fn=lambda x: x):
|
||||||
key = {}
|
key = {}
|
||||||
for el in map(fn, arr):
|
for el in map(fn, arr):
|
||||||
key[el] = 0 if not el in key else key[el]
|
key[el] = 0 if not el in key else key[el]
|
||||||
key[el] += 1
|
key[el] += 1
|
||||||
return key
|
return key
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
from math import floor
|
from math import floor
|
||||||
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
|
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
|
||||||
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}
|
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}
|
||||||
```
|
```
|
||||||
@ -1,18 +1,18 @@
|
|||||||
### count_occurences
|
### count_occurences
|
||||||
|
|
||||||
:information_source: Already implemented via `list.count()`.
|
:information_source: Already implemented via `list.count()`.
|
||||||
|
|
||||||
Counts the occurrences of a value in an list.
|
Counts the occurrences of a value in an list.
|
||||||
|
|
||||||
Uses the `reduce` functin from built-in module `functools` to increment a counter each time you encounter the specific value inside the list.
|
Uses the `reduce` functin from built-in module `functools` to increment a counter each time you encounter the specific value inside the list.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def count_occurences(arr, val):
|
def count_occurences(arr, val):
|
||||||
return reduce(
|
return reduce(
|
||||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||||
arr)
|
arr)
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
|
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
|
||||||
```
|
```
|
||||||
@ -1,18 +1,18 @@
|
|||||||
### count_vowels
|
### count_vowels
|
||||||
|
|
||||||
Retuns `number` of vowels in provided `string`.
|
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.
|
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a string.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
|
||||||
def count_vowels(str):
|
def count_vowels(str):
|
||||||
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
|
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
count_vowels('foobar') # 3
|
count_vowels('foobar') # 3
|
||||||
count_vowels('gym') # 0
|
count_vowels('gym') # 0
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,15 +1,15 @@
|
|||||||
### decapitalize
|
### decapitalize
|
||||||
|
|
||||||
Decapitalizes the first letter of a string.
|
Decapitalizes the first letter of a string.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def decapitalize(string, upper_rest=False):
|
def decapitalize(string, upper_rest=False):
|
||||||
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
|
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
decapitalize('FooBar') # 'fooBar'
|
decapitalize('FooBar') # 'fooBar'
|
||||||
decapitalize('FooBar', True) # 'fOOBAR'
|
decapitalize('FooBar', True) # 'fOOBAR'
|
||||||
```
|
```
|
||||||
@ -1,27 +1,27 @@
|
|||||||
### deep_flatten
|
### deep_flatten
|
||||||
|
|
||||||
Deep flattens a list.
|
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.
|
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.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def spread(arg):
|
def spread(arg):
|
||||||
ret = []
|
ret = []
|
||||||
for i in arg:
|
for i in arg:
|
||||||
if isinstance(i, list):
|
if isinstance(i, list):
|
||||||
ret.extend(i)
|
ret.extend(i)
|
||||||
else:
|
else:
|
||||||
ret.append(i)
|
ret.append(i)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
def deep_flatten(arr):
|
def deep_flatten(arr):
|
||||||
result = []
|
result = []
|
||||||
result.extend(
|
result.extend(
|
||||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
|
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
### difference
|
### difference
|
||||||
|
|
||||||
Returns the difference between two arrays.
|
Returns the difference between two arrays.
|
||||||
|
|
||||||
Create a `set` from `b`, then use list comprehension to only keep values not contained in `b`
|
Create a `set` from `b`, then use list comprehension to only keep values not contained in `b`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def difference(a, b):
|
def difference(a, b):
|
||||||
b = set(b)
|
b = set(b)
|
||||||
return [item for item in a if item not in b]
|
return [item for item in a if item not in b]
|
||||||
```
|
```
|
||||||
``` python
|
``` python
|
||||||
difference([1, 2, 3], [1, 2, 4]) # [3]
|
difference([1, 2, 3], [1, 2, 4]) # [3]
|
||||||
```
|
```
|
||||||
@ -1,17 +1,17 @@
|
|||||||
### difference_by
|
### difference_by
|
||||||
|
|
||||||
Returns the difference between two list, after applying the provided function to each list element of both.
|
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`.
|
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
|
```python
|
||||||
def difference_by(a, b, fn):
|
def difference_by(a, b, fn):
|
||||||
b = set(map(fn, b))
|
b = set(map(fn, b))
|
||||||
return [item for item in a if fn(item) not in b]
|
return [item for item in a if fn(item) not in b]
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from math import floor
|
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 } ]
|
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
|
||||||
```
|
```
|
||||||
@ -1,16 +1,16 @@
|
|||||||
### factorial
|
### factorial
|
||||||
|
|
||||||
Calculates the factorial of a number.
|
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.
|
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
|
```python
|
||||||
def factorial(num):
|
def factorial(num):
|
||||||
if not ((num >= 0) & (num % 1 == 0)):
|
if not ((num >= 0) & (num % 1 == 0)):
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"Number( {num} ) can't be floating point or negative ")
|
f"Number( {num} ) can't be floating point or negative ")
|
||||||
return 1 if num == 0 else num * factorial(num - 1)
|
return 1 if num == 0 else num * factorial(num - 1)
|
||||||
```
|
```
|
||||||
``` python
|
``` python
|
||||||
factorial(6) # 720
|
factorial(6) # 720
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,38 +1,38 @@
|
|||||||
### gcd
|
### gcd
|
||||||
|
|
||||||
:information_source: `math.gcd` works with only two numbers
|
:information_source: `math.gcd` works with only two numbers
|
||||||
|
|
||||||
Calculates the greatest common divisor between two or more numbers/lists.
|
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`.
|
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.
|
Uses the reduce function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from functools import reduce
|
from functools import reduce
|
||||||
|
|
||||||
|
|
||||||
def spread(arg):
|
def spread(arg):
|
||||||
ret = []
|
ret = []
|
||||||
for i in arg:
|
for i in arg:
|
||||||
if isinstance(i, list):
|
if isinstance(i, list):
|
||||||
ret.extend(i)
|
ret.extend(i)
|
||||||
else:
|
else:
|
||||||
ret.append(i)
|
ret.append(i)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
def gcd(*args):
|
def gcd(*args):
|
||||||
numbers = []
|
numbers = []
|
||||||
numbers.extend(spread(list(args)))
|
numbers.extend(spread(list(args)))
|
||||||
|
|
||||||
def _gcd(x, y):
|
def _gcd(x, y):
|
||||||
return x if not y else gcd(y, x % y)
|
return x if not y else gcd(y, x % y)
|
||||||
|
|
||||||
return reduce((lambda x, y: _gcd(x, y)), numbers)
|
return reduce((lambda x, y: _gcd(x, y)), numbers)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
gcd(8,36) # 4
|
gcd(8,36) # 4
|
||||||
```
|
```
|
||||||
@ -7,11 +7,11 @@ def insertionsort(arr):
|
|||||||
|
|
||||||
for i in range(1, len(arr)):
|
for i in range(1, len(arr)):
|
||||||
key = arr[i]
|
key = arr[i]
|
||||||
j = i-1
|
j = i - 1
|
||||||
while j>=0 and key < arr[j]:
|
while j >= 0 and key < arr[j]:
|
||||||
arr[j+1] = arr[j]
|
arr[j + 1] = arr[j]
|
||||||
j -= 1
|
j -= 1
|
||||||
arr[j+1] = key
|
arr[j + 1] = key
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|||||||
@ -1,16 +1,16 @@
|
|||||||
### is_lower_case
|
### is_lower_case
|
||||||
|
|
||||||
Checks if a string is lower case.
|
Checks if a string is lower case.
|
||||||
|
|
||||||
Convert the given string to lower case, using `str.lower()` method and compare it to the original.
|
Convert the given string to lower case, using `str.lower()` method and compare it to the original.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def is_lower_case(str):
|
def is_lower_case(str):
|
||||||
return str == str.lower()
|
return str == str.lower()
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
is_lower_case('abc') # True
|
is_lower_case('abc') # True
|
||||||
is_lower_case('a3@$') # True
|
is_lower_case('a3@$') # True
|
||||||
is_lower_case('Ab4') # False
|
is_lower_case('Ab4') # False
|
||||||
```
|
```
|
||||||
@ -1,16 +1,16 @@
|
|||||||
### is_upper_case
|
### is_upper_case
|
||||||
|
|
||||||
Checks if a string is upper case.
|
Checks if a string is upper case.
|
||||||
|
|
||||||
Convert the given string to upper case, using `str.upper()` method and compare it to the original.
|
Convert the given string to upper case, using `str.upper()` method and compare it to the original.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def is_upper_case(str):
|
def is_upper_case(str):
|
||||||
return str == str.upper()
|
return str == str.upper()
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
is_upper_case('ABC') # True
|
is_upper_case('ABC') # True
|
||||||
is_upper_case('a3@$') # True
|
is_upper_case('a3@$') # True
|
||||||
is_upper_case('aB4') # False
|
is_upper_case('aB4') # False
|
||||||
```
|
```
|
||||||
@ -1,40 +1,40 @@
|
|||||||
### lcm
|
### lcm
|
||||||
|
|
||||||
Returns the least common multiple of two or more numbers.
|
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.
|
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.
|
Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from functools import reduce
|
from functools import reduce
|
||||||
|
|
||||||
|
|
||||||
def spread(arg):
|
def spread(arg):
|
||||||
ret = []
|
ret = []
|
||||||
for i in arg:
|
for i in arg:
|
||||||
if isinstance(i, list):
|
if isinstance(i, list):
|
||||||
ret.extend(i)
|
ret.extend(i)
|
||||||
else:
|
else:
|
||||||
ret.append(i)
|
ret.append(i)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
def lcm(*args):
|
def lcm(*args):
|
||||||
numbers = []
|
numbers = []
|
||||||
numbers.extend(spread(list(args)))
|
numbers.extend(spread(list(args)))
|
||||||
|
|
||||||
def _gcd(x, y):
|
def _gcd(x, y):
|
||||||
return x if not y else gcd(y, x % y)
|
return x if not y else gcd(y, x % y)
|
||||||
|
|
||||||
def _lcm(x, y):
|
def _lcm(x, y):
|
||||||
return x * y / _gcd(x, y)
|
return x * y / _gcd(x, y)
|
||||||
|
|
||||||
return reduce((lambda x, y: _lcm(x, y)), numbers)
|
return reduce((lambda x, y: _lcm(x, y)), numbers)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
lcm(12, 7) # 84
|
lcm(12, 7) # 84
|
||||||
lcm([1, 3, 4], 5) # 60
|
lcm([1, 3, 4], 5) # 60
|
||||||
```
|
```
|
||||||
@ -1,21 +1,21 @@
|
|||||||
### max_n
|
### 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).
|
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
|
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
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
|
||||||
|
|
||||||
def max_n(arr, n=1):
|
def max_n(arr, n=1):
|
||||||
numbers = deepcopy(arr)
|
numbers = deepcopy(arr)
|
||||||
numbers.sort()
|
numbers.sort()
|
||||||
numbers.reverse()
|
numbers.reverse()
|
||||||
return numbers[:n]
|
return numbers[:n]
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
max_n([1, 2, 3]) # [3]
|
max_n([1, 2, 3]) # [3]
|
||||||
max_n([1, 2, 3], 2) # [3,2]
|
max_n([1, 2, 3], 2) # [3,2]
|
||||||
```
|
```
|
||||||
@ -1,20 +1,20 @@
|
|||||||
### min_n
|
### min_n
|
||||||
|
|
||||||
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).
|
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
|
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
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
|
||||||
|
|
||||||
def min_n(arr, n=1):
|
def min_n(arr, n=1):
|
||||||
numbers = deepcopy(arr)
|
numbers = deepcopy(arr)
|
||||||
numbers.sort()
|
numbers.sort()
|
||||||
return numbers[:n]
|
return numbers[:n]
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
min_n([1, 2, 3]) # [1]
|
min_n([1, 2, 3]) # [1]
|
||||||
min_n([1, 2, 3], 2) # [1,2]
|
min_n([1, 2, 3], 2) # [1,2]
|
||||||
```
|
```
|
||||||
@ -1,15 +1,15 @@
|
|||||||
### palindrome
|
### palindrome
|
||||||
|
|
||||||
Returns `True` if the given string is a palindrome, `False` otherwise.
|
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.
|
Convert string `str.lower()` and use `re.sub` to remove non-alphanumeric characters from it. Then compare the new string to the reversed.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def palindrome(string):
|
def palindrome(string):
|
||||||
from re import sub
|
from re import sub
|
||||||
s = sub('[\W_]', '', string.lower())
|
s = sub('[\W_]', '', string.lower())
|
||||||
return s == s[::-1]
|
return s == s[::-1]
|
||||||
```
|
```
|
||||||
```python
|
```python
|
||||||
palindrome('taco cat') # True
|
palindrome('taco cat') # True
|
||||||
```
|
```
|
||||||
@ -1,27 +1,27 @@
|
|||||||
### shuffle
|
### shuffle
|
||||||
|
|
||||||
:information_source: The same algorithm is already implemented via `random.shuffle`.
|
:information_source: The same algorithm is already implemented via `random.shuffle`.
|
||||||
|
|
||||||
Randomizes the order of the values of an list, returning a new list.
|
Randomizes the order of the values of an list, returning a new list.
|
||||||
|
|
||||||
Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.
|
Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from random import randint
|
from random import randint
|
||||||
|
|
||||||
|
|
||||||
def shuffle(arr):
|
def shuffle(arr):
|
||||||
temp_arr = deepcopy(arr)
|
temp_arr = deepcopy(arr)
|
||||||
m = len(temp_arr)
|
m = len(temp_arr)
|
||||||
while (m):
|
while (m):
|
||||||
m -= 1
|
m -= 1
|
||||||
i = randint(0, m)
|
i = randint(0, m)
|
||||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||||
return temp_arr
|
return temp_arr
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
foo = [1,2,3]
|
foo = [1,2,3]
|
||||||
shuffle(foo) # [2,3,1] , foo = [1,2,3]
|
shuffle(foo) # [2,3,1] , foo = [1,2,3]
|
||||||
```
|
```
|
||||||
@ -1,19 +1,19 @@
|
|||||||
### spread
|
### spread
|
||||||
|
|
||||||
Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list.
|
Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def spread(arg):
|
def spread(arg):
|
||||||
ret = []
|
ret = []
|
||||||
for i in arg:
|
for i in arg:
|
||||||
if isinstance(i, list):
|
if isinstance(i, list):
|
||||||
ret.extend(i)
|
ret.extend(i)
|
||||||
else:
|
else:
|
||||||
ret.append(i)
|
ret.append(i)
|
||||||
return ret
|
return ret
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
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]
|
||||||
```
|
```
|
||||||
@ -1,24 +1,24 @@
|
|||||||
### zip
|
### zip
|
||||||
|
|
||||||
:information_source: Already implemented via `itertools.zip_longest()`
|
:information_source: Already implemented via `itertools.zip_longest()`
|
||||||
|
|
||||||
Creates a list of elements, grouped based on the position in the original lists.
|
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`.
|
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
|
```python
|
||||||
def zip(*args, fillvalue=None):
|
def zip(*args, fillvalue=None):
|
||||||
max_length = max([len(arr) for arr in args])
|
max_length = max([len(arr) for arr in args])
|
||||||
result = []
|
result = []
|
||||||
for i in range(max_length):
|
for i in range(max_length):
|
||||||
result.append([
|
result.append([
|
||||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||||
])
|
])
|
||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
``` python
|
``` python
|
||||||
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
|
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]) # [['a', 1, True], [None, 2, False]]
|
||||||
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]
|
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]
|
||||||
```
|
```
|
||||||
@ -22,4 +22,4 @@ is_upper_case:string
|
|||||||
is_lower_case:string
|
is_lower_case:string
|
||||||
count_by:list
|
count_by:list
|
||||||
difference_by:list
|
difference_by:list
|
||||||
insertion_sort:list
|
insertion_sort:list
|
||||||
Reference in New Issue
Block a user