1. Regroup arrays

Subdivide a list according to the desired size:

The effect is as follows:

EXAMPLES the chunk ([1, 2, 3, 4, 5], 2) # [[1, 2], [3, 4], 5]Copy the code

In return, the second argument to map is a list. Map uses each element in the list to call function with the first argument, returning a new list containing the value returned by function each time.

2. Turn numbers into arrays

Here’s another map application that splits integer numbers into arrays:

def digitize(n):

  return list(map(int, str(n)))
Copy the code

The effect is as follows:

EXAMPLES

digitize(123)# [1, 2, 3]
Copy the code

After it converts the integer number N to a string, it also automatically serializes the string, and finally applies the element to the first parameter of the map, converts it to an integer and returns.

Non-recursive Fibonacci

Remember the Fibonacci sequence, where the sum of the first two numbers is the value of the third: 0, 1, 1, 2, 3, 5, 8, 13….

It would be very inefficient to implement this algorithm recursively, so let’s implement it non-recursively:

The effect is as follows:

EXAMPLES

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

It is very simple to see so, but the thinking should be around oh.

4. Underline the string

Batch uniform variable name or string format.

The effect is as follows:

EXAMPLES

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"
Copy the code

Re.sub is used to replace the match in the string. This is actually a “nesting doll” usage, may not be very easy to understand at first, need to understand slowly.

The first substitution is to replace ‘-‘ with ‘ ‘in the s string.

The second substitution, for the first replaced string, is to use r’ \1′ for the range of characters (all uppercase words) that match the regular expression ‘([a-z]+)’, that is, to separate each word with Spaces.

The third substitution is to replace the second replaced string with r’ \1′ for the range of characters that fit the regular expression ‘([a-z] [a-z]+)’ (that is, words that start with uppercase and rest with lowercase), also separating the words with Spaces.