diff --git a/.travis/push.sh b/.travis/push.sh index 96d8ca2a8..e6a4e9bc2 100755 --- a/.travis/push.sh +++ b/.travis/push.sh @@ -1,44 +1,44 @@ -#!/bin/bash -setup_git() { - git config --global user.email "mst10041967@gmail.com" - git config --global user.name "Rohit Tanwar" -} - -commit_website_files() { - if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then - if [ $TRAVIS_BRANCH == "master" ]; then - git checkout master - echo "Committing to master branch..." - git add -A - echo "All files added" - git status - if [ $TRAVIS_EVENT_TYPE == "cron" ]; then - git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [cron]" - elif [ $TRAVIS_EVENT_TYPE == "api" ]; then - git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]" - else - git commit --message "Travis build: $TRAVIS_BUILD_NUMBER" - fi - echo "Files commited" - git status - fi - fi -} - -upload_files() { - if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then - if [ $TRAVIS_BRANCH == "master" ]; then - echo "Pushing to master branch..." - git push --force "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" master > /dev/null 2>&1 - echo "Pushing done" - echo "Pushing to website" - git subtree push --prefix website "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" website - echo "Pushed to master branch" - git status - fi - fi -} - -setup_git -commit_website_files -upload_files +#!/bin/bash +setup_git() { + git config --global user.email "mst10041967@gmail.com" + git config --global user.name "Rohit Tanwar" +} + +commit_website_files() { + if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then + if [ $TRAVIS_BRANCH == "master" ]; then + git checkout master + echo "Committing to master branch..." + git add -A + echo "All files added" + git status + if [ $TRAVIS_EVENT_TYPE == "cron" ]; then + git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [cron]" + elif [ $TRAVIS_EVENT_TYPE == "api" ]; then + git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]" + else + git commit --message "Travis build: $TRAVIS_BUILD_NUMBER" + fi + echo "Files commited" + git status + fi + fi +} + +upload_files() { + if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then + if [ $TRAVIS_BRANCH == "master" ]; then + echo "Pushing to master branch..." + git push --force "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" master > /dev/null 2>&1 + echo "Pushing done" + echo "Pushing to website" + git subtree push --prefix website "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" website + echo "Pushed to master branch" + git status + fi + fi +} + +setup_git +commit_website_files +upload_files diff --git a/README.md b/README.md index 421a8f82e..271c71e4f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ![Logo](/icon.png) -# 30-seconds-of-python-code +# 30-seconds-of-python-code [![Tweet](http://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) [![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) @@ -52,6 +52,7 @@ ### chunk Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Chunks an array into smaller lists of a specified size. @@ -77,6 +78,7 @@ chunk([1,2,3,4,5],2) # [[1,2],[3,4],5] ### compact Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Removes falsey values from a list. @@ -97,6 +99,7 @@ compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] ### 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` @@ -108,7 +111,7 @@ Use `map()` to map the values of the list using the given function. Iterate over def count_by(arr, fn=lambda x: x): key = {} for el in map(fn, arr): - key[el] = 0 if not el in key else key[el] + key[el] = 0 if el not in key else key[el] key[el] += 1 return key ``` @@ -125,6 +128,7 @@ count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1} ### count_occurences Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) :information_source: Already implemented via `list.count()`. @@ -152,6 +156,7 @@ count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 ### 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 flattens a list. @@ -185,6 +190,7 @@ deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] ### difference Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Returns the difference between two arrays. @@ -206,6 +212,7 @@ difference([1, 2, 3], [1, 2, 4]) # [3] ### difference_by Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Returns the difference between two list, after applying the provided function to each list element of both. @@ -229,6 +236,7 @@ difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x ### insertion_sort Author:- [Meet Zaveri](https://www.github.com/meetzaveri) + Contributors:-[Meet Zaveri](https://www.github.com/meetzaveri), [Rohit Tanwar](https://www.github.com/kriadmin) 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! @@ -256,6 +264,7 @@ print('Sorted %s' %arr) # sorted [2, 3, 4, 6, 7, 9] ### shuffle Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) :information_source: The same algorithm is already implemented via `random.shuffle`. @@ -289,6 +298,7 @@ shuffle(foo) # [2,3,1] , foo = [1,2,3] ### spread Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list. @@ -313,6 +323,7 @@ spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] ### zip Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) :information_source: Already implemented via `itertools.zip_longest()` @@ -345,13 +356,14 @@ zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, ### average Author:- [Rohit Tanwar](https://www.github.com/kriadmin) - Contributors:-[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 `statistics.mean`. `statistics.mean` takes an array as an argument whereas this function takes variadic arguments. Returns the average of two or more numbers. -Takes the sum of all the `args` and divides it by `len(args)`. The secind argument `0.0` in sum is to handle floating point division in `python2`. +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 `python2`. ```py def average(*args): return sum(args, 0.0) / len(args) @@ -368,6 +380,7 @@ average(1, 2, 3) # 2.0 ### factorial Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Calculates the factorial of a number. @@ -391,6 +404,7 @@ factorial(6) # 720 ### gcd Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin), [cclauss][@cclauss] :information_source: `math.gcd` works with only two numbers @@ -434,6 +448,7 @@ gcd(8,36) # 4 ### lcm Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Returns the least common multiple of two or more numbers. @@ -479,6 +494,7 @@ lcm([1, 3, 4], 5) # 60 ### max_n Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) 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). @@ -506,6 +522,7 @@ max_n([1, 2, 3], 2) # [3,2] ### min_n Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) 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). @@ -534,6 +551,7 @@ min_n([1, 2, 3], 2) # [1,2] ### byte_size Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Returns the length of a string in bytes. @@ -555,6 +573,7 @@ byte_size('Hello World') # 11 ### capitalize Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Capitalizes the first letter of a string. @@ -576,6 +595,7 @@ capitalize('fooBar', True) # 'Foobar' ### capitalize_every_word Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Capitalizes the first letter of every word in a string. @@ -596,6 +616,7 @@ capitalize_every_word('hello world!') # 'Hello World!' ### 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`. @@ -620,6 +641,7 @@ count_vowels('gym') # 0 ### decapitalize Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Decapitalizes the first letter of a string. @@ -641,6 +663,7 @@ decapitalize('FooBar', True) # 'fOOBAR' ### is_lower_case Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Checks if a string is lower case. @@ -663,6 +686,7 @@ is_lower_case('Ab4') # False ### is_upper_case Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Checks if a string is upper case. @@ -685,6 +709,7 @@ is_upper_case('aB4') # False ### palindrome Author:- [Rohit Tanwar](https://www.github.com/kriadmin) + Contributors:-[Rohit Tanwar](https://www.github.com/kriadmin) Returns `True` if the given string is a palindrome, `False` otherwise. diff --git a/test/count_by/count_by.py b/test/count_by/count_by.py index aae034ead..851a83160 100644 --- a/test/count_by/count_by.py +++ b/test/count_by/count_by.py @@ -1,6 +1,6 @@ def count_by(arr, fn=lambda x: x): key = {} for el in map(fn, arr): - key[el] = 0 if not el in key else key[el] + key[el] = 0 if el not in key else key[el] key[el] += 1 return key \ No newline at end of file diff --git a/website/app/snippets b/website/app/snippets index 09c52e118..28ea1fabc 100644 --- a/website/app/snippets +++ b/website/app/snippets @@ -1,8 +1,8 @@ -count_vowels -byte_size -capitalize -capitalize_every_word -decapitalize -palindrome -is_upper_case +count_vowels +byte_size +capitalize +capitalize_every_word +decapitalize +palindrome +is_upper_case is_lower_case \ No newline at end of file diff --git a/website/app/templates/index.html b/website/app/templates/index.html index 88cc3da1a..0551a1b67 100644 --- a/website/app/templates/index.html +++ b/website/app/templates/index.html @@ -1,379 +1,400 @@ -{% extends "base.html" %} - -{% block content %}

Math

average

-

Already implemented via statistics.mean. statistics.mean takes an array as an argument whereas this function takes variadic arguments.

-

Returns the average of two or more numbers.

-

Takes the sum of all the args and divides it by len(args). The secind argument 0.0 in sum is to handle floating point division in python2.

- -
def average(*args):
-    return sum(args, 0.0) / len(args)
- -
average(*[1, 2, 3]) # 2.0
-average(1, 2, 3) # 2.0
-
- -

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.

- -
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)
- -
factorial(6) # 720
-
- -

gcd

-

math.gcd works with only two numbers

-

Calculates the greatest common divisor between two or more numbers/lists.

-

The helperGcdfunction uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.

-

Uses the reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.

- -
from functools import reduce
-
-
-def spread(arg):
-    ret = []
-    for i in arg:
-        if isinstance(i, list):
-            ret.extend(i)
-        else:
-            ret.append(i)
-    return ret
-
-
-def gcd(*args):
-    numbers = []
-    numbers.extend(spread(list(args)))
-
-    def _gcd(x, y):
-        return x if not y else gcd(y, x % y)
-
-    return reduce((lambda x, y: _gcd(x, y)), numbers)
- -
gcd(8,36) # 4
-
- -

lcm

-

Returns the least common multiple of two or more numbers.

-

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

-

Uses reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.

- -
from functools import reduce
-
-
-def spread(arg):
-    ret = []
-    for i in arg:
-        if isinstance(i, list):
-            ret.extend(i)
-        else:
-            ret.append(i)
-    return ret
-
-
-def lcm(*args):
-    numbers = []
-    numbers.extend(spread(list(args)))
-
-    def _gcd(x, y):
-        return x if not y else gcd(y, x % y)
-
-    def _lcm(x, y):
-        return x * y / _gcd(x, y)
-
-    return reduce((lambda x, y: _lcm(x, y)), numbers)
- -
lcm(12, 7) # 84
-lcm([1, 3, 4], 5) # 60
-
- -

max_n

-

Returns the n maximum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in descending order).

-

Use list.sort() combined with the deepcopy function from the inbuilt copy module to create a shallow clone of the list and sort it in ascending order and then use list.reverse() reverse it to make it descending order. Use [:n] to get the specified number of elements. Omit the second argument, n, to get a one-element array

- -
from copy import deepcopy
-
-
-def max_n(arr, n=1):
-    numbers = deepcopy(arr)
-    numbers.sort()
-    numbers.reverse()
-    return numbers[:n]
- -
max_n([1, 2, 3]) # [3]
-max_n([1, 2, 3], 2) # [3,2]
-
- -

min_n

-

Returns the n minimum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).

-

Use list.sort() combined with the deepcopy function from the inbuilt copy module to create a shallow clone of the list and sort it in ascending order. Use [:n] to get the specified number of elements. Omit the second argument, n, to get a one-element array

- -
from copy import deepcopy
-
-
-def min_n(arr, n=1):
-    numbers = deepcopy(arr)
-    numbers.sort()
-    return numbers[:n]
- -
min_n([1, 2, 3]) # [1]
-min_n([1, 2, 3], 2) # [1,2]
-
- -

List

chunk

-

Chunks an array into smaller lists of a specified size.

-

Uses range to create a list of desired size. Then use map on this list and fill it with splices of arr.

- -
from math import ceil
-
-
-def chunk(arr, size):
-    return list(
-        map(lambda x: arr[x * size:x * size + size],
-            list(range(0, ceil(len(arr) / size)))))
- -
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
-
- -

compact

-

Removes falsey values from a list.

-

Use filter() to filter out falsey values (False, None, 0, and "").

- -
def compact(arr):
-    return list(filter(lambda x: bool(x), arr))
- -
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
-
- -

count_occurences

-

Already implemented via list.count().

-

Counts the occurrences of a value in an list.

-

Uses the reduce functin from built-in module functools to increment a counter each time you encounter the specific value inside the list.

- -
def count_occurences(arr, val):
-    return reduce(
-        (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
-        arr)
- -
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
-
- -

deep_flatten

-

Deep flattens a list.

-

Use recursion. Use list.extend() with an empty array (result) and the spread function to flatten a list. Recursively flatten each element that is a list.

- -
def spread(arg):
-    ret = []
-    for i in arg:
-        if isinstance(i, list):
-            ret.extend(i)
-        else:
-            ret.append(i)
-    return ret
-
-
-def deep_flatten(arr):
-    result = []
-    result.extend(
-        spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
-    return result
- -
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
-
- -

difference

-

Returns the difference between two arrays.

-

Create a set from b, then use list comprehension to only keep values not contained in b

- -
def difference(a, b):
-    b = set(b)
-    return [item for item in a if item not in b]
- -
difference([1, 2, 3], [1, 2, 4]) # [3]
-
- -

shuffle

-

The same algorithm is already implemented via random.shuffle.

-

Randomizes the order of the values of an list, returning a new list.

-

Uses the Fisher-Yates algorithm to reorder the elements of the list.

- -
from copy import deepcopy
-from random import randint
-
-
-def shuffle(arr):
-    temp_arr = deepcopy(arr)
-    m = len(temp_arr)
-    while (m):
-        m -= 1
-        i = randint(0, m)
-        temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
-    return temp_arr
- -
foo = [1,2,3]
-shuffle(foo) # [2,3,1] , foo = [1,2,3]
-
- -

spread

-

Implements javascript's [].concat(...arr). Flattens the list(non-deep) and returns an list.

- -
def spread(arg):
-    ret = []
-    for i in arg:
-        if isinstance(i, list):
-            ret.extend(i)
-        else:
-            ret.append(i)
-    return ret
- -
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
-
- -

zip

-

Already implemented via itertools.zip_longest()

-

Creates a list of elements, grouped based on the position in the original lists.

-

Use max combined with list comprehension to get the length of the longest list in the arguments. Loops for max_length times grouping elements. If lengths of lists vary fill_value is used. By default fill_value is None.

- -
def zip(*args, fillvalue=None):
-    max_length = max([len(arr) for arr in args])
-    result = []
-    for i in range(max_length):
-        result.append([
-            args[k][i] if i < len(args[k]) else None for k in range(len(args))
-        ])
-    return result
- -
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]]
-
- -

count_by

-

Already implemented via collections.Counter

-

Groups the elements of a list based on the given function and returns the count of elements in each group.

-

Use map() to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.

- -
def count_by(arr, fn=lambda x: x):
-    key = {}
-    for el in map(fn, arr):
-        key[el] = 0 if not el in key else key[el]
-        key[el] += 1
-    return key
- -
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}
-
- -

difference_by

-

Returns the difference between two list, after applying the provided function to each list element of both.

-

Create a set by applying fn to each element in b, then use list comprehension in combination with fn on a to only keep values not contained in the previously created set.

- -
def difference_by(a, b, fn):
-    b = set(map(fn, b))
-    return [item for item in a if fn(item) not in b]
- -
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 } ]
-
- -

String

count_vowels

-

Retuns number of vowels in provided string.

-

Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.

- -
import re
-
-
-def count_vowels(str):
-    return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
- -
count_vowels('foobar') # 3
-count_vowels('gym') # 0
-
- -

byte_size

-

Returns the length of a string in bytes.

-

utf-8 encodes a given string and find its length.

- -
def byte_size(string):
-    return(len(string.encode('utf-8')))
- -
byte_size('😀') # 4
-byte_size('Hello World') # 11
-
- -

capitalize

-

Capitalizes the first letter of a string.

-

Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the lower_rest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

- -
def capitalize(string, lower_rest=False):
-    return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
- -
capitalize('fooBar') # 'FooBar'
-capitalize('fooBar', True) # 'Foobar'
-
- -

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.

- -
def capitalize_every_word(string):
-    return string.title()
- -
capitalize_every_word('hello world!') # 'Hello World!'
-
- -

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.

- -
def decapitalize(string, upper_rest=False):
-    return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
- -
decapitalize('FooBar') # 'fooBar'
-decapitalize('FooBar', True) # 'fOOBAR'
-
- -

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.

- -
def palindrome(string):
-    from re import sub
-    s = sub('[\W_]', '', string.lower())
-    return s == s[::-1]
- -
palindrome('taco cat') # True
-
- -

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.

- -
def is_upper_case(str):
-    return str == str.upper()
- -
is_upper_case('ABC') # True
-is_upper_case('a3@$') # True
-is_upper_case('aB4') # False
-
- -

is_lower_case

-

Checks if a string is lower case.

-

Convert the given string to lower case, using str.lower() method and compare it to the original.

- -
def is_lower_case(str):
-    return str == str.lower()
- -
is_lower_case('abc') # True
-is_lower_case('a3@$') # True
-is_lower_case('Ab4') # False
-
- -
- +{% extends "base.html" %} + +{% block content %}

Math

average

+

Already implemented via statistics.mean. statistics.mean takes an array as an argument whereas this function takes variadic arguments.

+

Returns the average of two or more numbers.

+

Takes the sum of all the args and divides it by len(args). The second argument 0.0 in sum is to handle floating point division in python2.

+ +
def average(*args):
+    return sum(args, 0.0) / len(args)
+ +
average(*[1, 2, 3]) # 2.0
+average(1, 2, 3) # 2.0
+
+ +

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.

+ +
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)
+ +
factorial(6) # 720
+
+ +

gcd

+

math.gcd works with only two numbers

+

Calculates the greatest common divisor between two or more numbers/lists.

+

The helperGcdfunction uses recursion. Base case is when y equals 0. In this case, return x. Otherwise, return the GCD of y and the remainder of the division x/y.

+

Uses the reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.

+ +
from functools import reduce
+
+
+def spread(arg):
+    ret = []
+    for i in arg:
+        if isinstance(i, list):
+            ret.extend(i)
+        else:
+            ret.append(i)
+    return ret
+
+
+def gcd(*args):
+    numbers = []
+    numbers.extend(spread(list(args)))
+
+    def _gcd(x, y):
+        return x if not y else gcd(y, x % y)
+
+    return reduce((lambda x, y: _gcd(x, y)), numbers)
+ +
gcd(8,36) # 4
+
+ +

lcm

+

Returns the least common multiple of two or more numbers.

+

Use the greatest common divisor (GCD) formula and the fact that lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple. The GCD formula uses recursion.

+

Uses reduce function from the inbuilt module functools. Also defines a method spread for javascript like spreading of lists.

+ +
from functools import reduce
+
+
+def spread(arg):
+    ret = []
+    for i in arg:
+        if isinstance(i, list):
+            ret.extend(i)
+        else:
+            ret.append(i)
+    return ret
+
+
+def lcm(*args):
+    numbers = []
+    numbers.extend(spread(list(args)))
+
+    def _gcd(x, y):
+        return x if not y else _gcd(y, x % y)
+
+    def _lcm(x, y):
+        return x * y / _gcd(x, y)
+
+    return reduce((lambda x, y: _lcm(x, y)), numbers)
+ +
lcm(12, 7) # 84
+lcm([1, 3, 4], 5) # 60
+
+ +

max_n

+

Returns the n maximum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in descending order).

+

Use list.sort() combined with the deepcopy function from the inbuilt copy module to create a shallow clone of the list and sort it in ascending order and then use list.reverse() reverse it to make it descending order. Use [:n] to get the specified number of elements. Omit the second argument, n, to get a one-element array

+ +
from copy import deepcopy
+
+
+def max_n(arr, n=1):
+    numbers = deepcopy(arr)
+    numbers.sort()
+    numbers.reverse()
+    return numbers[:n]
+ +
max_n([1, 2, 3]) # [3]
+max_n([1, 2, 3], 2) # [3,2]
+
+ +

min_n

+

Returns the n minimum elements from the provided list. If n is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).

+

Use list.sort() combined with the deepcopy function from the inbuilt copy module to create a shallow clone of the list and sort it in ascending order. Use [:n] to get the specified number of elements. Omit the second argument, n, to get a one-element array

+ +
from copy import deepcopy
+
+
+def min_n(arr, n=1):
+    numbers = deepcopy(arr)
+    numbers.sort()
+    return numbers[:n]
+ +
min_n([1, 2, 3]) # [1]
+min_n([1, 2, 3], 2) # [1,2]
+
+ +

List

chunk

+

Chunks an array into smaller lists of a specified size.

+

Uses range to create a list of desired size. Then use map on this list and fill it with splices of arr.

+ +
from math import ceil
+
+
+def chunk(arr, size):
+    return list(
+        map(lambda x: arr[x * size:x * size + size],
+            list(range(0, ceil(len(arr) / size)))))
+ +
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
+
+ +

compact

+

Removes falsey values from a list.

+

Use filter() to filter out falsey values (False, None, 0, and "").

+ +
def compact(arr):
+    return list(filter(lambda x: bool(x), arr))
+ +
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
+
+ +

count_occurences

+

Already implemented via list.count().

+

Counts the occurrences of a value in an list.

+

Uses the reduce functin from built-in module functools to increment a counter each time you encounter the specific value inside the list.

+ +
from functools import reduce
+
+
+def count_occurences(arr, val):
+    return reduce(
+        (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
+        arr)
+ +
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
+
+ +

deep_flatten

+

Deep flattens a list.

+

Use recursion. Use list.extend() with an empty array (result) and the spread function to flatten a list. Recursively flatten each element that is a list.

+ +
def spread(arg):
+    ret = []
+    for i in arg:
+        if isinstance(i, list):
+            ret.extend(i)
+        else:
+            ret.append(i)
+    return ret
+
+
+def deep_flatten(arr):
+    result = []
+    result.extend(
+        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, arr))))
+    return result
+ +
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
+
+ +

difference

+

Returns the difference between two arrays.

+

Create a set from b, then use list comprehension to only keep values not contained in b

+ +
def difference(a, b):
+    b = set(b)
+    return [item for item in a if item not in b]
+ +
difference([1, 2, 3], [1, 2, 4]) # [3]
+
+ +

shuffle

+

The same algorithm is already implemented via random.shuffle.

+

Randomizes the order of the values of an list, returning a new list.

+

Uses the Fisher-Yates algorithm to reorder the elements of the list.

+ +
from copy import deepcopy
+from random import randint
+
+
+def shuffle(arr):
+    temp_arr = deepcopy(arr)
+    m = len(temp_arr)
+    while (m):
+        m -= 1
+        i = randint(0, m)
+        temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
+    return temp_arr
+ +
foo = [1,2,3]
+shuffle(foo) # [2,3,1] , foo = [1,2,3]
+
+ +

spread

+

Implements javascript's [].concat(...arr). Flattens the list(non-deep) and returns an list.

+ +
def spread(arg):
+    ret = []
+    for i in arg:
+        if isinstance(i, list):
+            ret.extend(i)
+        else:
+            ret.append(i)
+    return ret
+ +
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
+
+ +

zip

+

Already implemented via itertools.zip_longest()

+

Creates a list of elements, grouped based on the position in the original lists.

+

Use max combined with list comprehension to get the length of the longest list in the arguments. Loops for max_length times grouping elements. If lengths of lists vary fill_value is used. By default fill_value is None.

+ +
def zip(*args, fillvalue=None):
+    max_length = max([len(arr) for arr in args])
+    result = []
+    for i in range(max_length):
+        result.append([
+            args[k][i] if i < len(args[k]) else None for k in range(len(args))
+        ])
+    return result
+ +
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]]
+
+ +

count_by

+

Already implemented via collections.Counter

+

Groups the elements of a list based on the given function and returns the count of elements in each group.

+

Use map() to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.

+ +
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
+ +
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}
+
+ +

difference_by

+

Returns the difference between two list, after applying the provided function to each list element of both.

+

Create a set by applying fn to each element in b, then use list comprehension in combination with fn on a to only keep values not contained in the previously created set.

+ +
def difference_by(a, b, fn):
+    b = set(map(fn, b))
+    return [item for item in a if fn(item) not in b]
+ +
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 } ]
+
+ +

insertion_sort

+

On a very basic level, an insertion sort algorithm contains the logic of shifting around and inserting elements in order to sort an unordered list of any size. The way that it goes about inserting elements, however, is what makes insertion sort so very interesting!

+ +
def insertion_sort(arr):
+
+    for i in range(1, len(arr)):
+        key = arr[i]
+        j = i - 1
+        while j >= 0 and key < arr[j]:
+            arr[j + 1] = arr[j]
+            j -= 1
+            arr[j + 1] = key
+ +
arr = [7,4,9,2,6,3]
+insertionsort(arr)
+print('Sorted %s'  %arr) # sorted [2, 3, 4, 6, 7, 9]
+
+ +

String

count_vowels

+

Retuns number of vowels in provided string.

+

Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.

+ +
import re
+
+
+def count_vowels(str):
+    return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
+ +
count_vowels('foobar') # 3
+count_vowels('gym') # 0
+
+ +

byte_size

+

Returns the length of a string in bytes.

+

utf-8 encodes a given string and find its length.

+ +
def byte_size(string):
+    return(len(string.encode('utf-8')))
+ +
byte_size('😀') # 4
+byte_size('Hello World') # 11
+
+ +

capitalize

+

Capitalizes the first letter of a string.

+

Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the lower_rest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

+ +
def capitalize(string, lower_rest=False):
+    return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
+ +
capitalize('fooBar') # 'FooBar'
+capitalize('fooBar', True) # 'Foobar'
+
+ +

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.

+ +
def capitalize_every_word(string):
+    return string.title()
+ +
capitalize_every_word('hello world!') # 'Hello World!'
+
+ +

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.

+ +
def decapitalize(string, upper_rest=False):
+    return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
+ +
decapitalize('FooBar') # 'fooBar'
+decapitalize('FooBar', True) # 'fOOBAR'
+
+ +

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.

+ +
def palindrome(string):
+    from re import sub
+    s = sub('[\W_]', '', string.lower())
+    return s == s[::-1]
+ +
palindrome('taco cat') # True
+
+ +

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.

+ +
def is_upper_case(str):
+    return str == str.upper()
+ +
is_upper_case('ABC') # True
+is_upper_case('a3@$') # True
+is_upper_case('aB4') # False
+
+ +

is_lower_case

+

Checks if a string is lower case.

+

Convert the given string to lower case, using str.lower() method and compare it to the original.

+ +
def is_lower_case(str):
+    return str == str.lower()
+ +
is_lower_case('abc') # True
+is_lower_case('a3@$') # True
+is_lower_case('Ab4') # False
+
+ +
+
{% endblock %} \ No newline at end of file