“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”

This series of columns was created to get the Python feel right, and you can use it to learn Python as well, because it’s difficult to jump over, so it’s best to start with the Snowball series.

Learn a little each day, so each column in this series should be no more than 3000 words (including code)

Write to write to discover, these may be interview questions ~

Binary search

Problem scenario Looking for a subscript of a target number in an ascending array (essentially a list of integers) does not return -1.

Because the array is in ascending order, so binary search can be landed first take out the array in the middle value, compare the size with the target number, determine half of the range and then repeat the above steps to constantly narrow the range.

Code is as follows

def search(nums, start, end, target) :
    if start > end:
        return -1

    Get the median value
    mid = (start + end) // 2
    # compare the size of the middle value with the target number
    if nums[mid] > target:  # The median is greater than the target data, and the number of targets is on the left
        return search(nums, start, mid, target)
    if nums[mid] == target:  # median equals target data, return
        return mid
    if nums[mid] < target:  # The median is less than the target data, and the number of targets is on the right
        return search(nums, mid, end, target)

if __name__ == '__main__':
    ret = search([1.2.3.4].0.4.1)
    print(ret)
Copy the code

String template

Problem scenario + concatenating strings makes code hard to read. Is there another way to format strings?

Python strings allow placeholders to appear and then be replaced with specific code.

Code is as follows

import string

tp1 = string.Template('You are reading $name's blog')
tp2 = string.Template('You are reading ${name} blog')

s1 = tp1.substitute(name=eraser)
s2 = tp2.substitute(name=eraser)
print(s1)
print(s2)
Copy the code

$is the special symbol at the beginning of the placeholder. If the string itself has a $sign, use $$instead. String templates use the Template class in the String module, and replacing strings requires calling the object’s substitute() method. It is important to note that the Python compiler does not throw an error if the number of arguments in the substitute() method does not match those in the template.

Import string tp1 = string.Template(' you are reading $name's blog ') s1 = tp1. Substitute (name=" erectile ", age=18)Copy the code

Conversely, if a placeholder exists in the string template but is not provided in the substitute() method, an exception is thrown.

import string

tp1 = string.Template('You are reading $name's blog')
tp2 = string.Template('You are reading ${name}$age blog')

s1 = tp1.substitute(name=eraser, age=18)  If the parameter is not consistent, there will be no error
s2 = tp2.substitute(name=eraser)  # But this does go wrong

s3 = tp2.safe_substitute(name=eraser)
print(s1)
print(s2)
print(s3)
Copy the code

The solution is to use another safe_substitute() method provided in the string template class, coded as follows

import string

tp1 = string.Template('You are reading $name's blog')
tp2 = string.Template('You are reading ${name}$age blog')
Substitute (name=" eraser ") # s2 = tp2

s3 = tp2.safe_substitute(name=eraser) No error will be reported
# print(s2)
print(s3)
Copy the code

Textwrap module

Problem scenario Python allows for more detailed manipulation of text, or strings, such as wrapping lines and padding characters.

Use the Textwrap module to perform operations. Start by using the help() function to see what classes and methods the module has.

The module has the class TextWrapper(builtins.object), with the following methods:

  • dedent(text): Removes any whitespace of the same prefix from each line of text;
  • fill(text, width=70, **kwargs)Wrap a single paragraph in text and return a single string containing the wrapped paragraph,fill()wrap()The method is similar, the segmentation result is the same, but the return result form is different, its function is to add between the segmented fragments\n, and then turn it back into a text for output;
  • indent(text, prefix, predicate=None): adds prefix to the beginning of the selected line in text;
  • shorten(text, width, **kwargs): intercepts the character given width in text;
  • wrap(text, width=70, **kwargs): Wraps individual paragraphs (strings) in text, each line is at mostwidthIt’s a character long. Returns a list of output lines without a final newline character.

Textwrap.wrap ()

import textwrap
text = "Hello, I'm an eraser and this is day two of Python."
result = textwrap.wrap(text,10)
print(result)
Copy the code

The following output is displayed:

textwrap.fill()

import textwrap
text = "Hello, I'm an eraser and this is day two of Python."
result = textwrap.fill(text,10)
print(result)
Copy the code

Textwrap.dedent (text) This method removes unwanted prefix whitespace. You can use a triple quoted string to align with the left edge of the display, while still appearing indented in source code.

import textwrap
text = "Hi, I'm eraser and this is your Python blog."
print(text)

print("*"*100)

print(textwrap.dedent(text))
Copy the code

The running results are as follows:

textwrap.indent()

import textwrap
sample_text = "Hello, I'm an eraser and this is my blog writing all about Python and hoping to get your attention."
dedented_text = textwrap.dedent(sample_text)

final = textwrap.indent(dedented_text, '>')

print(final)
Copy the code

The running results are as follows:

The rest can be found in the official manual.

Count phrases according to the space

Question scenario Count the number of phrases in a paragraph such as “I’m an eraser and this is your Python blog”.

The preceding character is a space.

Code is as follows

class Ca:
    def phrase_count(self, p) :
        c = 0 # count
        for i in range(len(p)):
            # If the current character is not a space and is not the first character or the preceding character is not a space
            ifp[i] ! =' ' and (i == 0 or p[i - 1] = =' ') :# 1
                c += 1

        return c

if __name__ == '__main__':
    c = Ca()
    p = 'I'm an eraser and this is your Python blog'
    print(F "the number of phrases is:{c.phrase_count(p)}")
Copy the code

Populate the string with “0”

The problem scenario prefixes the string with placeholder 0.

Zfill () returns a string of the specified length, aligned to the right and preceded by 0

Encoding time

str = "Eraser blog."

print(str.zfill(20))
print(str.zfill(30))
Copy the code

Recording time

2022 Flag, 560/1024 articles written. You can follow me, like me, comment on me, favorites me.