Python through 30 seconds can learn the beautiful short program code of process full solution

  • 2021-12-09 09:15:04
  • OfStack

① 2-D list

Returns a 2-dimensional list based on the given length and width and initial values:


def initialize_2d_list(w, h, val=None):
    return [[val for x in range(w)] for y in range(h)]

For example:


>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]

② Function cutting array

Use a function applied to each element of an array so that the array is cut into two parts. If the function is applied to an element and returns a value of True, the element is cut to Part 1, otherwise it is divided into Part 2:


def bifurcate_by(lst, fn):
    return [
      [x for x in lst if fn(x)],
      [x for x in lst if not fn(x)]
    ]

For example:


>>> bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b') 
[['beep', 'boop', 'bar'], ['foo']]

③ Intersection point

After two arrays are applied by a function, the original elements of the common elements are extracted from the first array to form a new array:


def intersection_by(a, b, fn):
    _b = set(map(fn, b))
    return [item for item in a if fn(item) in _b]

For example:


>>> from math import floor
>>> intersection_by([2.1, 1.2], [2.3, 3.4],floor)
[2.1]

④ Maximum subscript

Returns the subscript of the maximum value in the array:


def max_element_index(arr):
    return arr.index(max(arr))

For example:


>>> max_element_index([5, 8, 9, 7, 10, 3, 0])
4

⑤ Array symmetry difference

Find out the different elements in the two arrays and synthesize them into a new array:


def symmetric_difference(a, b):
    _a, _b = set(a), set(b)
    return [item for item in a if item not in _b] + [item for item in b if item not in _a]

For example:


>>> symmetric_difference([1, 2, 3], [1, 2, 4])
[3, 4]

Number of clips

Returns num if num falls within a range of 1 digits, otherwise returns the nearest boundary to this range:


>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]
0

For example:


>> clamp_number(2,3,10)
3

>> clamp_number(7,3,10)
7

>> clamp_number(124,3,10)
10

⑦ Bond-value mapping

Recreate objects with their keys and run functions to create values for each object's key; Use dict. keys () to traverse the key of the object and generate a new value through the function;

def map_values(obj, fn):
    ret = {}
    for key in obj.keys():
        ret[key] = fn(obj[key])
    return ret

For example:


>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]
3

8 Case conversion

Change the first letters of English words from uppercase to lowercase; upper_rest parameter: Sets whether to convert other letters except the first letter to case;

>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]
4

For example:


>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]
5

Pet-name ruby summation with the same bond

Sum objects with the same key value in each dictionary in the list:


>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]
6

For example:


>>> sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }], lambda v : v['n'])
14

Attending 1 line of code to find the number of occurrences

Find the number of occurrences of a number in the list and:


def count_occurrences(lst, val):
    return len([x for x in lst if x == val and type(x) == type(val)])

For example:


>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]
9

Array regrouping

Break down 1 list according to the required size:


from math import ceil
def chunk(lst, size):
	return list (
		map(lambda x:lst[x * size:x * size + size],
			list(range(0, int(ceil(len(lst) / size))))))

The effect is as follows:


chunk([1,2,3,4,5],2)
# [[1,2],[3,4],5]

In return, the second parameter of map is a list, and map uses every element in the list to call the function function of the first parameter, returning a new list containing the return value of each function function.

Digital to array

The same is about the application of map, which splits the shaping numbers into arrays:


def digitize(n):
    return list(map(int, str(n)))

The effect is as follows:


digitize(123)
# [1, 2, 3]

After it converts the shaping number n into a string, it also automatically serializes and divides the string. Finally, it applies the element to the first parameter of map, and returns after being converted into shaping.

Non-recursive Fibonacci

Fibonacci sequence, the sum of the first two numbers is the value of the third number, such as 0, 1, 1, 2, 3, 5, 8, 13 … If we use recursion to implement this algorithm, the efficiency is very low, so we use non-recursive method to implement it:

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

The effect is as follows:


fibonacci(7)
# [0, 1, 1, 2, 3, 5, 8, 13]

Underlined string batch system 1 variable name or string format:


from re import sub

def snake(s):
	return '_'.join(
		sub('([A-Z][a-z]+)', r' 1',
		sub('( [A-Z]+)', r' l1',
		s.replace('-', ' '))).split()).lower()

The effect is as follows:


snake('camelCase')# 'camel_case'

snake('some text')# 'some_text'

snake('some-mixed_string With spaces_underscores-and-hyphens')# 'some_mixed_string_with_spaces_underscores_and_hyphens'

snake('AllThe-small Things')# "all_the_small_things"
re. sub is used to replace matches in strings. This is actually a usage of "Taowa", which may not be easy to understand at first and needs to be understood slowly. The first replacement is to replace '-' with '' in the s string. The second substitution, for the first substituted string, replaces the character segments (all uppercase words) of the '([A-Z] +)' regular expression with r '\ 1', that is, separates each word with a space. The third substitution is to replace the string after the second substitution with r '\ 1' for character segments (that is, words with uppercase initials and lowercase other letters) that conform to the '([A-Z] [a-z] +)' regular expression, and also to separate words with spaces.

Related articles: