From 55f39b14bd6904927e95375a4542c20ddfda115b Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Thu, 1 Feb 2018 13:49:59 +0530 Subject: [PATCH] new snippets --- README.md | 191 +++++++++++++++++++++++++++--- scripts/lint.py | 2 +- scripts/readme.py | 3 +- snippets/average.md | 1 - snippets/byte_size.md | 15 +++ snippets/capitalize.md | 15 +++ snippets/capitalize_every_word.md | 14 +++ snippets/chunk.md | 1 - snippets/compact.md | 1 - snippets/count_occurences.md | 1 - snippets/count_vowels.md | 1 - snippets/decapitalize.md | 15 +++ snippets/deep_flatten.md | 1 - snippets/difference.md | 1 - snippets/factorial.md | 1 - snippets/gcd.md | 1 - snippets/is_lower_case.md | 16 +++ snippets/is_upper_case.md | 16 +++ snippets/lcm.md | 1 - snippets/max_n.md | 1 - snippets/min_n.md | 1 - snippets/palindrome.md | 15 +++ snippets/shuffle.md | 1 - snippets/spread.md | 1 - snippets/zip.md | 1 - static-parts/index-start.html | 0 tag_database | 9 +- 27 files changed, 292 insertions(+), 34 deletions(-) create mode 100644 snippets/byte_size.md create mode 100644 snippets/capitalize.md create mode 100644 snippets/capitalize_every_word.md create mode 100644 snippets/decapitalize.md create mode 100644 snippets/is_lower_case.md create mode 100644 snippets/is_upper_case.md create mode 100644 snippets/palindrome.md create mode 100644 static-parts/index-start.html diff --git a/README.md b/README.md index 8a3002fdb..10db657c7 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,13 @@ ### :scroll: String
View contents

@@ -49,7 +56,6 @@ 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) @@ -74,7 +80,6 @@ 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( @@ -104,7 +109,6 @@ The `helperGcdfunction` uses recursion. Base case is when `y` equals `0`. In thi 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 @@ -150,7 +154,6 @@ Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists. ```py - from functools import reduce @@ -198,7 +201,6 @@ Returns the `n` maximum elements from the provided list. If `n` is greater than Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order and then use `list.reverse()` reverse it to make it descending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array ```py - from copy import deepcopy @@ -229,7 +231,6 @@ Returns the `n` minimum elements from the provided list. If `n` is greater than Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array ```py - from copy import deepcopy @@ -261,7 +262,6 @@ 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 @@ -290,7 +290,6 @@ 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)) @@ -316,7 +315,6 @@ 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), @@ -342,7 +340,6 @@ 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: @@ -379,7 +376,6 @@ 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] @@ -405,7 +401,6 @@ 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 @@ -438,7 +433,6 @@ shuffle(foo) # [2,3,1] , foo = [1,2,3] Implements javascript's spread syntax as a function. Flattens the list(non-deep) and returns an list. ```py - def spread(arg): ret = [] for i in arg: @@ -471,7 +465,6 @@ 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 = [] @@ -505,7 +498,6 @@ 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 @@ -526,6 +518,175 @@ count_vowels('gym') # 0
:arrow_up: Back to top +### 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 + +### 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 + +### 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 + +### 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 + +### 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 + ## Credits diff --git a/scripts/lint.py b/scripts/lint.py index 2324adfe3..3eae6198f 100644 --- a/scripts/lint.py +++ b/scripts/lint.py @@ -10,7 +10,7 @@ for file in files: someFile.close() originalCode = re.search(codeRe,fileData).group(0) #print(re.split(codeRe,fileData)[0]) - formatedCode = autopep8.fix_code(re.split(codeRe,fileData)[1]) + formatedCode = '\n'+autopep8.fix_code(re.split(codeRe,fileData)[1]).strip()+'\n' fileToSave = fileData.replace(originalCode,('```python'+formatedCode+'```')) someFile = open("snippets/"+file,'w') someFile.write(fileToSave) diff --git a/scripts/readme.py b/scripts/readme.py index 78e1e6a78..14303d834 100644 --- a/scripts/readme.py +++ b/scripts/readme.py @@ -31,7 +31,6 @@ def tagger(): tag_dict[category] = [snippet] return tag_dict -files = os.listdir('snippets') start = open("static-parts/readme-start.md").read() + '\n\n' end = open("static-parts/readme-end.md").read() toAppend = '' @@ -50,4 +49,4 @@ for category in tag_dict: fileData = someFile.read() codeParts = re.split(codeRe,fileData) toAppend += codeParts[0] + f'```py{codeParts[1]} \n ```' +codeParts[2] + f'
View Examples\n\n```py\n{codeParts[3]}\n```\n
\n\n
:arrow_up: Back to top\n ' + '\n' -open("README.md",'w').write(start+toAppend+'\n'+end) +open("README.md",'w').write(start+toAppend+'\n'+end) \ No newline at end of file diff --git a/snippets/average.md b/snippets/average.md index 33a2480c3..746f6f746 100644 --- a/snippets/average.md +++ b/snippets/average.md @@ -7,7 +7,6 @@ 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) ``` diff --git a/snippets/byte_size.md b/snippets/byte_size.md new file mode 100644 index 000000000..faa8ba5fd --- /dev/null +++ b/snippets/byte_size.md @@ -0,0 +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 +``` \ No newline at end of file diff --git a/snippets/capitalize.md b/snippets/capitalize.md new file mode 100644 index 000000000..61f1b3294 --- /dev/null +++ b/snippets/capitalize.md @@ -0,0 +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' +``` \ No newline at end of file diff --git a/snippets/capitalize_every_word.md b/snippets/capitalize_every_word.md new file mode 100644 index 000000000..ba0c8f273 --- /dev/null +++ b/snippets/capitalize_every_word.md @@ -0,0 +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!' +``` \ No newline at end of file diff --git a/snippets/chunk.md b/snippets/chunk.md index 5b8d500f9..d6dc58060 100644 --- a/snippets/chunk.md +++ b/snippets/chunk.md @@ -5,7 +5,6 @@ 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 diff --git a/snippets/compact.md b/snippets/compact.md index 188e9a3fb..51f14918e 100644 --- a/snippets/compact.md +++ b/snippets/compact.md @@ -5,7 +5,6 @@ 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)) ``` diff --git a/snippets/count_occurences.md b/snippets/count_occurences.md index f580d5fb8..82dc746d7 100644 --- a/snippets/count_occurences.md +++ b/snippets/count_occurences.md @@ -7,7 +7,6 @@ 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), diff --git a/snippets/count_vowels.md b/snippets/count_vowels.md index 69a35f4d0..256009312 100644 --- a/snippets/count_vowels.md +++ b/snippets/count_vowels.md @@ -5,7 +5,6 @@ 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 diff --git a/snippets/decapitalize.md b/snippets/decapitalize.md new file mode 100644 index 000000000..9667c5ccf --- /dev/null +++ b/snippets/decapitalize.md @@ -0,0 +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' +``` \ No newline at end of file diff --git a/snippets/deep_flatten.md b/snippets/deep_flatten.md index 877f0ef78..3da31478d 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -5,7 +5,6 @@ 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: diff --git a/snippets/difference.md b/snippets/difference.md index 189b74902..e8efec4d7 100644 --- a/snippets/difference.md +++ b/snippets/difference.md @@ -5,7 +5,6 @@ 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] diff --git a/snippets/factorial.md b/snippets/factorial.md index 19afdf942..2a303a11c 100644 --- a/snippets/factorial.md +++ b/snippets/factorial.md @@ -5,7 +5,6 @@ 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( diff --git a/snippets/gcd.md b/snippets/gcd.md index e66f371e4..5922b24b5 100644 --- a/snippets/gcd.md +++ b/snippets/gcd.md @@ -9,7 +9,6 @@ The `helperGcdfunction` uses recursion. Base case is when `y` equals `0`. In thi 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 diff --git a/snippets/is_lower_case.md b/snippets/is_lower_case.md new file mode 100644 index 000000000..e760674db --- /dev/null +++ b/snippets/is_lower_case.md @@ -0,0 +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 +``` \ No newline at end of file diff --git a/snippets/is_upper_case.md b/snippets/is_upper_case.md new file mode 100644 index 000000000..af1f35d55 --- /dev/null +++ b/snippets/is_upper_case.md @@ -0,0 +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 +``` \ No newline at end of file diff --git a/snippets/lcm.md b/snippets/lcm.md index 1085433d3..7400a6d4c 100644 --- a/snippets/lcm.md +++ b/snippets/lcm.md @@ -7,7 +7,6 @@ Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists. ```python - from functools import reduce diff --git a/snippets/max_n.md b/snippets/max_n.md index c1827aaf3..05953faeb 100644 --- a/snippets/max_n.md +++ b/snippets/max_n.md @@ -5,7 +5,6 @@ Returns the `n` maximum elements from the provided list. If `n` is greater than Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order and then use `list.reverse()` reverse it to make it descending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array ```python - from copy import deepcopy diff --git a/snippets/min_n.md b/snippets/min_n.md index 69de68e37..36a436d10 100644 --- a/snippets/min_n.md +++ b/snippets/min_n.md @@ -5,7 +5,6 @@ Returns the `n` minimum elements from the provided list. If `n` is greater than Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array ```python - from copy import deepcopy diff --git a/snippets/palindrome.md b/snippets/palindrome.md new file mode 100644 index 000000000..4764aaf3a --- /dev/null +++ b/snippets/palindrome.md @@ -0,0 +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 +``` \ No newline at end of file diff --git a/snippets/shuffle.md b/snippets/shuffle.md index 6fce8b819..536591f1e 100644 --- a/snippets/shuffle.md +++ b/snippets/shuffle.md @@ -7,7 +7,6 @@ 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 diff --git a/snippets/spread.md b/snippets/spread.md index 2eaf23f81..c03d2a080 100644 --- a/snippets/spread.md +++ b/snippets/spread.md @@ -3,7 +3,6 @@ Implements javascript's spread syntax as a function. Flattens the list(non-deep) and returns an list. ```python - def spread(arg): ret = [] for i in arg: diff --git a/snippets/zip.md b/snippets/zip.md index 9f168989f..c36700aab 100644 --- a/snippets/zip.md +++ b/snippets/zip.md @@ -7,7 +7,6 @@ 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 = [] diff --git a/static-parts/index-start.html b/static-parts/index-start.html new file mode 100644 index 000000000..e69de29bb diff --git a/tag_database b/tag_database index b567d72b5..72a4fa20c 100644 --- a/tag_database +++ b/tag_database @@ -12,4 +12,11 @@ max_n:math min_n:math shuffle:list spread:list -zip:list \ No newline at end of file +zip:list +byte_size:string +capitalize:string +capitalize_every_word:string +decapitalize:string +palindrome:string +is_upper_case:string +is_lower_case:string \ No newline at end of file