From 7cc78ca4c46de59b9c78ff81191dc687e88482cc Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Tue, 20 Feb 2018 17:08:10 +0530 Subject: [PATCH] update insertion_sort --- README.md | 1547 +++++++++++++++-------------- contributor_database | 3 +- snippets/average.md | 32 +- snippets/byte_size.md | 28 +- snippets/capitalize.md | 28 +- snippets/capitalize_every_word.md | 26 +- snippets/chunk.md | 38 +- snippets/compact.md | 26 +- snippets/count_by.md | 42 +- snippets/count_occurences.md | 34 +- snippets/count_vowels.md | 36 +- snippets/decapitalize.md | 28 +- snippets/deep_flatten.md | 54 +- snippets/difference.md | 26 +- snippets/difference_by.md | 32 +- snippets/factorial.md | 32 +- snippets/gcd.md | 74 +- snippets/insertion_sort.md | 8 +- snippets/is_lower_case.md | 30 +- snippets/is_upper_case.md | 30 +- snippets/lcm.md | 78 +- snippets/max_n.md | 40 +- snippets/min_n.md | 38 +- snippets/palindrome.md | 28 +- snippets/shuffle.md | 52 +- snippets/spread.md | 36 +- snippets/zip.md | 46 +- tag_database | 2 +- 28 files changed, 1252 insertions(+), 1222 deletions(-) diff --git a/README.md b/README.md index 298e2a05c..858c3e275 100644 --- a/README.md +++ b/README.md @@ -1,758 +1,789 @@ -![Logo](/icon.png) - -# 30-seconds-of-python-code -[![License](https://img.shields.io/aur/license/yaourt.svg)](https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-python-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.org/kriadmin/30-seconds-of-python-code.svg?branch=master)](https://travis-ci.org/kriadmin/30-seconds-of-python-code) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/kriadmin/30-seconds-of-python-code/tree/master/?source=0) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_shield) - ->Python implementation of 30-seconds-of-code. - -**Note**:- This is in no way affiliated with the original [30-seconds-of-code](https://github.com/Chalarangelo/30-seconds-of-code/). - - -## Table of Contents -### :heavy_division_sign: Math - -
View contents
- -### :books: List - -
View contents
- -### :scroll: String - -
View contents
- -
- -## :heavy_division_sign: Math - -### average - -: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. - -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`. - -```py -def average(*args): - return sum(args, 0.0) / len(args) - - ``` - -
View Examples - -```py - -average(*[1, 2, 3]) # 2.0 -average(1, 2, 3) # 2.0 - -``` -
- -
:arrow_up: Back to top - -### factorial - -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. - -```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) - - ``` -
View Examples - -```py - -factorial(6) # 720 - -``` -
- -
:arrow_up: Back to top - -### gcd - -:information_source: `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. - -```py -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) - - ``` - - -
View Examples - -```py - -gcd(8,36) # 4 - -``` -
- -
:arrow_up: Back to top - -### 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. - -```py -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) - - ``` - - -
View Examples - -```py - -lcm(12, 7) # 84 -lcm([1, 3, 4], 5) # 60 - -``` -
- -
:arrow_up: Back to top - -### 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 - -```py -from copy import deepcopy - - -def max_n(arr, n=1): - numbers = deepcopy(arr) - numbers.sort() - numbers.reverse() - return numbers[:n] - - ``` - -
View Examples - -```py - -max_n([1, 2, 3]) # [3] -max_n([1, 2, 3], 2) # [3,2] - -``` -
- -
:arrow_up: Back to top - -### 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). - -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 - -```py -from copy import deepcopy - - -def min_n(arr, n=1): - numbers = deepcopy(arr) - numbers.sort() - return numbers[:n] - - ``` - -
View Examples - -```py - -min_n([1, 2, 3]) # [1] -min_n([1, 2, 3], 2) # [1,2] - -``` -
- -
:arrow_up: Back to top - -## :books: List - -### chunk - -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`. - -```py -from math import ceil - - -def chunk(arr, size): - return list( - map(lambda x: arr[x * size:x * size + size], - list(range(0, ceil(len(arr) / size))))) - - ``` - -
View Examples - -```py - -chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] - -``` -
- -
:arrow_up: Back to top - -### compact - -Removes falsey values from a list. - -Use `filter()` to filter out falsey values (False, None, 0, and ""). - -```py -def compact(arr): - return list(filter(lambda x: bool(x), arr)) - - ``` - -
View Examples - -```py - -compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] - -``` -
- -
:arrow_up: Back to top - -### count_by - -: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. - -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. - -```py -def count_by(arr, fn=lambda x: x): - key = {} - for el in map(fn, arr): - key[el] = 0 if not el in key else key[el] - key[el] += 1 - return key - - ``` - -
View Examples - -```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} - -``` -
- -
:arrow_up: Back to top - -### count_occurences - -:information_source: Already implemented via `list.count()`. - -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. - -```py -def count_occurences(arr, val): - return reduce( - (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0), - arr) - - ``` - -
View Examples - -```py - -count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 - -``` -
- -
:arrow_up: Back to top - -### 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. - -```py -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 - - ``` - -
View Examples - -```py - -deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] - -``` -
- -
:arrow_up: Back to top - -### difference - -Returns the difference between two arrays. - -Create a `set` from `b`, then use list comprehension to only keep values not contained in `b` - -```py -def difference(a, b): - b = set(b) - return [item for item in a if item not in b] - - ``` -
View Examples - -```py - -difference([1, 2, 3], [1, 2, 4]) # [3] - -``` -
- -
:arrow_up: Back to top - -### difference_by - -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`. - -```py -def difference_by(a, b, fn): - b = set(map(fn, b)) - return [item for item in a if fn(item) not in b] - - ``` - -
View Examples - -```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 } ] - -``` -
- -
:arrow_up: Back to top - -### 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. - -Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. - -```py -from copy import deepcopy -from random import randint - - -def shuffle(arr): - temp_arr = deepcopy(arr) - m = len(temp_arr) - while (m): - m -= 1 - i = randint(0, m) - temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m] - return temp_arr - - ``` - -
View Examples - -```py - -foo = [1,2,3] -shuffle(foo) # [2,3,1] , foo = [1,2,3] - -``` -
- -
:arrow_up: Back to top - -### spread - -Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. - -```py -def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) - return ret - - ``` - - -
View Examples - -```py - -spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] - -``` -
- -
:arrow_up: Back to top - -### zip - -:information_source: Already implemented via `itertools.zip_longest()` - -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`. - -```py -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 - - ``` - -
View Examples - -```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]] - -``` -
- -
:arrow_up: Back to top - -## :scroll: String - -### byte_size - -Returns the length of a string in bytes. - -`utf-8` encodes a given string and find its length. - -```py -def byte_size(string): - return(len(string.encode('utf-8'))) - - ``` - -
View Examples - -```py - -byte_size('😀') # 4 -byte_size('Hello World') # 11 - -``` -
- -
:arrow_up: Back to top - -### capitalize - -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. - -```py -def capitalize(string, lower_rest=False): - return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) - - ``` - -
View Examples - -```py - -capitalize('fooBar') # 'FooBar' -capitalize('fooBar', True) # 'Foobar' - -``` -
- -
:arrow_up: Back to top - -### capitalize_every_word - -Capitalizes the first letter of every word in a string. - -Uses `str.title` to capitalize first letter of evry word in the string. - -```py -def capitalize_every_word(string): - return string.title() - - ``` - -
View Examples - -```py - -capitalize_every_word('hello world!') # 'Hello World!' - -``` -
- -
:arrow_up: Back to top - -### count_vowels - -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. - -```py -import re - - -def count_vowels(str): - return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE))) - - ``` - -
View Examples - -```py - -count_vowels('foobar') # 3 -count_vowels('gym') # 0 - -``` -
- -
:arrow_up: Back to top - -### decapitalize - -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. - -```py -def decapitalize(string, upper_rest=False): - return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) - - ``` - -
View Examples - -```py - -decapitalize('FooBar') # 'fooBar' -decapitalize('FooBar', True) # 'fOOBAR' - -``` -
- -
:arrow_up: Back to top - -### 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. - -```py -def is_lower_case(str): - return str == str.lower() - - ``` - -
View Examples - -```py - -is_lower_case('abc') # True -is_lower_case('a3@$') # True -is_lower_case('Ab4') # False - -``` -
- -
:arrow_up: Back to top - -### 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. - -```py -def is_upper_case(str): - return str == str.upper() - - ``` - -
View Examples - -```py - -is_upper_case('ABC') # True -is_upper_case('a3@$') # True -is_upper_case('aB4') # False - -``` -
- -
:arrow_up: Back to top - -### palindrome - -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. - -```py -def palindrome(string): - from re import sub - s = sub('[\W_]', '', string.lower()) - return s == s[::-1] - - ``` -
View Examples - -```py - -palindrome('taco cat') # True - -``` -
- -
:arrow_up: Back to top - - -## Credits - -*Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).* - - - -## License -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_large) +![Logo](/icon.png) + +# 30-seconds-of-python-code +[![License](https://img.shields.io/aur/license/yaourt.svg)](https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-python-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.org/kriadmin/30-seconds-of-python-code.svg?branch=master)](https://travis-ci.org/kriadmin/30-seconds-of-python-code) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/kriadmin/30-seconds-of-python-code/tree/master/?source=0) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_shield) + +>Python implementation of 30-seconds-of-code. + +**Note**:- This is in no way affiliated with the original [30-seconds-of-code](https://github.com/Chalarangelo/30-seconds-of-code/). + + +## Table of Contents +### :heavy_division_sign: Math + +
View contents
+ +### :books: List + +
View contents
+ +### :scroll: String + +
View contents
+ +
+ +## :heavy_division_sign: Math + +### average + +: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. + +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`. + +```py +def average(*args): + return sum(args, 0.0) / len(args) + + ``` + +
View Examples + +```py + +average(*[1, 2, 3]) # 2.0 +average(1, 2, 3) # 2.0 + +``` +
+ +
:arrow_up: Back to top + +### factorial + +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. + +```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) + + ``` +
View Examples + +```py + +factorial(6) # 720 + +``` +
+ +
:arrow_up: Back to top + +### gcd + +:information_source: `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. + +```py +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) + + ``` + + +
View Examples + +```py + +gcd(8,36) # 4 + +``` +
+ +
:arrow_up: Back to top + +### 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. + +```py +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) + + ``` + + +
View Examples + +```py + +lcm(12, 7) # 84 +lcm([1, 3, 4], 5) # 60 + +``` +
+ +
:arrow_up: Back to top + +### 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 + +```py +from copy import deepcopy + + +def max_n(arr, n=1): + numbers = deepcopy(arr) + numbers.sort() + numbers.reverse() + return numbers[:n] + + ``` + +
View Examples + +```py + +max_n([1, 2, 3]) # [3] +max_n([1, 2, 3], 2) # [3,2] + +``` +
+ +
:arrow_up: Back to top + +### 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). + +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 + +```py +from copy import deepcopy + + +def min_n(arr, n=1): + numbers = deepcopy(arr) + numbers.sort() + return numbers[:n] + + ``` + +
View Examples + +```py + +min_n([1, 2, 3]) # [1] +min_n([1, 2, 3], 2) # [1,2] + +``` +
+ +
:arrow_up: Back to top + +## :books: List + +### chunk + +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`. + +```py +from math import ceil + + +def chunk(arr, size): + return list( + map(lambda x: arr[x * size:x * size + size], + list(range(0, ceil(len(arr) / size))))) + + ``` + +
View Examples + +```py + +chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] + +``` +
+ +
:arrow_up: Back to top + +### compact + +Removes falsey values from a list. + +Use `filter()` to filter out falsey values (False, None, 0, and ""). + +```py +def compact(arr): + return list(filter(lambda x: bool(x), arr)) + + ``` + +
View Examples + +```py + +compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] + +``` +
+ +
:arrow_up: Back to top + +### count_by + +: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. + +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. + +```py +def count_by(arr, fn=lambda x: x): + key = {} + for el in map(fn, arr): + key[el] = 0 if not el in key else key[el] + key[el] += 1 + return key + + ``` + +
View Examples + +```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} + +``` +
+ +
:arrow_up: Back to top + +### count_occurences + +:information_source: Already implemented via `list.count()`. + +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. + +```py +def count_occurences(arr, val): + return reduce( + (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0), + arr) + + ``` + +
View Examples + +```py + +count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 + +``` +
+ +
:arrow_up: Back to top + +### 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. + +```py +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 + + ``` + +
View Examples + +```py + +deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] + +``` +
+ +
:arrow_up: Back to top + +### difference + +Returns the difference between two arrays. + +Create a `set` from `b`, then use list comprehension to only keep values not contained in `b` + +```py +def difference(a, b): + b = set(b) + return [item for item in a if item not in b] + + ``` +
View Examples + +```py + +difference([1, 2, 3], [1, 2, 4]) # [3] + +``` +
+ +
:arrow_up: Back to top + +### difference_by + +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`. + +```py +def difference_by(a, b, fn): + b = set(map(fn, b)) + return [item for item in a if fn(item) not in b] + + ``` + +
View Examples + +```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 } ] + +``` +
+ +
:arrow_up: Back to top + +### insertion_sort + +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! + +```py +def insertionsort(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 + + ``` + +
View Examples + +```py + +arr = [7,4,9,2,6,3] +insertionsort(arr) +print('Sorted %s' %arr) # sorted [2, 3, 4, 6, 7, 9] + +``` +
+ +
:arrow_up: Back to top + +### 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. + +Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. + +```py +from copy import deepcopy +from random import randint + + +def shuffle(arr): + temp_arr = deepcopy(arr) + m = len(temp_arr) + while (m): + m -= 1 + i = randint(0, m) + temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m] + return temp_arr + + ``` + +
View Examples + +```py + +foo = [1,2,3] +shuffle(foo) # [2,3,1] , foo = [1,2,3] + +``` +
+ +
:arrow_up: Back to top + +### spread + +Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. + +```py +def spread(arg): + ret = [] + for i in arg: + if isinstance(i, list): + ret.extend(i) + else: + ret.append(i) + return ret + + ``` + + +
View Examples + +```py + +spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] + +``` +
+ +
:arrow_up: Back to top + +### zip + +:information_source: Already implemented via `itertools.zip_longest()` + +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`. + +```py +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 + + ``` + +
View Examples + +```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]] + +``` +
+ +
:arrow_up: Back to top + +## :scroll: String + +### byte_size + +Returns the length of a string in bytes. + +`utf-8` encodes a given string and find its length. + +```py +def byte_size(string): + return(len(string.encode('utf-8'))) + + ``` + +
View Examples + +```py + +byte_size('😀') # 4 +byte_size('Hello World') # 11 + +``` +
+ +
:arrow_up: Back to top + +### capitalize + +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. + +```py +def capitalize(string, lower_rest=False): + return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) + + ``` + +
View Examples + +```py + +capitalize('fooBar') # 'FooBar' +capitalize('fooBar', True) # 'Foobar' + +``` +
+ +
:arrow_up: Back to top + +### capitalize_every_word + +Capitalizes the first letter of every word in a string. + +Uses `str.title` to capitalize first letter of evry word in the string. + +```py +def capitalize_every_word(string): + return string.title() + + ``` + +
View Examples + +```py + +capitalize_every_word('hello world!') # 'Hello World!' + +``` +
+ +
:arrow_up: Back to top + +### count_vowels + +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. + +```py +import re + + +def count_vowels(str): + return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE))) + + ``` + +
View Examples + +```py + +count_vowels('foobar') # 3 +count_vowels('gym') # 0 + +``` +
+ +
:arrow_up: Back to top + +### decapitalize + +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. + +```py +def decapitalize(string, upper_rest=False): + return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) + + ``` + +
View Examples + +```py + +decapitalize('FooBar') # 'fooBar' +decapitalize('FooBar', True) # 'fOOBAR' + +``` +
+ +
:arrow_up: Back to top + +### 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. + +```py +def is_lower_case(str): + return str == str.lower() + + ``` + +
View Examples + +```py + +is_lower_case('abc') # True +is_lower_case('a3@$') # True +is_lower_case('Ab4') # False + +``` +
+ +
:arrow_up: Back to top + +### 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. + +```py +def is_upper_case(str): + return str == str.upper() + + ``` + +
View Examples + +```py + +is_upper_case('ABC') # True +is_upper_case('a3@$') # True +is_upper_case('aB4') # False + +``` +
+ +
:arrow_up: Back to top + +### palindrome + +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. + +```py +def palindrome(string): + from re import sub + s = sub('[\W_]', '', string.lower()) + return s == s[::-1] + + ``` +
View Examples + +```py + +palindrome('taco cat') # True + +``` +
+ +
:arrow_up: Back to top + + +## Credits + +*Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).* + + + +## License +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_large) diff --git a/contributor_database b/contributor_database index 471bb5072..5cf642d74 100644 --- a/contributor_database +++ b/contributor_database @@ -22,5 +22,4 @@ is_upper_case:[Rohit Tanwar](@kriadmin) is_lower_case:[Rohit Tanwar](@kriadmin) count_by:[Rohit Tanwar](@kriadmin) insertion_sort:[Meet Zaveri](@meetzaveri) -difference_by:[Rohit Tanwar](@kriadmin) - +difference_by:[Rohit Tanwar](@kriadmin) \ No newline at end of file diff --git a/snippets/average.md b/snippets/average.md index 0adee30a0..746f6f746 100644 --- a/snippets/average.md +++ b/snippets/average.md @@ -1,17 +1,17 @@ -### average - -: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. - -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 -def average(*args): - return sum(args, 0.0) / len(args) -``` - -``` python -average(*[1, 2, 3]) # 2.0 -average(1, 2, 3) # 2.0 +### average + +: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. + +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 +def average(*args): + return sum(args, 0.0) / len(args) +``` + +``` python +average(*[1, 2, 3]) # 2.0 +average(1, 2, 3) # 2.0 ``` \ No newline at end of file diff --git a/snippets/byte_size.md b/snippets/byte_size.md index 885bb35e1..faa8ba5fd 100644 --- a/snippets/byte_size.md +++ b/snippets/byte_size.md @@ -1,15 +1,15 @@ -### byte_size - -Returns the length of a string in bytes. - -`utf-8` encodes a given string and find its length. - -```python -def byte_size(string): - return(len(string.encode('utf-8'))) -``` - -```python -byte_size('😀') # 4 -byte_size('Hello World') # 11 +### byte_size + +Returns the length of a string in bytes. + +`utf-8` encodes a given string and find its length. + +```python +def byte_size(string): + return(len(string.encode('utf-8'))) +``` + +```python +byte_size('😀') # 4 +byte_size('Hello World') # 11 ``` \ No newline at end of file diff --git a/snippets/capitalize.md b/snippets/capitalize.md index f7de127c7..61f1b3294 100644 --- a/snippets/capitalize.md +++ b/snippets/capitalize.md @@ -1,15 +1,15 @@ -### capitalize - -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. - -```python -def capitalize(string, lower_rest=False): - return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) -``` - -```python -capitalize('fooBar') # 'FooBar' -capitalize('fooBar', True) # 'Foobar' +### capitalize + +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. + +```python +def capitalize(string, lower_rest=False): + return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) +``` + +```python +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 3e676437f..ba0c8f273 100644 --- a/snippets/capitalize_every_word.md +++ b/snippets/capitalize_every_word.md @@ -1,14 +1,14 @@ -### capitalize_every_word - -Capitalizes the first letter of every word in a string. - -Uses `str.title` to capitalize first letter of evry word in the string. - -```python -def capitalize_every_word(string): - return string.title() -``` - -```python -capitalize_every_word('hello world!') # 'Hello World!' +### capitalize_every_word + +Capitalizes the first letter of every word in a string. + +Uses `str.title` to capitalize first letter of evry word in the string. + +```python +def capitalize_every_word(string): + return string.title() +``` + +```python +capitalize_every_word('hello world!') # 'Hello World!' ``` \ No newline at end of file diff --git a/snippets/chunk.md b/snippets/chunk.md index 7678a16e2..d6dc58060 100644 --- a/snippets/chunk.md +++ b/snippets/chunk.md @@ -1,19 +1,19 @@ -### chunk - -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`. - -```python -from math import ceil - - -def chunk(arr, size): - return list( - map(lambda x: arr[x * size:x * size + size], - list(range(0, ceil(len(arr) / size))))) -``` - -``` python -chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] -``` +### chunk + +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`. + +```python +from math import ceil + + +def chunk(arr, size): + return list( + map(lambda x: arr[x * size:x * size + size], + list(range(0, ceil(len(arr) / size))))) +``` + +``` python +chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] +``` diff --git a/snippets/compact.md b/snippets/compact.md index 75b9e10f6..51f14918e 100644 --- a/snippets/compact.md +++ b/snippets/compact.md @@ -1,14 +1,14 @@ -### compact - -Removes falsey values from a list. - -Use `filter()` to filter out falsey values (False, None, 0, and ""). - -```python -def compact(arr): - return list(filter(lambda x: bool(x), arr)) -``` - -``` python -compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] +### compact + +Removes falsey values from a list. + +Use `filter()` to filter out falsey values (False, None, 0, and ""). + +```python +def compact(arr): + return list(filter(lambda x: bool(x), arr)) +``` + +``` python +compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] ``` \ No newline at end of file diff --git a/snippets/count_by.md b/snippets/count_by.md index 2a395292d..c3e67488a 100644 --- a/snippets/count_by.md +++ b/snippets/count_by.md @@ -1,22 +1,22 @@ -### count_by - -: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. - -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 -def count_by(arr, fn=lambda x: x): - key = {} - for el in map(fn, arr): - key[el] = 0 if not el in key else key[el] - key[el] += 1 - return key -``` - -``` python -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} +### count_by + +: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. + +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 +def count_by(arr, fn=lambda x: x): + key = {} + for el in map(fn, arr): + key[el] = 0 if not el in key else key[el] + key[el] += 1 + return key +``` + +``` python +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} ``` \ No newline at end of file diff --git a/snippets/count_occurences.md b/snippets/count_occurences.md index 0d3726e5c..82dc746d7 100644 --- a/snippets/count_occurences.md +++ b/snippets/count_occurences.md @@ -1,18 +1,18 @@ -### count_occurences - -:information_source: Already implemented via `list.count()`. - -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. - -```python -def count_occurences(arr, val): - return reduce( - (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0), - arr) -``` - -```python -count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 +### count_occurences + +:information_source: Already implemented via `list.count()`. + +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. + +```python +def count_occurences(arr, val): + return reduce( + (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0), + arr) +``` + +```python +count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 ``` \ No newline at end of file diff --git a/snippets/count_vowels.md b/snippets/count_vowels.md index 2550cae19..256009312 100644 --- a/snippets/count_vowels.md +++ b/snippets/count_vowels.md @@ -1,18 +1,18 @@ -### count_vowels - -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 -import re - - -def count_vowels(str): - return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE))) -``` - -``` python -count_vowels('foobar') # 3 -count_vowels('gym') # 0 -``` +### count_vowels + +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 +import re + + +def count_vowels(str): + return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE))) +``` + +``` python +count_vowels('foobar') # 3 +count_vowels('gym') # 0 +``` diff --git a/snippets/decapitalize.md b/snippets/decapitalize.md index 2a41484bd..9667c5ccf 100644 --- a/snippets/decapitalize.md +++ b/snippets/decapitalize.md @@ -1,15 +1,15 @@ -### decapitalize - -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. - -```python -def decapitalize(string, upper_rest=False): - return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) -``` - -```python -decapitalize('FooBar') # 'fooBar' -decapitalize('FooBar', True) # 'fOOBAR' +### decapitalize + +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. + +```python +def decapitalize(string, upper_rest=False): + return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) +``` + +```python +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 dc8f35c18..3da31478d 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -1,27 +1,27 @@ -### 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. - -```python -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 -``` - -```python -deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] -``` +### 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. + +```python +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 +``` + +```python +deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] +``` diff --git a/snippets/difference.md b/snippets/difference.md index dedb95263..e8efec4d7 100644 --- a/snippets/difference.md +++ b/snippets/difference.md @@ -1,14 +1,14 @@ -### difference - -Returns the difference between two arrays. - -Create a `set` from `b`, then use list comprehension to only keep values not contained in `b` - -```python -def difference(a, b): - b = set(b) - return [item for item in a if item not in b] -``` -``` python -difference([1, 2, 3], [1, 2, 4]) # [3] +### difference + +Returns the difference between two arrays. + +Create a `set` from `b`, then use list comprehension to only keep values not contained in `b` + +```python +def difference(a, b): + b = set(b) + return [item for item in a if item not in b] +``` +``` python +difference([1, 2, 3], [1, 2, 4]) # [3] ``` \ No newline at end of file diff --git a/snippets/difference_by.md b/snippets/difference_by.md index a7801bfc9..5fcd004a2 100644 --- a/snippets/difference_by.md +++ b/snippets/difference_by.md @@ -1,17 +1,17 @@ -### difference_by - -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`. - -```python -def difference_by(a, b, fn): - b = set(map(fn, b)) - return [item for item in a if fn(item) not in b] -``` - -```python -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 } ] +### difference_by + +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`. + +```python +def difference_by(a, b, fn): + b = set(map(fn, b)) + return [item for item in a if fn(item) not in b] +``` + +```python +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 } ] ``` \ No newline at end of file diff --git a/snippets/factorial.md b/snippets/factorial.md index e7d3d6e81..2a303a11c 100644 --- a/snippets/factorial.md +++ b/snippets/factorial.md @@ -1,16 +1,16 @@ -### factorial - -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 -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 -factorial(6) # 720 -``` +### factorial + +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 +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 +factorial(6) # 720 +``` diff --git a/snippets/gcd.md b/snippets/gcd.md index cca70cb41..5922b24b5 100644 --- a/snippets/gcd.md +++ b/snippets/gcd.md @@ -1,38 +1,38 @@ -### gcd - -:information_source: `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. - -```python -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) -``` - - -``` python -gcd(8,36) # 4 +### gcd + +:information_source: `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. + +```python +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) +``` + + +``` python +gcd(8,36) # 4 ``` \ No newline at end of file diff --git a/snippets/insertion_sort.md b/snippets/insertion_sort.md index 6c6625272..1d2e912a5 100644 --- a/snippets/insertion_sort.md +++ b/snippets/insertion_sort.md @@ -7,11 +7,11 @@ def insertionsort(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 = i - 1 + while j >= 0 and key < arr[j]: + arr[j + 1] = arr[j] j -= 1 - arr[j+1] = key + arr[j + 1] = key ``` ```python diff --git a/snippets/is_lower_case.md b/snippets/is_lower_case.md index a702252a0..e760674db 100644 --- a/snippets/is_lower_case.md +++ b/snippets/is_lower_case.md @@ -1,16 +1,16 @@ -### 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. - -```python -def is_lower_case(str): - return str == str.lower() -``` - -```python -is_lower_case('abc') # True -is_lower_case('a3@$') # True -is_lower_case('Ab4') # False +### 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. + +```python +def is_lower_case(str): + return str == str.lower() +``` + +```python +is_lower_case('abc') # True +is_lower_case('a3@$') # True +is_lower_case('Ab4') # False ``` \ No newline at end of file diff --git a/snippets/is_upper_case.md b/snippets/is_upper_case.md index 0e26509b6..af1f35d55 100644 --- a/snippets/is_upper_case.md +++ b/snippets/is_upper_case.md @@ -1,16 +1,16 @@ -### 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. - -```python -def is_upper_case(str): - return str == str.upper() -``` - -```python -is_upper_case('ABC') # True -is_upper_case('a3@$') # True -is_upper_case('aB4') # False +### 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. + +```python +def is_upper_case(str): + return str == str.upper() +``` + +```python +is_upper_case('ABC') # True +is_upper_case('a3@$') # True +is_upper_case('aB4') # False ``` \ No newline at end of file diff --git a/snippets/lcm.md b/snippets/lcm.md index 59b75c08f..7400a6d4c 100644 --- a/snippets/lcm.md +++ b/snippets/lcm.md @@ -1,40 +1,40 @@ -### 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. - -```python -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) -``` - - -``` python -lcm(12, 7) # 84 -lcm([1, 3, 4], 5) # 60 +### 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. + +```python +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) +``` + + +``` python +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 cab451b17..05953faeb 100644 --- a/snippets/max_n.md +++ b/snippets/max_n.md @@ -1,21 +1,21 @@ -### 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 - -```python -from copy import deepcopy - - -def max_n(arr, n=1): - numbers = deepcopy(arr) - numbers.sort() - numbers.reverse() - return numbers[:n] -``` - -```python -max_n([1, 2, 3]) # [3] -max_n([1, 2, 3], 2) # [3,2] +### 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 + +```python +from copy import deepcopy + + +def max_n(arr, n=1): + numbers = deepcopy(arr) + numbers.sort() + numbers.reverse() + return numbers[:n] +``` + +```python +max_n([1, 2, 3]) # [3] +max_n([1, 2, 3], 2) # [3,2] ``` \ No newline at end of file diff --git a/snippets/min_n.md b/snippets/min_n.md index ee57f05c2..36a436d10 100644 --- a/snippets/min_n.md +++ b/snippets/min_n.md @@ -1,20 +1,20 @@ -### 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). - -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 -from copy import deepcopy - - -def min_n(arr, n=1): - numbers = deepcopy(arr) - numbers.sort() - return numbers[:n] -``` - -```python -min_n([1, 2, 3]) # [1] -min_n([1, 2, 3], 2) # [1,2] +### 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). + +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 +from copy import deepcopy + + +def min_n(arr, n=1): + numbers = deepcopy(arr) + numbers.sort() + return numbers[:n] +``` + +```python +min_n([1, 2, 3]) # [1] +min_n([1, 2, 3], 2) # [1,2] ``` \ No newline at end of file diff --git a/snippets/palindrome.md b/snippets/palindrome.md index 20efc8259..4764aaf3a 100644 --- a/snippets/palindrome.md +++ b/snippets/palindrome.md @@ -1,15 +1,15 @@ -### palindrome - -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 -def palindrome(string): - from re import sub - s = sub('[\W_]', '', string.lower()) - return s == s[::-1] -``` -```python -palindrome('taco cat') # True +### palindrome + +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 +def palindrome(string): + from re import sub + s = sub('[\W_]', '', string.lower()) + return s == s[::-1] +``` +```python +palindrome('taco cat') # True ``` \ No newline at end of file diff --git a/snippets/shuffle.md b/snippets/shuffle.md index 4d27274b7..536591f1e 100644 --- a/snippets/shuffle.md +++ b/snippets/shuffle.md @@ -1,27 +1,27 @@ -### 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. - -Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. - -```python -from copy import deepcopy -from random import randint - - -def shuffle(arr): - temp_arr = deepcopy(arr) - m = len(temp_arr) - while (m): - m -= 1 - i = randint(0, m) - temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m] - return temp_arr -``` - -``` python -foo = [1,2,3] -shuffle(foo) # [2,3,1] , foo = [1,2,3] +### 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. + +Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. + +```python +from copy import deepcopy +from random import randint + + +def shuffle(arr): + temp_arr = deepcopy(arr) + m = len(temp_arr) + while (m): + m -= 1 + i = randint(0, m) + temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m] + return temp_arr +``` + +``` python +foo = [1,2,3] +shuffle(foo) # [2,3,1] , foo = [1,2,3] ``` \ No newline at end of file diff --git a/snippets/spread.md b/snippets/spread.md index 65e0becd3..c37fae703 100644 --- a/snippets/spread.md +++ b/snippets/spread.md @@ -1,19 +1,19 @@ -### spread - -Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. - -```python -def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) - return ret -``` - - -```python -spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] +### spread + +Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. + +```python +def spread(arg): + ret = [] + for i in arg: + if isinstance(i, list): + ret.extend(i) + else: + ret.append(i) + return ret +``` + + +```python +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/zip.md b/snippets/zip.md index f10ced8d4..c36700aab 100644 --- a/snippets/zip.md +++ b/snippets/zip.md @@ -1,24 +1,24 @@ -### zip - -:information_source: Already implemented via `itertools.zip_longest()` - -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 -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 -``` - -``` python -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]] +### zip + +:information_source: Already implemented via `itertools.zip_longest()` + +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 +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 +``` + +``` python +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]] ``` \ No newline at end of file diff --git a/tag_database b/tag_database index 4c4918959..b3ba59a8f 100644 --- a/tag_database +++ b/tag_database @@ -22,4 +22,4 @@ is_upper_case:string is_lower_case:string count_by:list difference_by:list -insertion_sort:list +insertion_sort:list \ No newline at end of file