29 Star 96 Fork 32

30秒学代码 / 30-seconds-of-python-code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
CC0-1.0

Logo

30-seconds-of-python-code Tweet

License first-timers-only Gitter chat PRs Welcome Travis Build Insight.io js-semistandard-style FOSSA Status

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.

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

:books: List

View contents

:heavy_division_sign: Math

View contents

:card_file_box: Object

View contents

:scroll: String

View contents

:books: List

bubble_sort

Author:- Shobhit Sachan

Contributors:- Shobhit Sachan

Bubble_sort uses the technique of comparing and swapping

def bubble_sort(lst):
    for passnum in range(len(lst) - 1, 0, -1):
        for i in range(passnum):
            if lst[i] > lst[i + 1]:
                temp = lst[i]
                lst[i] = lst[i + 1]
                lst[i + 1] = temp
View Examples
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]


:arrow_up: Back to top

chunk

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

Chunks an list 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 lst.

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)))))
View Examples
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]


:arrow_up: Back to top

compact

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

Removes falsey values from a list.

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

def compact(lst):
    return list(filter(bool, lst))
View Examples
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]


:arrow_up: Back to top

count_by

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

:information_source: Already implemented via collections.Counter

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

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

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
View Examples
from math import floor
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}


:arrow_up: Back to top

count_occurences

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar, Hui Binyuan

:information_source: Already implemented via list.count().

Counts the occurrences of a value in an list.

Uses the list comprehension to increment a counter each time you encounter the specific value inside the list.

def count_occurrences(lst, val):
    return len([x for x in lst if x == val and type(x) == type(val)])
View Examples
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3


:arrow_up: Back to top

deep_flatten

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar, Meet Zaveri

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.

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret


def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result
View Examples
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]


:arrow_up: Back to top

difference

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

Returns the difference between two iterables.

Use list comprehension to only keep values not contained in b

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


:arrow_up: Back to top

difference_by

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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]
View Examples
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]


:arrow_up: Back to top

has_duplicates

Author:- Rob-Rychs

Contributors:- Rob-Rychs

Checks a flat list for duplicate values. Returns True if duplicate values exist and False if values are 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.

def has_duplicates(lst):
    return len(lst) != len(set(lst))
View Examples
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False


:arrow_up: Back to top

insertion_sort

Author:- Meet Zaveri

Contributors:-Meet Zaveri, Rohit Tanwar

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(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
View Examples
lst = [7,4,9,2,6,3]
insertionsort(lst)
print('Sorted %s'  %lst) # sorted [2, 3, 4, 6, 7, 9]


:arrow_up: Back to top

shuffle

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

:information_source: The same algorithm is already implemented via random.shuffle.

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

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

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
View Examples
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]


:arrow_up: Back to top

spread

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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
View Examples
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]


:arrow_up: Back to top

zip

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

:information_source: Already implemented via itertools.zip_longest()

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

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

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 None for k in range(len(args))
        ])
    return result
View Examples
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]


:arrow_up: Back to top

:heavy_division_sign: Math

average

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar, Hui Binyuan

: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 second argument 0.0 in sum is to handle floating point division in python3.

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


:arrow_up: Back to top

factorial

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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


:arrow_up: Back to top

gcd

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar, cclauss

:information_source: math.gcd works with only two numbers

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

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

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

from functools import reduce


def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret


def gcd(*args):
    numbers = []
    numbers.extend(spread(list(args)))

    def _gcd(x, y):
        return x if not y else gcd(y, x % y)

    return reduce((lambda x, y: _gcd(x, y)), numbers)
View Examples
gcd(8,36) # 4


:arrow_up: Back to top

lcm

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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)
View Examples
lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60


:arrow_up: Back to top

max_n

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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 list

def max_n(lst, n=1, reverse=True):
    return sorted(lst, reverse=reverse)[:n]
View Examples
max_n([1, 2, 3]) # [3]
max_n([1, 2, 3], 2) # [3,2]


:arrow_up: Back to top

min_n

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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 list

from copy import deepcopy


def min_n(lst, n=1):
    numbers = deepcopy(lst)
    numbers.sort()
    return numbers[:n]
View Examples
min_n([1, 2, 3]) # [1]
min_n([1, 2, 3], 2) # [1,2]


:arrow_up: Back to top

:card_file_box: Object

all_unique

Author:- Rob-Rychs

Contributors:- Rob-Rychs

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.

def all_unique(lst):
    return len(lst) == len(set(lst))
View Examples
x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True
all_unique(y) # False


:arrow_up: Back to top

keys_only

Author:- Rob-Rychs

Contributors:- Rob-Rychs

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).

def keys_only(flat_dict):
    lst = []
    for k, v in flat_dict.items():
        lst.append(k)
    return lst
View Examples
ages = {
     "Peter": 10,
     "Isabel": 11,
     "Anna": 9,
}
keys_only(ages) # ['Peter', 'Isabel', 'Anna']


:arrow_up: Back to top

values_only

Author:- Rob-Rychs

Contributors:- Rob-Rychs

Function which accepts a dictionary of key value pairs and returns a new flat list of only the values.

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.

def values_only(dict):
    lst = []
    for k, v in dict.items():
        lst.append(v)
    return lst
View Examples
ages = {
     "Peter": 10,
     "Isabel": 11,
     "Anna": 9,
}
values_only(ages) # [10, 11, 9]


:arrow_up: Back to top

:scroll: String

byte_size

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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')))
View Examples
byte_size('😀') # 4
byte_size('Hello World') # 11


:arrow_up: Back to top

capitalize

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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:])
View Examples
capitalize('fooBar') # 'FooBar'
capitalize('fooBar', True) # 'Foobar'


:arrow_up: Back to top

capitalize_every_word

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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()
View Examples
capitalize_every_word('hello world!') # 'Hello World!'


:arrow_up: Back to top

count_vowels

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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)))
View Examples
count_vowels('foobar') # 3
count_vowels('gym') # 0


:arrow_up: Back to top

decapitalize

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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:])
View Examples
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar', True) # 'fOOBAR'


:arrow_up: Back to top

is_lower_case

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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(string):
    return string == string.lower()
View Examples
is_lower_case('abc') # True
is_lower_case('a3@$') # True
is_lower_case('Ab4') # False


:arrow_up: Back to top

is_upper_case

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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(string):
    return string == string.upper()
View Examples
is_upper_case('ABC') # True
is_upper_case('a3@$') # True
is_upper_case('aB4') # False


:arrow_up: Back to top

palindrome

Author:- Rohit Tanwar

Contributors:-Rohit Tanwar

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]
View Examples
palindrome('taco cat') # True


:arrow_up: Back to top

Credits

Icons made by Smashicons from www.flaticon.com is licensed by CC 3.0 BY.

License

FOSSA Status

CC0 1.0 Universal Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. For more information, please see <http://creativecommons.org/publicdomain/zero/1.0/>

简介

Python 语言版的 30 秒学代码 展开 收起
Python
CC0-1.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Python
1
https://gitee.com/seconds-of-code/30-seconds-of-python-code.git
git@gitee.com:seconds-of-code/30-seconds-of-python-code.git
seconds-of-code
30-seconds-of-python-code
30-seconds-of-python-code
master

搜索帮助