diff --git a/.travis/push.sh b/.travis/push.sh index b797b8420..48610bcfa 100755 --- a/.travis/push.sh +++ b/.travis/push.sh @@ -25,7 +25,7 @@ upload_files() { if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then if [ $TRAVIS_BRANCH == "master" ]; then echo "Pushing to master branch..." - git push --force --quiet "https://${GH_TOKEN}@github.com/30-seconds/30-seconds-of-python-code.git" master > /dev/null 2>&1 + git push --force --quiet "https://${GH_TOKEN}@github.com/30-seconds/30-seconds-of-python.git" master > /dev/null 2>&1 fi fi } diff --git a/COLLABORATING.md b/COLLABORATING.md index 86677db56..f8f7f0ebb 100644 --- a/COLLABORATING.md +++ b/COLLABORATING.md @@ -13,7 +13,7 @@ As a member of the team that manages **30 seconds of python code**, you have the ## Guidelines for merging pull requests and making changes to the project -- **[Usual guidelines](https://github.com/30-seconds/30-seconds-of-python-code/blob/master/CONTRIBUTING.md) apply.** Make sure to follow them, like everybody else. +- **[Usual guidelines](https://github.com/30-seconds/30-seconds-of-python/blob/master/CONTRIBUTING.md) apply.** Make sure to follow them, like everybody else. - **For a pull request to be considered ready to merge, there should be at least 2 (preferably 3) reviews approving it for merge.** There are, however, certain exceptions: - **If a pull request only fixes typos**, there is no need to wait for a second reviewer (unless you are not certain these were not typos in the first place). - **If a pull request only clarifies a snippet's description or enforces the style guide for an existing snippet**, you might be able to merge it without getting a second reviewer to review it, but only if you are certain about it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 72d5df377..393763409 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,11 +4,11 @@ Here's what you can do to help: -- [Open issues](https://github.com/30-seconds/30-seconds-of-python-code/issues/new) for things you want to see added or modified. -- Be part of the discussion by helping out with [existing issues](https://github.com/30-seconds/30-seconds-of-python-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-python-code/Lobby). -- Submit [pull requests](https://github.com/30-seconds/30-seconds-of-python-code/pulls) with snippets you have created (see below for guidelines). +- [Open issues](https://github.com/30-seconds/30-seconds-of-python/issues/new) for things you want to see added or modified. +- Be part of the discussion by helping out with [existing issues](https://github.com/30-seconds/30-seconds-of-python/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-python/Lobby). +- Submit [pull requests](https://github.com/30-seconds/30-seconds-of-python/pulls) with snippets you have created (see below for guidelines). - Fix typos in existing snippets, improve snippet descriptions and explanations or provide better examples. -- Before submitting a PR for any new snippets go through [this](https://github.com/30-seconds/30-seconds-of-python-code/projects/1) project. If your snippet is not there, then go ahead and submit a PR. Else if it is in the done column, sorry it has been already implemented. If it is in any other column submit a PR and give the card's link in the description section of PR. +- Before submitting a PR for any new snippets go through [this](https://github.com/30-seconds/30-seconds-of-python/projects/1) project. If your snippet is not there, then go ahead and submit a PR. Else if it is in the done column, sorry it has been already implemented. If it is in any other column submit a PR and give the card's link in the description section of PR. - **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github) ### Snippet submission and Pull request guidelines diff --git a/README.md b/README.md index a8a9753b3..63806af1a 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,24 @@ -![Logo](/icon.png) - -## 30-seconds-of-python-code - -> Curated collection of useful Python snippets that you can understand in 30 seconds or less. - -* Use Ctrl + F or command + F to search for a snippet. -* Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). -* If you want to follow 30-seconds-of-code on social media, you can find us on [Facebook](https://www.facebook.com/30secondsofcode), [Instagram](https://www.instagram.com/30secondsofcode) and [Twitter](https://twitter.com/30secondsofcode). - -#### Related projects - -* [30 Seconds of code](https://github.com/30-seconds/30-seconds-of-code) -* [30 Seconds of CSS](https://30-seconds.github.io/30-seconds-of-css/) -* [30 Seconds of Interviews](https://30secondsofinterviews.org/) -* [30 Seconds of React](https://github.com/30-seconds/30-seconds-of-react) -* [30 Seconds of PHP](https://github.com/30-seconds/30-seconds-of-php-code) -* [30 Seconds of Knowledge](https://chrome.google.com/webstore/detail/30-seconds-of-knowledge/mmgplondnjekobonklacmemikcnhklla) -* [30 Seconds of Kotlin](https://github.com/IvanMwiruki/30-seconds-of-kotlin) _(unofficial)_ - -## Contents +![Logo](/icon.png) + +## 30-seconds-of-python + +> Curated collection of useful Python snippets that you can understand in 30 seconds or less. + +* Use Ctrl + F or command + F to search for a snippet. +* Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). +* If you want to follow 30-seconds-of-code on social media, you can find us on [Facebook](https://www.facebook.com/30secondsofcode), [Instagram](https://www.instagram.com/30secondsofcode) and [Twitter](https://twitter.com/30secondsofcode). + +#### Related projects + +* [30 Seconds of code](https://github.com/30-seconds/30-seconds-of-code) +* [30 Seconds of CSS](https://30-seconds.github.io/30-seconds-of-css/) +* [30 Seconds of Interviews](https://30secondsofinterviews.org/) +* [30 Seconds of React](https://github.com/30-seconds/30-seconds-of-react) +* [30 Seconds of PHP](https://github.com/30-seconds/30-seconds-of-php-code) +* [30 Seconds of Knowledge](https://chrome.google.com/webstore/detail/30-seconds-of-knowledge/mmgplondnjekobonklacmemikcnhklla) +* [30 Seconds of Kotlin](https://github.com/IvanMwiruki/30-seconds-of-kotlin) _(unofficial)_ + +## Contents ### List @@ -146,7 +146,7 @@ Check if all elements in a list are equal. Use `[1:]` and `[:-1]` to compare all the values in the given list. ```py -def all_equal(lst): +def all_equal(lst): return lst[1:] == lst[:-1] ``` @@ -154,7 +154,7 @@ def all_equal(lst): Examples ```py -all_equal([1, 2, 3, 4, 5, 6]) # False +all_equal([1, 2, 3, 4, 5, 6]) # False all_equal([1, 1, 1, 1]) # True ``` @@ -168,7 +168,7 @@ Returns `True` if all the values in a flat list are unique, `False` otherwise. Use `set()` on the given list to remove duplicates, compare its length with the length of the list. ```py -def all_unique(lst): +def all_unique(lst): return len(lst) == len(set(lst)) ``` @@ -176,9 +176,9 @@ def all_unique(lst): Examples ```py -x = [1,2,3,4,5,6] -y = [1,2,2,3,4,5] -all_unique(x) # True +x = [1,2,3,4,5,6] +y = [1,2,2,3,4,5] +all_unique(x) # True all_unique(y) # False ``` @@ -193,10 +193,10 @@ If an element in `filter` is `True`, the corresponding element in the collection Use list comprehension and `enumerate()` to add elements to groups, based on `filter`. ```py -def bifurcate(lst, filter): - return [ - [x for i,x in enumerate(lst) if filter[i] == True], - [x for i,x in enumerate(lst) if filter[i] == False] +def bifurcate(lst, filter): + return [ + [x for i,x in enumerate(lst) if filter[i] == True], + [x for i,x in enumerate(lst) if filter[i] == False] ] ``` @@ -218,10 +218,10 @@ If the function returns `True`, the element belongs to the first group; otherwis Use list comprehension to add elements to groups, based on `fn`. ```py -def bifurcate_by(lst, fn): - return [ - [x for x in lst if fn(x)], - [x for x in lst if not fn(x)] +def bifurcate_by(lst, fn): + return [ + [x for x in lst if fn(x)], + [x for x in lst if not fn(x)] ] ``` @@ -244,11 +244,11 @@ Use `map()` on the list and fill it with splices of the given list. Finally, return use created list. ```py -from math import ceil - -def chunk(lst, size): - return list( - map(lambda x: lst[x * size:x * size + size], +from math import ceil + +def chunk(lst, size): + return list( + map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size))))) ``` @@ -269,7 +269,7 @@ Removes falsey values from a list. Use `filter()` to filter out falsey values (`False`, `None`, `0`, and `""`). ```py -def compact(lst): +def compact(lst): return list(filter(bool, lst)) ``` @@ -291,11 +291,11 @@ Use `map()` to map the values of the given list using the given function. Iterate over the map and increase the element 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 el not in key else key[el] - key[el] += 1 +def count_by(arr, fn=lambda x: x): + key = {} + for el in map(fn, arr): + key[el] = 0 if el not in key else key[el] + key[el] += 1 return key ``` @@ -303,8 +303,8 @@ def count_by(arr, fn=lambda x: x): Examples ```py -from math import floor -count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2} +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} ``` @@ -318,7 +318,7 @@ Counts the occurrences of a value in a list. Increment a counter for every item in the list that has the given value and is of the same type. ```py -def count_occurrences(lst, val): +def count_occurrences(lst, val): return len([x for x in lst if x == val and type(x) == type(val)]) ``` @@ -342,19 +342,19 @@ Use `list.extend()` with an empty list and the `spread` function to flatten a li 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(lst): - result = [] - result.extend( - spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) +def spread(arg): + ret = [] + for i in arg: + if isinstance(i, list): + ret.extend(i) + else: + ret.append(i) + return ret + +def deep_flatten(lst): + result = [] + result.extend( + spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) return result ``` @@ -375,8 +375,8 @@ Returns the difference between two iterables. Create a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`. ```py -def difference(a, b): - _b = set(b) +def difference(a, b): + _b = set(b) return [item for item in a if item not in _b] ``` @@ -397,8 +397,8 @@ Returns the difference between two lists, after applying the provided function t 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, `_b`. ```py -def difference_by(a, b, fn): - _b = set(map(fn, b)) +def difference_by(a, b, fn): + _b = set(map(fn, b)) return [item for item in a if fn(item) not in _b] ``` @@ -406,8 +406,8 @@ def difference_by(a, b, fn): Examples ```py -from math import floor -difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2] +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 } ] ``` @@ -422,10 +422,10 @@ Iterate over the elements of the list to test if every element in the list retur Omit the seconds argument, `fn`, to check if all elements are `True`. ```py -def every(lst, fn=lambda x: not not x): - for el in lst: - if not fn(el): - return False +def every(lst, fn=lambda x: not not x): + for el in lst: + if not fn(el): + return False return True ``` @@ -433,7 +433,7 @@ def every(lst, fn=lambda x: not not x): Examples ```py -every([4, 2, 3], lambda x: x > 1) # True +every([4, 2, 3], lambda x: x > 1) # True every([1, 2, 3]) # True ``` @@ -447,7 +447,7 @@ Returns every nth element in a list. Use `[1::nth]` to create a new list that contains every nth element of the given list. ```py -def every_nth(lst, nth): +def every_nth(lst, nth): return lst[1::nth] ``` @@ -468,7 +468,7 @@ Filters out the non-unique values in a list. Use list comprehension and `list.count()` to create a list containing only the unique values. ```py -def filter_non_unique(lst): +def filter_non_unique(lst): return [item for item in lst if lst.count(item) == 1] ``` @@ -490,10 +490,10 @@ Use `list()` in combination with `map()` and `fn` to map the values of the list Use list comprehension to map each element to the appropriate `key`. ```py -def group_by(lst, fn): - groups = {} - for key in list(map(fn,lst)): - groups[key] = [item for item in lst if fn(item) == key] +def group_by(lst, fn): + groups = {} + for key in list(map(fn,lst)): + groups[key] = [item for item in lst if fn(item) == key] return groups ``` @@ -501,8 +501,8 @@ def group_by(lst, fn): Examples ```py -import math -group_by([6.1, 4.2, 6.3], math.floor); # {4: [4.2], 6: [6.1, 6.3]} +import math +group_by([6.1, 4.2, 6.3], math.floor); # {4: [4.2], 6: [6.1, 6.3]} group_by(['one', 'two', 'three'], 'length'); # {3: ['one', 'two'], 5: ['three']} ``` @@ -516,7 +516,7 @@ Returns `True` if there are duplicate values in a flast list, `False` otherwise. Use `set()` on the given list to remove duplicates, compare its length with the length of the list. ```py -def has_duplicates(lst): +def has_duplicates(lst): return len(lst) != len(set(lst)) ``` @@ -524,9 +524,9 @@ def has_duplicates(lst): Examples ```py -x = [1,2,3,4,5,5] -y = [1,2,3,4,5] -has_duplicates(x) # True +x = [1,2,3,4,5,5] +y = [1,2,3,4,5] +has_duplicates(x) # True has_duplicates(y) # False ``` @@ -540,7 +540,7 @@ Returns the head of a list. use `lst[0]` to return the first element of the passed list. ```py -def head(lst): +def head(lst): return lst[0] ``` @@ -561,7 +561,7 @@ Returns all the elements of a list except the last one. Use `lst[0:-1]` to return all but the last element of the list. ```py -def initial(lst): +def initial(lst): return lst[0:-1] ``` @@ -585,7 +585,7 @@ If `val` is not provided, default to `None`. Explain briefly how the snippet works. ```py -def initialize_2d_list(w,h, val = None): +def initialize_2d_list(w,h, val = None): return [[val for x in range(w)] for y in range(h)] ``` @@ -608,7 +608,7 @@ Omit `start` to use the default value of `0`. Omit `step` to use the default value of `1`. ```py -def initialize_list_with_range(end, start = 0, step = 1): +def initialize_list_with_range(end, start = 0, step = 1): return [x for x in range(start, end + 1, step)] ``` @@ -616,8 +616,8 @@ def initialize_list_with_range(end, start = 0, step = 1): Examples ```py -initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5] -initialize_list_with_range(7,3) # [3, 4, 5, 6, 7] +initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5] +initialize_list_with_range(7,3) # [3, 4, 5, 6, 7] initialize_list_with_range(9,0,2) # [0, 2, 4, 6, 8] ``` @@ -632,7 +632,7 @@ Use list comprehension and `range()` to generate a list of length equal to `n`, Omit `val` to use the default value of `0`. ```py -def initialize_list_with_values(n, val = 0): +def initialize_list_with_values(n, val = 0): return [val for x in range(n)] ``` @@ -653,8 +653,8 @@ Returns a list of elements that exist in both lists. Create a `set` from `b`, then use list comprehension on `a` to only keep values contained in both lists. ```py -def intersection(a, b): - _b = set(b) +def intersection(a, b): + _b = set(b) return [item for item in a if item in _b] ``` @@ -675,8 +675,8 @@ Returns a list of elements that exist in both lists, after applying the provided 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 contained in both lists. ```py -def intersection_by(a, b, fn): - _b = set(map(fn, b)) +def intersection_by(a, b, fn): + _b = set(map(fn, b)) return [item for item in a if fn(item) in _b] ``` @@ -684,7 +684,7 @@ def intersection_by(a, b, fn): Examples ```py -from math import floor +from math import floor intersection_by([2.1, 1.2], [2.3, 3.4],floor) # [2.1] ``` @@ -698,7 +698,7 @@ Returns the last element in a list. use `lst[-1]` to return the last element of the passed list. ```py -def last(lst): +def last(lst): return lst[-1] ``` @@ -720,7 +720,7 @@ If multiple objects have the same length, the first one will be returned. Use `max()` with `len` as the `key` to return the item with the greatest length. ```py -def longest_item(*args): +def longest_item(*args): return max(args, key = len) ``` @@ -728,8 +728,8 @@ def longest_item(*args): Examples ```py -longest_item('this', 'is', 'a', 'testcase') # 'testcase' -longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5] +longest_item('this', 'is', 'a', 'testcase') # 'testcase' +longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5] longest_item([1, 2, 3], 'foobar') # 'foobar' ``` @@ -745,7 +745,7 @@ Use `sorted() to sort the list, `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element list. ```py -def max_n(lst, n=1): +def max_n(lst, n=1): return sorted(lst, reverse=True)[:n] ``` @@ -753,7 +753,7 @@ def max_n(lst, n=1): Examples ```py -max_n([1, 2, 3]) # [3] +max_n([1, 2, 3]) # [3] max_n([1, 2, 3], 2) # [3,2] ``` @@ -769,7 +769,7 @@ Use `sorted() to sort the list, `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element list. ```py -def min_n(lst, n=1): +def min_n(lst, n=1): return sorted(lst, reverse=False)[:n] ``` @@ -777,7 +777,7 @@ def min_n(lst, n=1): Examples ```py -min_n([1, 2, 3]) # [1] +min_n([1, 2, 3]) # [1] min_n([1, 2, 3], 2) # [1,2] ``` @@ -792,10 +792,10 @@ Iterate over the elements of the list to test if every element in the list retur Omit the seconds argument, `fn`, to check if all elements are `False`. ```py -def none(lst, fn=lambda x: not not x): - for el in lst: - if fn(el): - return False +def none(lst, fn=lambda x: not not x): + for el in lst: + if fn(el): + return False return True ``` @@ -803,7 +803,7 @@ def none(lst, fn=lambda x: not not x): Examples ```py -none([0, 1, 2, 0], lambda x: x >= 2 ) # False +none([0, 1, 2, 0], lambda x: x >= 2 ) # False none([0, 0, 0]) # True ``` @@ -819,7 +819,7 @@ Use `lst[offset:]` and `lst[:offset]` to get the two slices of the list and comb Explain briefly how the snippet works. ```py -def offset(lst, offset): +def offset(lst, offset): return lst[offset:] + lst[:offset] ``` @@ -827,7 +827,7 @@ def offset(lst, offset): Examples ```py -offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2] +offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2] offset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3] ``` @@ -841,9 +841,9 @@ Returns a random element from an array. Use `randint()` to generate a random number that corresponds to an index in the list, return the element at that index. ```py -from random import randint - -def sample(lst): +from random import randint + +def sample(lst): return lst[randint(0, len(lst) - 1)] ``` @@ -864,16 +864,16 @@ 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(lst): - temp_lst = deepcopy(lst) - m = len(temp_lst) - while (m): - m -= 1 - i = randint(0, m) - temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] +from copy import deepcopy +from random import randint + +def shuffle(lst): + temp_lst = deepcopy(lst) + m = len(temp_lst) + while (m): + m -= 1 + i = randint(0, m) + temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] return temp_lst ``` @@ -881,7 +881,7 @@ def shuffle(lst): Examples ```py -foo = [1,2,3] +foo = [1,2,3] shuffle(foo) # [2,3,1] , foo = [1,2,3] ``` @@ -895,7 +895,7 @@ Returns a list of elements that exist in both lists. Use list comprehension on `a` to only keep values contained in both lists. ```py -def similarity(a, b): +def similarity(a, b): return [item for item in a if item in b] ``` @@ -917,10 +917,10 @@ Iterate over the elements of the list to test if every element in the list retur Omit the seconds argument, `fn`, to check if all elements are `True`. ```py -def some(lst, fn=lambda x: not not x): - for el in lst: - if fn(el): - return True +def some(lst, fn=lambda x: not not x): + for el in lst: + if fn(el): + return True return False ``` @@ -928,7 +928,7 @@ def some(lst, fn=lambda x: not not x): Examples ```py -some([0, 1, 2, 0], lambda x: x >= 2 ) # True +some([0, 1, 2, 0], lambda x: x >= 2 ) # True some([0, 0, 1, 0]) # True ``` @@ -942,13 +942,13 @@ Flattens a list, by spreading its elements into a new list. Loop over elements, use `list.extend()` if the element is a list, `list.append()` otherwise. ```py -def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) +def spread(arg): + ret = [] + for i in arg: + if isinstance(i, list): + ret.extend(i) + else: + ret.append(i) return ret ``` @@ -969,8 +969,8 @@ Returns the symmetric difference between two iterables, without filtering out du Create a `set` from each list, then use list comprehension on each one to only keep values not contained in the previously created set of the other. ```py -def symmetric_difference(a, b): - _a, _b = set(a), set(b) +def symmetric_difference(a, b): + _a, _b = set(a), set(b) return [item for item in a if item not in _b] + [item for item in b if item not in _a] ``` @@ -991,8 +991,8 @@ Returns the symmetric difference between two lists, after applying the provided Create a `set` by applying `fn` to each element in every list, then use list comprehension in combination with `fn` on each one to only keep values not contained in the previously created set of the other. ```py -def symmetric_difference_by(a, b, fn): - _a, _b = set(map(fn, a)), set(map(fn, b)) +def symmetric_difference_by(a, b, fn): + _a, _b = set(map(fn, a)), set(map(fn, b)) return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a] ``` @@ -1000,7 +1000,7 @@ def symmetric_difference_by(a, b, fn): Examples ```py -from math import floor +from math import floor symmetric_difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2, 3.4] ``` @@ -1014,7 +1014,7 @@ Returns all elements in a list except for the first one. Return `lst[1:]` if the list's length is more than `1`, otherwise, return the whole list. ```py -def tail(lst): +def tail(lst): return lst[1:] if len(lst) > 1 else lst ``` @@ -1022,7 +1022,7 @@ def tail(lst): Examples ```py -tail([1, 2, 3]); # [2,3] +tail([1, 2, 3]); # [2,3] tail([1]); # [1] ``` @@ -1036,7 +1036,7 @@ Returns every element that exists in any of the two lists once. Create a `set` with all values of `a` and `b` and convert to a `list`. ```py -def union(a,b): +def union(a,b): return list(set(a + b)) ``` @@ -1058,8 +1058,8 @@ Create a `set` by applying `fn` to each element in `a`, then use list comprehens Finally, create a `set` from the previous result and `a` and transform it into a `list` ```py -def union_by(a,b,fn): - _a = set(map(fn, a)) +def union_by(a,b,fn): + _a = set(map(fn, a)) return list(set(a + [item for item in b if fn(item) not in _a])) ``` @@ -1067,7 +1067,7 @@ def union_by(a,b,fn): Examples ```py -from math import floor +from math import floor union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2] ``` @@ -1081,7 +1081,7 @@ Returns the unique elements in a given list. Create a `set` from the list to discard duplicated values, then return a `list` from it. ```py -def unique_elements(li): +def unique_elements(li): return list(set(li)) ``` @@ -1105,13 +1105,13 @@ Loop for `max_length` times grouping elements. If lengths of `lists` vary, use `fill_value` (defaults to `None`). ```py -def zip(*args, fillvalue=None): - max_length = max([len(lst) for lst in args]) - result = [] - for i in range(max_length): - result.append([ - args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args)) - ]) +def zip(*args, fillvalue=None): + max_length = max([len(lst) for lst in args]) + result = [] + for i in range(max_length): + result.append([ + args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args)) + ]) return result ``` @@ -1119,8 +1119,8 @@ def zip(*args, fillvalue=None): 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', '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]] ``` @@ -1139,7 +1139,7 @@ Returns the average of two or more numbers. Use `sum()` to sum all of the `args` provided, divide by `len(args)`. ```py -def average(*args): +def average(*args): return sum(args, 0.0) / len(args) ``` @@ -1147,7 +1147,7 @@ def average(*args): Examples ```py -average(*[1, 2, 3]) # 2.0 +average(*[1, 2, 3]) # 2.0 average(1, 2, 3) # 2.0 ``` @@ -1162,7 +1162,7 @@ Use `map()` to map each element to the value returned by `fn`. Use `sum()` to sum all of the mapped values, divide by `len(lst)`. ```py -def average_by(lst, fn=lambda x: x): +def average_by(lst, fn=lambda x: x): return sum(map(fn, lst), 0.0) / len(lst) ``` @@ -1184,7 +1184,7 @@ If `num` falls within the range, return `num`. Otherwise, return the nearest number in the range. ```py -def clamp_number(num,a,b): +def clamp_number(num,a,b): return max(min(num, max(a,b)),min(a,b)) ``` @@ -1192,7 +1192,7 @@ def clamp_number(num,a,b): Examples ```py -clamp_number(2, 3, 5) # 3 +clamp_number(2, 3, 5) # 3 clamp_number(1, -1, -5) # -1 ``` @@ -1206,7 +1206,7 @@ Converts a number to an array of digits. Use `map()` combined with `int` on the string representation of `n` and return a list from the result. ```py -def digitize(n): +def digitize(n): return list(map(int, str(n))) ``` @@ -1230,10 +1230,10 @@ 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 ") +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) ``` @@ -1255,15 +1255,15 @@ Starting with `0` and `1`, use `list.apoend() to add the sum of the last two num If `n` is less or equal to `0`, return a list containing `0`. ```py -def fibonacci(n): - if n <= 0: - return [0] - - sequence = [0, 1] - while len(sequence) <= n: - next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2] - sequence.append(next_value) - +def fibonacci(n): + if n <= 0: + return [0] + + sequence = [0, 1] + while len(sequence) <= n: + next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2] + sequence.append(next_value) + return sequence ``` @@ -1284,10 +1284,10 @@ Calculates the greatest common divisor of a list of numbers. Use `reduce()` and `math.gcd` over the given list. ```py -from functools import reduce -import math - -def gcd(numbers): +from functools import reduce +import math + +def gcd(numbers): return reduce(math.gcd, numbers) ``` @@ -1309,9 +1309,9 @@ Use arithmetic comparison to check if the given number is in the specified range If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`. ```py -def in_range(n, start, end = 0): - if (start > end): - end, start = start, end +def in_range(n, start, end = 0): + if (start > end): + end, start = start, end return start <= n <= end ``` @@ -1319,9 +1319,9 @@ def in_range(n, start, end = 0): Examples ```py -in_range(3, 2, 5); # True -in_range(3, 4); # True -in_range(2, 3, 5); # False +in_range(3, 2, 5); # True +in_range(3, 4); # True +in_range(2, 3, 5); # False in_range(3, 2); # False ``` @@ -1335,7 +1335,7 @@ Checks if the first numeric argument is divisible by the second one. Use the modulo operator (`%`) to check if the remainder is equal to `0`. ```py -def is_divisible(dividend, divisor): +def is_divisible(dividend, divisor): return dividend % divisor == 0 ``` @@ -1357,7 +1357,7 @@ Checks whether a number is odd or even using the modulo (`%`) operator. Returns `True` if the number is even, `False` if the number is odd. ```py -def is_even(num): +def is_even(num): return num % 2 == 0 ``` @@ -1379,7 +1379,7 @@ Checks whether a number is even or odd using the modulo (`%`) operator. Returns `True` if the number is odd, `False` if the number is even. ```py -def is_odd(num): +def is_odd(num): return num % 2 == `0` ``` @@ -1401,25 +1401,25 @@ Define a function, `spread`, that uses either `list.extend()` or `list.append()` Use `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. ```py -from functools import reduce -import math - -def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) - return ret - -def lcm(*args): - numbers = [] - numbers.extend(spread(list(args))) - - def _lcm(x, y): - return int(x * y / math.gcd(x, y)) - +from functools import reduce +import math + +def spread(arg): + ret = [] + for i in arg: + if isinstance(i, list): + ret.extend(i) + else: + ret.append(i) + return ret + +def lcm(*args): + numbers = [] + numbers.extend(spread(list(args))) + + def _lcm(x, y): + return int(x * y / math.gcd(x, y)) + return reduce((lambda x, y: _lcm(x, y)), numbers) ``` @@ -1427,7 +1427,7 @@ def lcm(*args): Examples ```py -lcm(12, 7) # 84 +lcm(12, 7) # 84 lcm([1, 3, 4], 5) # 60 ``` @@ -1441,7 +1441,7 @@ Returns the maximum value of a list, after mapping each element to a value using Use `map()` with `fn` to map each element to a value using the provided function, convert to a `list` and use `max()` to return the maximum value. ```py -def max_by(lst, fn): +def max_by(lst, fn): return max(list(map(fn,lst))) ``` @@ -1462,7 +1462,7 @@ Returns the minimum value of a list, after mapping each element to a value using Use `map()` with `fn` to map each element to a value using the provided function, convert to a `list` and use `min()` to return the minimum value. ```py -def min_by(lst, fn): +def min_by(lst, fn): return min(list(map(fn,lst))) ``` @@ -1483,9 +1483,9 @@ Converts an angle from radians to degrees. Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees. ```py -import math - -def rads_to_degrees(rad): +import math + +def rads_to_degrees(rad): return (rad * 180.0) / math.pi ``` @@ -1493,7 +1493,7 @@ def rads_to_degrees(rad): Examples ```py -import math +import math rads_to_degrees(math.pi / 2) # 90.0 ``` @@ -1507,7 +1507,7 @@ Returns the sum of a list, after mapping each element to a value using the provi Use `map()` with `fn` to map each element to a value using the provided function, convert to a `list` and use `sum()` to return the sum of the values. ```py -def sum_by(lst, fn): +def sum_by(lst, fn): return sum(list(map(fn,lst))) ``` @@ -1534,7 +1534,7 @@ Use `dict.keys()` to return the keys in the given dictionary. Return a `list()` of the previous result. ```py -def keys_only(flat_dict): +def keys_only(flat_dict): return list(flat_dict.keys()) ``` @@ -1542,11 +1542,11 @@ def keys_only(flat_dict): Examples ```py -ages = { - "Peter": 10, - "Isabel": 11, - "Anna": 9, -} +ages = { + "Peter": 10, + "Isabel": 11, + "Anna": 9, +} keys_only(ages) # ['Peter', 'Isabel', 'Anna'] ``` @@ -1560,10 +1560,10 @@ Creates an object with the same keys as the provided object and values generated Use `dict.keys()` to iterate over the object's keys, assigning the values produced by `fn` to each key of a new object. ```py -def map_values(obj, fn): - ret = {} - for key in obj.keys(): - ret[key] = fn(obj[key]) +def map_values(obj, fn): + ret = {} + for key in obj.keys(): + ret[key] = fn(obj[key]) return ret ``` @@ -1571,11 +1571,11 @@ def map_values(obj, fn): Examples ```py -users = { - 'fred': { 'user': 'fred', 'age': 40 }, - 'pebbles': { 'user': 'pebbles', 'age': 1 } -} - +users = { + 'fred': { 'user': 'fred', 'age': 40 }, + 'pebbles': { 'user': 'pebbles', 'age': 1 } +} + map_values(users, lambda u : u['age']) # {'fred': 40, 'pebbles': 1} ``` @@ -1590,7 +1590,7 @@ Use `dict.values()` to return the values in the given dictionary. Return a `list()` of the previous result. ```py -def values_only(dict): +def values_only(dict): return list(flat_dict.values()) ``` @@ -1598,11 +1598,11 @@ def values_only(dict): Examples ```py -ages = { - "Peter": 10, - "Isabel": 11, - "Anna": 9, -} +ages = { + "Peter": 10, + "Isabel": 11, + "Anna": 9, +} values_only(ages) # [10, 11, 9] ``` @@ -1621,7 +1621,7 @@ Returns the length of a string in bytes. Use `string.encode('utf-8')` to encode the given string and return its length. ```py -def byte_size(string): +def byte_size(string): return len(string.encode('utf-8')) ``` @@ -1629,7 +1629,7 @@ def byte_size(string): Examples ```py -byte_size('😀') # 4 +byte_size('😀') # 4 byte_size('Hello World') # 11 ``` @@ -1643,13 +1643,13 @@ Converts a string to camelcase. Break the string into words and combine them capitalizing the first letter of each word, using a regexp. ```py -import re - -def camel(str): - s = re.sub(r"(\s|_|-)+","", - re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", - lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),str) - ) +import re + +def camel(str): + s = re.sub(r"(\s|_|-)+","", + re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", + lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),str) + ) return s[0].lower() + s[1:] ``` @@ -1657,9 +1657,9 @@ def camel(str): Examples ```py -camel('some_database_field_name'); # 'someDatabaseFieldName' -camel('Some label that needs to be camelized'); # 'someLabelThatNeedsToBeCamelized' -camel('some-javascript-property'); # 'someJavascriptProperty' +camel('some_database_field_name'); # 'someDatabaseFieldName' +camel('Some label that needs to be camelized'); # 'someLabelThatNeedsToBeCamelized' +camel('some-javascript-property'); # 'someJavascriptProperty' camel('some-mixed_string with spaces_underscores-and-hyphens'); # 'someMixedStringWithSpacesUnderscoresAndHyphens' ``` @@ -1674,7 +1674,7 @@ Capitalize the first letter of the string and then add it with rest of the strin 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): +def capitalize(string, lower_rest=False): return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) ``` @@ -1682,7 +1682,7 @@ def capitalize(string, lower_rest=False): Examples ```py -capitalize('fooBar') # 'FooBar' +capitalize('fooBar') # 'FooBar' capitalize('fooBar', True) # 'Foobar' ``` @@ -1696,7 +1696,7 @@ Capitalizes the first letter of every word in a string. Use `string.title()` to capitalize first letter of every word in the string. ```py -def capitalize_every_word(string): +def capitalize_every_word(string): return string.title() ``` @@ -1718,7 +1718,7 @@ Decapitalize the first letter of the string and then add it with rest of the str 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): +def decapitalize(string, upper_rest=False): return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) ``` @@ -1726,7 +1726,7 @@ def decapitalize(string, upper_rest=False): Examples ```py -decapitalize('FooBar') # 'fooBar' +decapitalize('FooBar') # 'fooBar' decapitalize('FooBar', True) # 'fOOBAR' ``` @@ -1742,12 +1742,12 @@ Compare the lengths of the two strings, return `False` if they are not equal. Use `sorted()` on both strings and compare the results. ```py -def is_anagram(str1, str2): - _str1, _str2 = str1.replace(" ", ""), str2.replace(" ", "") - - if len(_str1) != len(_str2): - return False - else: +def is_anagram(str1, str2): + _str1, _str2 = str1.replace(" ", ""), str2.replace(" ", "") + + if len(_str1) != len(_str2): + return False + else: return sorted(_str1.lower()) == sorted(_str2.lower()) ``` @@ -1768,7 +1768,7 @@ Checks if a string is lower case. Convert the given string to lower case, using `str.lower()` and compare it to the original. ```py -def is_lower_case(string): +def is_lower_case(string): return string == string.lower() ``` @@ -1776,8 +1776,8 @@ def is_lower_case(string): Examples ```py -is_lower_case('abc') # True -is_lower_case('a3@$') # True +is_lower_case('abc') # True +is_lower_case('a3@$') # True is_lower_case('Ab4') # False ``` @@ -1791,7 +1791,7 @@ Checks if a string is upper case. Convert the given string to upper case, using `str.upper()` and compare it to the original. ```py -def is_upper_case(string): +def is_upper_case(string): return string == string.upper() ``` @@ -1799,8 +1799,8 @@ def is_upper_case(string): Examples ```py -is_upper_case('ABC') # True -is_upper_case('a3@$') # False +is_upper_case('ABC') # True +is_upper_case('a3@$') # False is_upper_case('aB4') # False ``` @@ -1814,12 +1814,12 @@ Converts a string to kebab case. Break the string into words and combine them adding `-` as a separator, using a regexp. ```py -import re - -def kebab(str): - return re.sub(r"(\s|_|-)+","-", - re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", - lambda mo: mo.group(0).lower(),str) +import re + +def kebab(str): + return re.sub(r"(\s|_|-)+","-", + re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", + lambda mo: mo.group(0).lower(),str) ) ``` @@ -1827,9 +1827,9 @@ def kebab(str): Examples ```py -kebab('camelCase'); # 'camel-case' -kebab('some text'); # 'some-text' -kebab('some-mixed_string With spaces_underscores-and-hyphens'); # 'some-mixed-string-with-spaces-underscores-and-hyphens' +kebab('camelCase'); # 'camel-case' +kebab('some text'); # 'some-text' +kebab('some-mixed_string With spaces_underscores-and-hyphens'); # 'some-mixed-string-with-spaces-underscores-and-hyphens' kebab('AllThe-small Things'); # "all-the-small-things" ``` @@ -1844,10 +1844,10 @@ Use `str.lower()` and `re.sub()` to convert to lowercase and remove non-alphanu Then, compare the new string with its reverse. ```py -from re import sub - -def palindrome(string): - s = sub('[\W_]', '', string.lower()) +from re import sub + +def palindrome(string): + s = sub('[\W_]', '', string.lower()) return s == s[::-1] ``` @@ -1868,12 +1868,12 @@ Converts a string to snake case. Break the string into words and combine them adding `_-_` as a separator, using a regexp. ```py -import re - -def snake(str): - return re.sub(r"(\s|_|-)+","-", - re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", - lambda mo: mo.group(0).lower(),str) +import re + +def snake(str): + return re.sub(r"(\s|_|-)+","-", + re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", + lambda mo: mo.group(0).lower(),str) ) ``` @@ -1881,9 +1881,9 @@ def snake(str): Examples ```py -snake('camelCase'); # 'camel_case' -snake('some text'); # 'some_text' -snake('some-mixed_string With spaces_underscores-and-hyphens'); # 'some_mixed_string_with_spaces_underscores_and_hyphens' +snake('camelCase'); # 'camel_case' +snake('some text'); # 'some_text' +snake('some-mixed_string With spaces_underscores-and-hyphens'); # 'some_mixed_string_with_spaces_underscores_and_hyphens' snake('AllThe-small Things'); # "all_the_smal_things" ``` @@ -1897,7 +1897,7 @@ Splits a multiline string into a list of lines. Use `str.split()` and `'\n'` to match line breaks and create a list. ```py -def split_lines(str): +def split_lines(str): str.split('\n') ``` @@ -1923,7 +1923,7 @@ Casts the provided value as an array if it's not one. Use `isinstance()` to check if the given value is a list and return it as-is or encapsulated in a list accordingly. ```py -def cast_list(val): +def cast_list(val): return val if isinstance(val, list) else [val] ``` @@ -1931,19 +1931,19 @@ def cast_list(val): Examples ```py -cast_list('foo'); # ['foo'] +cast_list('foo'); # ['foo'] cast_list([1]); # [1] ```
[⬆ Back to top](#contents) -## Collaborators - -| [](https://github.com/Chalarangelo)
[Angelos Chalaris](https://github.com/Chalarangelo) | [](https://github.com/fejes713)
[Stefan Feješ](https://github.com/fejes713) | [](https://github.com/kriadmin)
[Rohit Tanwar](https://github.com/kriadmin) | -| --- | --- | --- | - -## Credits - -*This README is built using [markdown-builder](https://github.com/30-seconds/markdown-builder).* +## Collaborators + +| [](https://github.com/Chalarangelo)
[Angelos Chalaris](https://github.com/Chalarangelo) | [](https://github.com/fejes713)
[Stefan Feješ](https://github.com/fejes713) | [](https://github.com/kriadmin)
[Rohit Tanwar](https://github.com/kriadmin) | +| --- | --- | --- | + +## Credits + +*This README is built using [markdown-builder](https://github.com/30-seconds/markdown-builder).* diff --git a/config.js b/config.js index a8a1da6df..743df63fb 100644 --- a/config.js +++ b/config.js @@ -3,7 +3,7 @@ module.exports = { name: `30 seconds of python`, description: `A curated collection of useful Python snippets that you can understand in 30 seconds or less.`, shortName: `30s`, - repositoryUrl: `https://github.com/30-seconds/30-seconds-of-python-code`, + repositoryUrl: `https://github.com/30-seconds/30-seconds-of-python`, // Path information snippetPath: `snippets`, snippetDataPath: `snippet_data`, diff --git a/package-lock.json b/package-lock.json index 9f3bd1e36..d50f5e9d3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "30-seconds-of-python-code", + "name": "30-seconds-of-python", "version": "1.0.0", "lockfileVersion": 1, "requires": true, diff --git a/package.json b/package.json index e48cacbba..732433a6c 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "30-seconds-of-python-code", + "name": "30-seconds-of-python", "version": "1.0.0", "description": "A curated collection of useful Python snippets that you can understand in 30 seconds or less.", "main": "config.js", @@ -12,14 +12,14 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/30-seconds/30-seconds-of-python-code.git" + "url": "git+https://github.com/30-seconds/30-seconds-of-python.git" }, "author": "Stefan Fejes (ns.fejes.stefan@gmail.com)", "license": "CC0-1.0", "bugs": { "url": "https://github.com/30-seconds/30-seconds-of-pythong-code/issues" }, - "homepage": "https://github.com/30-seconds/30-seconds-of-python-code", + "homepage": "https://github.com/30-seconds/30-seconds-of-python", "dependencies": {}, "devDependencies": { "@babel/core": "^7.5.4", diff --git a/src/static-parts/README-start.md b/src/static-parts/README-start.md index 060ce66b5..24cea538e 100644 --- a/src/static-parts/README-start.md +++ b/src/static-parts/README-start.md @@ -1,6 +1,6 @@ ![Logo](/icon.png) -## 30-seconds-of-python-code +## 30-seconds-of-python > Curated collection of useful Python snippets that you can understand in 30 seconds or less.