From 3a91c24efc65c7bcf0f13480f59d133463eb017f Mon Sep 17 00:00:00 2001 From: Stefan Fejes Date: Tue, 20 Aug 2019 16:00:27 +0200 Subject: [PATCH] WIP - add builder script --- README.md | 1950 ++++++++++++----- .../static-parts/README-end.md | 0 .../static-parts/README-start.md | 6 +- 3 files changed, 1438 insertions(+), 518 deletions(-) rename static-parts/readme-end.md => src/static-parts/README-end.md (100%) rename static-parts/readme-start.md => src/static-parts/README-start.md (90%) diff --git a/README.md b/README.md index ac4320ce4..84b82604f 100644 --- a/README.md +++ b/README.md @@ -1,883 +1,1807 @@ -![Logo](/icon.png) +![Logo](/icon.png) + +# 30-seconds-of-python-code [![Tweet](https://jpillora.com/github-twitter-button/img/tweet.png)](http://www.twitter.com/share?text=%2330secondsofcode+30-seconds-of-python-code+-+Python+Implementation+of+30+seconds+of+code%0Ahttps://github.com/kriadmin/30-seconds-of-python-code&url=a") +[![License](https://img.shields.io/aur/license/yaourt.svg)](https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE) +[![first-timers-only](https://img.shields.io/badge/first--timers--only-friendly-blue.svg?style=flat-square)](http://www.firsttimersonly.com/) [![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) + +## Welcome to 30-seconds-of-python-code! + +If you've come here from javascript land then you should be aware that this project uses `python 3`, therefore not all snippets will work as expected in every python interpreter or on system. You'll need to check your python version with the command `python -v`. If you need help installing the latest stable release of python 3 on your system checkout docs.python.org if you run into trouble make sure you research stackoverflow. Eventually it might be worth looking into how to set up a virtual environment for python projects with virtualenv or even a tool like anaconda. + +This project contains plenty of useful snippets which can help beginners and newcomers quickly ramp-up on grasping python 3's syntax. + +### Table of contents -# 30-seconds-of-python-code [![Tweet](https://jpillora.com/github-twitter-button/img/tweet.png)](http://www.twitter.com/share?text=%2330secondsofcode+30-seconds-of-python-code+-+Python+Implementation+of+30+seconds+of+code%0Ahttps://github.com/kriadmin/30-seconds-of-python-code&url=a") -[![License](https://img.shields.io/aur/license/yaourt.svg)](https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE) -[![first-timers-only](https://img.shields.io/badge/first--timers--only-friendly-blue.svg?style=flat-square)](http://www.firsttimersonly.com/) [![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) +### List -## Welcome to 30-seconds-of-🐍-code! +
+View contents ->A Python implementation of 30-seconds-of-code. +* [`all_equal`](#all_equal) +* [`all_unique`](#all_unique) +* [`bifurcate`](#bifurcate) +* [`bifurcate_by`](#bifurcate_by) +* [`chunk`](#chunk) +* [`compact`](#compact) +* [`count_by`](#count_by) +* [`count_occurences`](#count_occurences) +* [`deep_flatten`](#deep_flatten) +* [`difference`](#difference) +* [`difference_by`](#difference_by) +* [`every`](#every) +* [`every_nth`](#every_nth) +* [`filter_non_unique`](#filter_non_unique) +* [`group_by`](#group_by) +* [`has_duplicates`](#has_duplicates) +* [`head`](#head) +* [`initial`](#initial) +* [`initialize_2d_list`](#initialize_2d_list) +* [`initialize_list_with_range`](#initialize_list_with_range) +* [`initialize_list_with_values`](#initialize_list_with_values) +* [`intersection`](#intersection) +* [`intersection_by`](#intersection_by) +* [`last`](#last) +* [`longest_item`](#longest_item) +* [`max_n`](#max_n) +* [`min_n`](#min_n) +* [`none`](#none) +* [`offset`](#offset) +* [`sample`](#sample) +* [`shuffle`](#shuffle) +* [`similarity`](#similarity) +* [`some`](#some) +* [`spread`](#spread) +* [`tail`](#tail) +* [`unique_elements`](#unique_elements) +* [`zip`](#zip) -**Note**:- This is in no way affiliated with the original [30-seconds-of-code](https://github.com/Chalarangelo/30-seconds-of-code/). +
-If you've come here from javascript land then you should be aware that this project uses `python 3`, therefore not all snippets will work as expected in every python interpreter or on system. You'll need to check your python version with the command `python -v`. If you need help installing the latest stable release of python 3 on your system checkout docs.python.org if you run into trouble make sure you research stackoverflow. Eventually it might be worth looking into how to set up a virtual environment for python projects with virtualenv or even a tool like anaconda. +### Math -This project contains plenty of useful snippets which can help beginners and newcomers quickly ramp-up on grasping python 3's syntax. +
+View contents -### Table of contents -### :books: List +* [`average`](#average) +* [`average_by`](#average_by) +* [`clamp_number`](#clamp_number) +* [`digitize`](#digitize) +* [`factorial`](#factorial) +* [`fibonacci`](#fibonacci) +* [`gcd`](#gcd) +* [`in_range`](#in_range) +* [`is_divisible`](#is_divisible) +* [`is_even`](#is_even) +* [`is_odd`](#is_odd) +* [`lcm`](#lcm-) +* [`max_by`](#max_by) +* [`min_by`](#min_by) +* [`rads_to_degrees`](#rads_to_degrees) -
View contents
+
-### :heavy_division_sign: Math +### Object -
View contents
+
+View contents -### :card_file_box: Object +* [`keys_only`](#keys_only) +* [`map_values`](#map_values) +* [`values_only`](#values_only) -
View contents
+
-### :scroll: String +### String -
View contents
+
+View contents -
+* [`byte_size`](#byte_size) +* [`capitalize`](#capitalize) +* [`capitalize_every_word`](#capitalize_every_word) +* [`decapitalize`](#decapitalize) +* [`is_anagram`](#is_anagram) +* [`is_lower_case`](#is_lower_case) +* [`is_upper_case`](#is_upper_case) +* [`palindrome`](#palindrome) +* [`split_lines`](#split_lines) -## :books: List +
-### bubble_sort -Author:- [Shobhit Sachan](https://www.github.com/sachans) +### Utility - Contributors:- [Shobhit Sachan](https://www.github.com/sachans) +
+View contents -Bubble_sort uses the technique of comparing and swapping +* [`cast_list`](#cast_list) + +
+ + +--- + +## List + + +### all_equal + +Check if all elements in a list are equal. + +Use `[1:]` and `[:-1]` to compare all the values in the given list. + +```python ```py -def bubble_sort(lst): - for passnum in range(len(lst) - 1, 0, -1): - for i in range(passnum): - if lst[i] > lst[i + 1]: - lst[i], lst[i + 1] = lst[i + 1], lst[i] +def all_equal(lst): + return lst[1:] == lst[:-1] +``` ``` -
View Examples -```py -lst = [54,26,93,17,77,31,44,55,20] -bubble_sort(lst) -print("sorted %s" %lst) # [17,20,26,31,44,54,55,77,91] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### chunk -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### all_unique - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns `True` if all the values in a flat list are unique, `False` otherwise. -Chunks an list into smaller lists of a specified size. +Use `set()` on the given list to remove duplicates, compare its length with the length of the list. -Uses `range` to create a list of desired size. Then use `map` on this list and fill it with splices of `lst`. +```python +```py +def all_unique(lst): + return len(lst) == len(set(lst)) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### bifurcate + +Splits values into two groups. +If an element in `filter` is `True`, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group. + +Use list comprehension and `enumerate()` to add elements to groups, based on `filter`. + +```python +```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] + ] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### bifurcate_by + +Splits values into two groups according to a function, which specifies which group an element in the input list belongs to. +If the function returns `True`, the element belongs to the first group; otherwise, it belongs to the second group. + +Use list comprehension to add elements to groups, based on `fn`. + +```python +```py +def bifurcate_by(lst, fn): + return [ + [x for x in lst if fn(x)], + [x for x in lst if not fn(x)] + ] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### chunk + +Chunks a list into smaller lists of a specified size. + +Use `list()` and `range()` to create a list of the desired `size`. +Use `map()` on the list and fill it with splices of the given list. +Finally, return use created list. + +```python ```py 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))))) + return list( + map(lambda x: lst[x * size:x * size + size], + list(range(0, ceil(len(lst) / size))))) +``` ``` -
View Examples -```py -chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### compact -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### compact Removes falsey values from a list. -Use `filter()` to filter out falsey values (False, None, 0, and ""). +Use `filter()` to filter out falsey values (`False`, `None`, `0`, and `""`). + +```python ```py def compact(lst): - return list(filter(bool, lst)) + return list(filter(bool, lst)) +``` ``` -
View Examples -```py -compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### count_by -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) - -:information_source: Already implemented via `collections.Counter` +### count_by Groups the elements of a list based on the given function and returns the count of elements in each group. -Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs. +Use `map()` to map the values of the given list using the given function. +Iterate over the map and increase the element count each time it occurs. + +```python ```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 - return key + key = {} + for el in map(fn, arr): + key[el] = 0 if el not 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} +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### count_occurences -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin), [Hui Binyuan](https://www.github.com/huybery) - -:information_source: Already implemented via `list.count()`. +### count_occurences Counts the occurrences of a value in a list. -Uses the list comprehension to increment a counter each time you encounter the specific value inside the list. +Increment a counter for every item in the list that has the given value and is of the same type. + +```python ```py def count_occurrences(lst, val): - return len([x for x in lst if x == val and type(x) == type(val)]) + return len([x for x in lst if x == val and type(x) == type(val)]) +``` ``` -
View Examples -```py -count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### deep_flatten -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin), [Meet Zaveri](https://www.github.com/meetzaveri) +### deep_flatten Deep flattens a list. -Use recursion. Use `list.extend()` with an empty list (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list. +Use recursion. +Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it. +Use `list.extend()` with an empty list and the `spread` function to flatten a list. +Recursively flatten each element that is a list. + +```python ```py def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) - return ret - + 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 + result = [] + result.extend( + spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) + return result +``` ``` -
View Examples -```py -deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### difference -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### difference Returns the difference between two iterables. -Use list comprehension to only keep values not contained in `b` +Create a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`. + +```python ```py def difference(a, b): - return [item for item in a if item not in 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] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### difference_by -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### difference_by - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns the difference between two lists, after applying the provided function to each list element of both. -Returns the difference between two list, after applying the provided function to each list element of both. +Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with `fn` on `a` to only keep values not contained in the previously created set, `_b`. -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 ```py def difference_by(a, b, fn): - b = set(map(fn, b)) - return [item for item in a if fn(item) not in b] + _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 } ] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### has_duplicates -Author:- [Rob-Rychs](@Rob-Rychs) +### every - Contributors:- [Rob-Rychs](@Rob-Rychs) +Returns `True` if the provided function returns `True` for every element in the list, `False` otherwise. -Checks a flat list for duplicate values. Returns True if duplicate values exist and False if values are all unique. +Iterate over the elements of the list to test if every element in the list returns `True` based on `fn`. +Omit the seconds argument, `fn`, to check if all elements are `True`. -This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list. +```python +```py +def every(lst, fn=lambda x: not not x): + for el in lst: + if not fn(el): + return False + return True +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### every_nth + +Returns every nth element in a list. + +Use `[1::nth]` to create a new list that contains every nth element of the given list. + +```python +```py +def every_nth(lst, nth): + return lst[1::nth] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### filter_non_unique + +Filters out the non-unique values in a list. + +Use list comprehension and `list.count()` to create a list containing only the unique values. + +```python +```py +def filter_non_unique(lst): + return [item for item in lst if lst.count(item) == 1] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### group_by + +Groups the elements of a list based on the given function. + +Use `list()` in combination with `map()` and `fn` to map the values of the list to the keys of an object. +Use list comprehension to map each element to the appropriate `key`. + +```python +```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] + return groups +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### has_duplicates + +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. + +```python ```py def has_duplicates(lst): - return len(lst) != len(set(lst)) + return len(lst) != len(set(lst)) +``` ``` -
View Examples -```py -x = [1,2,3,4,5,5] -y = [1,2,3,4,5] -has_duplicates(x) # True -has_duplicates(y) # False +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### insertion_sort -Author:- [Meet Zaveri](https://www.github.com/meetzaveri) +### head - Contributors:-[Meet Zaveri](https://www.github.com/meetzaveri), [Rohit Tanwar](https://www.github.com/kriadmin) +Returns the head of a list. -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! +use `lst[0]` to return the first element of the passed list. + +```python ```py -def insertion_sort(lst): - - for i in range(1, len(lst)): - key = lst[i] - j = i - 1 - while j >= 0 and key < lst[j]: - lst[j + 1] = lst[j] - j -= 1 - lst[j + 1] = key +def head(lst): + return lst[0] +``` ``` -
View Examples -```py -lst = [7,4,9,2,6,3] -insertionsort(lst) -print('Sorted %s' %lst) # sorted [2, 3, 4, 6, 7, 9] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### shuffle -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### initial - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns all the elements of a list except the last one. -:information_source: The same algorithm is already implemented via `random.shuffle`. +Use `lst[0:-1]` to return all but the last element of the list. + +```python +```py +def initial(lst): + return lst[0:-1] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### initialize_2d_list + +Initializes a 2D list of given width and height and value. + +Use list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`. +If `val` is not provided, default to `None`. + +Explain briefly how the snippet works. + +```python +```py +def initialize_2d_list(w,h, val = None): + return [[val for x in range(w)] for y in range(h)] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### initialize_list_with_range + +Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. + +Use list comprehension and `range()` to generate a list of the appropriate length, filled with the desired values in the given range. +Omit `start` to use the default value of `0`. +Omit `step` to use the default value of `1`. + +```python +```py +def initialize_list_with_range(end, start = 0, step = 1): + return [x for x in range(start, end + 1, step)] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### initialize_list_with_values + +Initializes and fills a list with the specified value. + +Use list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values. +Omit `val` to use the default value of `0`. + +```python +```py +def initialize_list_with_values(n, val = 0): + return [val for x in range(n)] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### intersection + +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. + +```python +```py +def intersection(a, b): + _b = set(b) + return [item for item in a if item in _b] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### intersection_by + +Returns a list of elements that exist in both lists, 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 contained in both lists. + +```python +```py +def intersection_by(a, b, fn): + _b = set(map(fn, b)) + return [item for item in a if fn(item) in _b] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### last + +Returns the last element in a list. + +use `lst[-1]` to return the last element of the passed list. + +```python +```py +def last(lst): + return lst[-1] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### longest_item + +Takes any number of iterable objects or objects with a length property and returns the longest one. +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. + +```python +```py +def longest_item(*args): + return max(args, key = len) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### 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 `sorted() to sort the list, `[:n]` to get the specified number of elements. +Omit the second argument, `n`, to get a one-element list. + +```python +```py +def max_n(lst, n=1): + return sorted(lst, reverse=True)[:n] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### 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 `sorted() to sort the list, `[:n]` to get the specified number of elements. +Omit the second argument, `n`, to get a one-element list. + +```python +```py +def min_n(lst, n=1): + return sorted(lst, reverse=False)[:n] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### none + +Returns `False` if the provided function returns `True` for at least one element in the list, `True` otherwise. + +Iterate over the elements of the list to test if every element in the list returns `False` based on `fn`. +Omit the seconds argument, `fn`, to check if all elements are `False`. + +```python +```py +def none(lst, fn=lambda x: not not x): + for el in lst: + if fn(el): + return False + return True +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### offset + +Moves the specified amount of elements to the end of the list. + +Use `lst[offset:]` and `lst[:offset]` to get the two slices of the list and combine them before returning. + +Explain briefly how the snippet works. + +```python +```py +def offset(lst, offset): + return lst[offset:] + lst[:offset] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### sample + +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. + +```python +```py +from random import randint + +def sample(lst): + return lst[randint(0, len(lst) - 1)] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### 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 ```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] - return temp_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 +``` ``` -
View Examples -```py -foo = [1,2,3] -shuffle(foo) # [2,3,1] , foo = [1,2,3] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### spread -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### similarity - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns a list of elements that exist in both lists. -Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. +Use list comprehension on `a` to only keep values contained in both lists. + +```python +```py +def similarity(a, b): + return [item for item in a if item in b] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### some + +Returns `True` if the provided function returns `True` for at least one element in the list, `False` otherwise. + +Iterate over the elements of the list to test if every element in the list returns `True` based on `fn`. +Omit the seconds argument, `fn`, to check if all elements are `True`. + +```python +```py +def some(lst, fn=lambda x: not not x): + for el in lst: + if fn(el): + return True + return False +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### spread + +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. + +```python ```py def spread(arg): - ret = [] - for i in arg: - if isinstance(i, list): - ret.extend(i) - else: - ret.append(i) - return ret + 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] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### zip -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### tail - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin), [Leonardo Galdino](https://www.github.com/LeonardoGaldino) +Returns all elements in a list except for the first one. -:information_source: Already implemented via `itertools.zip_longest()` +Return `lst[1:]` if the list's length is more than `1`, otherwise, return the whole list. + +```python +```py +def tail(lst): + return lst[1:] if len(lst) > 1 else lst +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### unique_elements + +Returns the unique elements in a given list. + +Create a `set` from the list to discard duplicated values, then return a `list` from it. + +```python +```py +def unique_elements(li): + return list(set(li)) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### zip Creates a list of elements, grouped based on the position in the original lists. -Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`. + +Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. +Loop for `max_length` times grouping elements. +If lengths of `lists` vary, use `fill_value` (defaults to `None`). + +```python ```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)) - ]) - return result + 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 +``` ``` -
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]] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -## :heavy_division_sign: Math +--- -### average -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +## Math - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin), [Hui Binyuan](https://www.github.com/huybery) -:information_source: Already implemented via `statistics.mean`. `statistics.mean` takes an array as an argument whereas this function takes variadic arguments. +### average Returns the average of two or more numbers. -Takes the sum of all the `args` and divides it by `len(args)`. The second argument `0.0` in sum is to handle floating point division in `python3`. +Use `sum()` to sum all of the `args` provided, divide by `len(args)`. + +```python ```py def average(*args): - return sum(args, 0.0) / len(args) + return sum(args, 0.0) / len(args) +``` ``` -
View Examples -```py -average(*[1, 2, 3]) # 2.0 -average(1, 2, 3) # 2.0 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### factorial -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### average_by - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns the average of a list, after mapping each element to a value using the provided function. + +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)`. + +```python +```py +def average_by(lst, fn=lambda x: x): + return sum(map(fn, lst), 0.0) / len(lst) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### clamp_number + +Clamps `num` within the inclusive range specified by the boundary values `a` and `b`. + +If `num` falls within the range, return `num`. +Otherwise, return the nearest number in the range. + +```python +```py +def clamp_number(num,a,b): + return max(min(num, max(a,b)),min(a,b)) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### digitize + +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. + +```python +```py +def digitize(n): + return list(map(int, str(n))) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### 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. +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 ```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) + 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 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### fibonacci_until_num -Author:- [Nian Lee](https://www.github.com/scraggard) +### fibonacci - Contributors:- [Nian Lee](https://www.github.com/scraggard) +Generates an array, containing the Fibonacci sequence, up until the nth term. -Returns the n-th term in a Fibonnaci sequence that starts with 1 +Starting with `0` and `1`, use `list.apoend() to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches `n`. +If `n` is less or equal to `0`, return a list containing `0`. -A term in a Fibonnaci sequence is the sum of the two previous terms. -This function recursively calls the function to find the n-th term. -```py -def fibonacci_until_num(n): - if n < 3: - return 1 - return fibonacci_until_num(n - 2) + fibonacci_until_num(n - 1) +```python +```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) + + return sequence +``` ``` -
View Examples -```py -fibonnaci_until_num(5) # 5 -fibonnaci_until_num(15) # 610 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### gcd -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin), [cclauss](https://www.github.com/cclauss), [Sandhya Saravanan](https://www.github.com/sandy9999) +### gcd Calculates the greatest common divisor of a list of numbers. -Uses the reduce function from the inbuilt module `functools`. Also uses the `math.gcd` function over a list. +Use `reduce()` and `math.gcd` over the given list. + +```python ```py from functools import reduce import math def gcd(numbers): - return reduce(math.gcd, numbers) + return reduce(math.gcd, numbers) +``` ``` -
View Examples -```py -gcd([8,36,28]) # 4 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### lcm -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### in_range - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Checks if the given number falls within the given range. + +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`. + +```python +```py +def in_range(n, start, end = 0): + if (start > end): + end, start = start, end + return start <= n <= end +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### is_divisible + +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`. + +```python +```py +def is_divisible(dividend, divisor): + return dividend % divisor == 0 +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### is_even + +Returns `True` if the given number is even, `False` otherwise. + +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. + +```python +```py +def is_even(num): + return num % 2 == 0 +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### is_odd + +Returns `True` if the given number is odd, `False` otherwise. + +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. + +```python +```py +def is_odd(num): + return num % 2 == `0` +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### lcm ![advanced](/advanced.svg) 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. +Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it. +Use `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. -Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists. +```python ```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 - + 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))) + 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 int(x * y / math.gcd(x, y)) - def _lcm(x, y): - return x * y / _gcd(x, y) - - return reduce((lambda x, y: _lcm(x, y)), numbers) + return reduce((lambda x, y: _lcm(x, y)), numbers) +``` ``` -
View Examples -```py -lcm(12, 7) # 84 -lcm([1, 3, 4], 5) # 60 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### max_n -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### max_by - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns the maximum value of a list, after mapping each element to a value using the provided function. -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 `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. -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 list +```python ```py -def max_n(lst, n=1, reverse=True): - return sorted(lst, reverse=reverse)[:n] +def max_by(lst, fn): + return max(list(map(fn,lst))) +``` ``` -
View Examples -```py -max_n([1, 2, 3]) # [3] -max_n([1, 2, 3], 2) # [3,2] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### min_n -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### min_by - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Returns the minimum value of a list, after mapping each element to a value using the provided function. -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 `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. -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 list +```python ```py -from copy import deepcopy - - -def min_n(lst, n=1): - numbers = deepcopy(lst) - numbers.sort() - return numbers[:n] +def min_by(lst, fn): + return min(list(map(fn,lst))) +``` ``` -
View Examples -```py -min_n([1, 2, 3]) # [1] -min_n([1, 2, 3], 2) # [1,2] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -## :card_file_box: Object +### rads_to_degrees -### all_unique -Author:- [Rob-Rychs](@Rob-Rychs) +Converts an angle from radians to degrees. - Contributors:- [Rob-Rychs](@Rob-Rychs) +Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees. -Checks a flat list for all unique values. Returns True if list values are all unique and False if list values aren't all unique. - -This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list. +```python ```py -def all_unique(lst): - return len(lst) == len(set(lst)) +import math + +def rads_to_degrees(rad): + return (rad * 180.0) / math.pi +``` ``` -
View Examples -```py -x = [1,2,3,4,5,6] -y = [1,2,2,3,4,5] -all_unique(x) # True -all_unique(y) # False +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### keys_only -Author:- [Rob-Rychs](@Rob-Rychs) +--- - Contributors:- [Rob-Rychs](@Rob-Rychs) +## Object -Function which accepts a dictionary of key value pairs and returns a new flat list of only the keys. -Uses the .items() function with a for loop on the dictionary to track both the key and value and returns a new list by appending the keys to it. Best used on 1 level-deep key:value pair dictionaries (a flat dictionary) and not nested data-structures which are also commonly used with dictionaries. (a flat dictionary resembles a json and a flat list an array for javascript people). +### keys_only + +Returns a flat list of all the keys in a flat dictionary. + +Use `dict.keys()` to return the keys in the given dictionary. +Return a `list()` of the previous result. + +```python ```py def keys_only(flat_dict): - lst = [] - for k, v in flat_dict.items(): - lst.append(k) - return lst + return list(flat_dict.keys()) +``` ``` -
View Examples -```py -ages = { - "Peter": 10, - "Isabel": 11, - "Anna": 9, -} -keys_only(ages) # ['Peter', 'Isabel', 'Anna'] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### values_only -Author:- [Rob-Rychs](@Rob-Rychs) +### map_values - Contributors:- [Rob-Rychs](@Rob-Rychs) +Creates an object with the same keys as the provided object and values generated by running the provided function for each value. -Function which accepts a dictionary of key value pairs and returns a new flat list of only the values. +Use `dict.keys()` to iterate over the object's keys, assigning the values produced by `fn` to each key of a new object. -Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not nested data-structures. +```python +```py +def map_values(obj, fn): + ret = {} + for key in obj.keys(): + ret[key] = fn(obj[key]) + return ret +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### values_only + +Returns a flat list of all the values in a flat dictionary. + +Use `dict.values()` to return the values in the given dictionary. +Return a `list()` of the previous result. + +```python ```py def values_only(dict): - lst = [] - for k, v in dict.items(): - lst.append(v) - return lst + return list(flat_dict.values()) +``` ``` -
View Examples -```py -ages = { - "Peter": 10, - "Isabel": 11, - "Anna": 9, -} -values_only(ages) # [10, 11, 9] +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -## :scroll: String +--- -### byte_size -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +## String - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) + +### byte_size Returns the length of a string in bytes. -`utf-8` encodes a given string, then `len` finds the length of the encoded string. +Use `string.encode('utf-8')` to encode the given string and return its length. + +```python ```py def byte_size(string): - return(len(string.encode('utf-8'))) + return len(string.encode('utf-8')) +``` ``` -
View Examples -```py -byte_size('😀') # 4 -byte_size('Hello World') # 11 +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### capitalize -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### capitalize Capitalizes the first letter of a string. -Capitalizes the fist letter of the string 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. +Capitalize the first letter of the string and then add 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 ```py def capitalize(string, lower_rest=False): - return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) + return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:]) +``` ``` -
View Examples -```py -capitalize('fooBar') # 'FooBar' -capitalize('fooBar', True) # 'Foobar' +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### capitalize_every_word -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### 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. +Use `string.title()` to capitalize first letter of every word in the string. + +```python ```py def capitalize_every_word(string): - return string.title() + return string.title() +``` ``` -
View Examples -```py -capitalize_every_word('hello world!') # 'Hello World!' +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### count_vowels -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) - -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 -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### 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. +Decapitalize the first letter of the string and then add 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 ```py def decapitalize(string, upper_rest=False): - return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) + return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:]) +``` ``` -
View Examples -```py -decapitalize('FooBar') # 'fooBar' -decapitalize('FooBar', True) # 'fOOBAR' +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### is_lower_case -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) +### is_anagram - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters). + +Use `str.replace()` to remove spaces from both strings. +Compare the lengths of the two strings, return `False` if they are not equal. +Use `sorted()` on both strings and compare the results. + +```python +```py +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()) +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +### is_lower_case Checks if a string is lower case. -Convert the given string to lower case, using `str.lower()` method and compare it to the original. +Convert the given string to lower case, using `str.lower()` and compare it to the original. + +```python ```py def is_lower_case(string): - return string == string.lower() + return string == string.lower() +``` ``` -
View Examples -```py -is_lower_case('abc') # True -is_lower_case('a3@$') # True -is_lower_case('Ab4') # False +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### is_upper_case -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### is_upper_case Checks if a string is upper case. -Convert the given string to upper case, using `str.upper()` method and compare it to the original. +Convert the given string to upper case, using `str.upper()` and compare it to the original. + +```python ```py def is_upper_case(string): - return string == string.upper() + return string == string.upper() +``` ``` -
View Examples -```py -is_upper_case('ABC') # True -is_upper_case('a3@$') # False -is_upper_case('aB4') # False +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) -### palindrome -Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - - Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) +### 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 +Use `str.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string. +Then, compare the new string with its reverse. +```python ```py -palindrome('taco cat') # True +from re import sub + +def palindrome(string): + s = sub('[\W_]', '', string.lower()) + return s == s[::-1] +``` +``` + +
+Examples + +```python +undefined ```
-
:arrow_up: Back to top +
[⬆ Back to top](#contents) + +### split_lines + +Splits a multiline string into a list of lines. + +Use `str.split()` and `'\n'` to match line breaks and create a list. + +```python +```py +def split_lines(str): + str.split('\n') +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +--- + +## Utility -## Credits +### cast_list -*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/).* +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. +```python +```py +def cast_list(val): + return val if isinstance(val, list) else [val] +``` +``` + +
+Examples + +```python +undefined +``` +
+ +
[⬆ Back to top](#contents) + +## 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) -## 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/static-parts/readme-end.md b/src/static-parts/README-end.md similarity index 100% rename from static-parts/readme-end.md rename to src/static-parts/README-end.md diff --git a/static-parts/readme-start.md b/src/static-parts/README-start.md similarity index 90% rename from static-parts/readme-start.md rename to src/static-parts/README-start.md index fe5bd3a8e..da6883f2e 100644 --- a/static-parts/readme-start.md +++ b/src/static-parts/README-start.md @@ -5,11 +5,7 @@ [![first-timers-only](https://img.shields.io/badge/first--timers--only-friendly-blue.svg?style=flat-square)](http://www.firsttimersonly.com/) [![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) -## Welcome to 30-seconds-of-🐍-code! - ->A 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/). +## Welcome to 30-seconds-of-python-code! If you've come here from javascript land then you should be aware that this project uses `python 3`, therefore not all snippets will work as expected in every python interpreter or on system. You'll need to check your python version with the command `python -v`. If you need help installing the latest stable release of python 3 on your system checkout docs.python.org if you run into trouble make sure you research stackoverflow. Eventually it might be worth looking into how to set up a virtual environment for python projects with virtualenv or even a tool like anaconda.