I'm still looking for cases. I've brought you 30 Python cases

Posted by tooNight on Thu, 20 Jan 2022 22:41:18 +0100

Hello, everyone. I'm a meow in the IT industry.

Python is one of the most popular languages at present. It is widely used by many people in data science, machine learning, web development, scripting and automation. Its simplicity and ease of use make it so popular.

In this article, we will introduce 30 short code fragments that you can understand and learn in 30 seconds or less.

30 cases, first comfort your eyes before learning

1. Check for duplicate elements

The following method can check whether there are duplicate elements in a given list. It uses the set() attribute, which removes duplicate elements from the list.

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

2. Modified words

Detect whether two strings are muted words (i.e. reverse the character order)

from collections import Counter      
def anagram(first, second):      
    return Counter(first) == Counter(second)    
 anagram("abcd3", "3acdb") # True 

3. Check the memory usage

The following code snippet can be used to check the memory usage of an object.

import sys   
variable = 30    
print(sys.getsizeof(variable)) # 24 

4. Byte size calculation

The following method returns the string length in bytes.

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

5. Repeatedly print the string N times

The following code can print a string n times without using a loop

n = 2;   
s ="Programming"; print(s * n);   
# ProgrammingProgramming 

6. Initial capitalization

The following code snippet uses the title() method to capitalize each word in the string.

s = "programming is awesome"      
print(s.title()) # Programming Is Awesome 

7. Block

The following method uses range() to block the list into smaller lists of the specified size.

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

8. Compression

The following method uses fliter() to delete the error values in the list (such as False, None, 0 and "")

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

9. Number of intervals

The following code snippet can be used to convert a two-dimensional array.

array = [[ a ,  b ], [ c ,  d ], [ e ,  f ]]      
transposed = zip(*array)      
print(transposed) # [( a ,  c ,  e ), ( b ,  d ,  f )] 

10. Chain comparison

The following code can compare multiple times with various operators in one line.

a = 3      
print( 2 < a < 8) # True      
print(1 == a < 2) # False 

11. Comma separated

The following code snippet converts a list of strings into a single string, with each element in the list separated by commas.

hobbies = ["basketball", "football", "swimming"]  
print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming 

12. Calculate the number of vowels

The following method calculates the number of vowel letters ('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 

13. Restore the initial to lowercase

The following method can be used to convert the first letter of a given string to lowercase.

def decapitalize(string):      
    return str[:1].lower() + str[1:]   
decapitalize( FooBar ) #  fooBar    
decapitalize( FooBar ) #  fooBar 

14. Planarization

The following method uses recursion to expand the list of potential depths.

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

15. Differences

This method only preserves the value in the first iterator to find the difference between the two iterators.

def difference(a, b):  
    setset_a = set(a) 
    setset_b = set(b)  
    comparison = set_a.difference(set_b)  
    return list(comparison)  
difference([1,2,3], [1,2,4]) # [3] 

Visual fatigue - take a break

16. Look for differences

The following method returns the difference between the two lists after applying the given function to each element of the two lists.

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

17. Chained function call

The following methods can call multiple functions in one row.

def add(a, b):  
    return a + b  
def subtract(a, b):  
    return a - b  
a, b = 4, 5  
print((subtract if a > b else add)(a, b)) # 9 

18. Check for duplicate values

The following method uses the fact that the set() method contains only unique elements to check whether the list has duplicate values.

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

19. Merge two dictionaries

The following methods can be used to merge two dictionaries.

def merge_two_dicts(a, b):  
    c = a.copy()   # make a copy of a  
    c.update(b)    # modify keys and values of a with the ones from b  
    return c  
a = {  x : 1,  y : 2}  
b = {  y : 3,  z : 4}  
print(merge_two_dicts(a, b)) # { y : 3,  x : 1,  z : 4} 

In Python 3.5 and later, you can also do the following:

def merge_dictionaries(a, b)   return {**a, **b}a = {  x : 1,  y : 2}b = {  y : 3,  z : 4}print(merge_dictionaries(a, b)) # { y : 3,  x : 1,  z : 4}

20. Convert two lists into one dictionary

The following method converts two lists into a dictionary.

def to_dictionary(keys, values):  
    return dict(zip(keys, values))     
keys = ["a", "b", "c"]      
values = [2, 3, 4]  
print(to_dictionary(keys, values)) # { a : 2,  c : 4,  b : 3} 

21. Use enumeration

The following method takes the dictionary as input, and then returns only the keys in the dictionary.

list = ["a", "b", "c", "d"]  
for index, element in enumerate(list):   
    print("Value", element, "Index ", index, )  
# ( Value ,  a ,  Index  , 0)  
# ( Value ,  b ,  Index  , 1)  
#( Value ,  c ,  Index  , 2)  
# ( Value ,  d ,  Index  , 3) 

22. Calculate the time required

The following code snippet can be used to calculate the time required to execute specific code.

import time  
start_time = time.time()  
a = 1  
b = 2  
c = a + b  
print(c) #3  
end_time = time.time()  
total_time = end_time - start_time  
print("Time: ", total_time)  
# ( Time:  , 1.1205673217773438e-05) 

23.Try else command

You can use the else clause as part of the try/except block and execute it if no exception is thrown.

try:  
    2*3  
except TypeError:  
    print("An exception was raised") 
else: 
    print("Thank God, no exceptions were raised.") 
#Thank God, no exceptions were raised. 

24. Find the most common elements

The following method returns the most common elements that appear in the list.

def most_frequent(list):  
    return max(set(list), key = list.count)    
list = [1,2,1,2,3,2,1,4,2]  
most_frequent(list) 

25. Palindrome

The following method checks whether a given string is a palindrome structure. This method first converts the string to lowercase, and then removes non alphanumeric characters from it. Finally, it compares the new string with the inverted version.

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

26. Simple calculator without if else statement

The following code snippet shows how to write a simple calculator without using if else conditions.

import operator  
action = {  
    "+": operator.add,  
    "-": operator.sub,  
    "/": operator.truediv,  
    "*": operator.mul,  
    "**": pow 
}  
print(action[ - ](50, 25)) # 25 

27. Element order disorder

The following algorithm randomly disrupts the order of elements in the list by implementing Fisher Yates algorithm to sort in the new 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    
foo = [1,2,3]  
shuffle(foo) # [2,3,1] , foo = [1,2,3] 

28. List flattening

The following method flattens the list, similar to [] concat(…arr).

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] 

29. Variable exchange

Here is a quick way to swap two variables without using additional variables.

def swap(a, b): 
  return b, a  
a, b = -1, 14 
swap(a, b) # (14, -1) 

30. Get the default value of the missing key

The following code snippet shows how to get the default value if the dictionary does not contain the key to find.

d = { a : 1,  b : 2}  
print(d.get( c , 3)) # 3 

The above is a short list of useful methods you may find in your daily work. It is mainly based on the GitHub project( https://github.com/30-seconds/30_seconds_of_knowledge ), you can find many other useful code snippets, including Python and other programming languages and technologies.

Topics: Python list Flask