lintcode python grammatical familiarity (132 channels)

Posted by ('(' on Mon, 03 Jan 2022 08:34:38 +0100

Write at the beginning

Just to familiarize yourself with python's basic grammar, so some solutions may be more general and refer to some good ideas, which are listed here for easy review and learning. Because time is limited, you may choose more topics in the first three grades to focus on. The difficult and super difficult topics will be looked at first.

Getting Started (119 lanes)

String 23 Channels

2401. Alphabetic transformation

Title: Given a string s consisting of only uppercase letters, change the first letter in the alphabet to the first (26 - i + 1) letter (e.g., A to Z), transform all the letters in the string, and output the transformed string to the standard output stream (console) through a print statement.

Loop traversal notation:

s=input()
lis=[]
for i in s:
    if ord(i)<=90:
        lis.append(chr(155-ord(i)))
    else:
        lis.append(chr(219-ord(i)))
print(''.join(lis))

Here, the ord built-in function is to get the corresponding encoding size, according to the difference, get the inverted characters, and finally stitch with the join method.

Familiarize yourself with the writing of join:

''.join(str(e) for e in mylist[a:b])

686. Remove extra spaces

Title: Remove extra spaces from sentences

Smart built-in method:

class Solution:
    """
    @param s: the original string
    @return: the string without arbitrary spaces
    """
    def removeExtra(self, s):
        # write your code here
        return ' '.join(s.strip().split())

Built-in methods

Correct method of cyclic output:

class Solution:
    """
    @param: : the original string
    @return: the string without arbitrary spaces
    """

    def removeExtra(self, s):
        # write your code here
        ans = ""
        i = 0
        while i < len(s):
            if s[i] == ' ':
                isntBegin = i != 0
                while i < len(s) and s[i] == ' ':
                    i += 1
                if isntBegin and i < len(s):
                    ans += ' '
            
            while  i < len(s) and s[i] != ' ':
                ans += s[i]
                i += 1
        return ans

Convert to array traversal and stitch the output with join

class Solution:
    """
    @param s: the original string
    @return: the string without arbitrary spaces
    """
    def removeExtra(self, s):
        # write your code here
        s = s.lstrip().rstrip()
        arr = s.split(' ')
        res = []
        for i in range(len(arr)):
            if arr[i].strip() != '':
                res.append(arr[i])
        return ' '.join(res)

2263. Stitching of strings

join retrospective writing

''.join(str(e) for e in mylist[a:b])
def str_join(seq: tuple) -> tuple:
    """

    :param seq: The source tuple
    :return: a tuple contain two str after jion
    """
    # write your code here
    return '-'.join(seq),''.join(seq)

2379. Link List Elements

n=int(input())
list_in = str(input())
print('-'.join(list_in.split(' ')))

Even if they are stitched with spaces, they are also typed in quotation marks in parentheses.

Another is replace function Of:

n=int(input())
list_in=input()
list_in=list_in.replace(' ','-')
print(list_in)

2907 Sum two parameters

import sys

# try to import the function plus from a_plus_b.py in the same directory
# - write your code here -
from a_plus_b import plus

# read two parameters from command like `python main.py 1 2` by sys.argv
# - write your code here -
a=int(sys.argv[1])
b=int(sys.argv[2])
# call plus function and add them up
# - write your code here -
result=plus(a,b)
# print the sum to the console
# - write your code here -
print(result)

Sys in Python. Argv

Use of argv in Python

2908. Modify the k-th character of the string

tips: variable sequence: list, dictionary, set immutable sequence: tuple, string

Operation of replace on immutable sequence

Attention to Variable and Invariant Sequences

def change_str(txt, k, s) -> str:
    # write your code here
    return txt.replace(txt[k],s)

2407. Calculate a+a a+a a a+a a a a a a values

def calculate_sum(int_1: int) -> None:
    """
    :param int_1: Input number
    :return: None
    """
    # -- write your code here --
    temp = 0
    result = 0
    n = 1
    for i in range(4):
        temp = int(str(int_1) * n)
        result += temp
        n += 1
    print(result)

Or the use of strings, the implementation of string replication, and similarly, addition implements string splicing in string operations. Note that there is no concept of self-increasing or self-decreasing in python.

See lines of code and understand

 print(sum([int(str(int_1) * i) for i in range(1,5)]))

The tests are as follows:

print(int(str(5)*i) for i in range(1,5))
print([int(str(5)*i) for i in range(1,5)])
print(sum([int(str(5)*i) for i in range(1,5)]))

The result is:

With brackets, you create a list object, as shown in the second line.

sum() sums list elements, like max and min.

The iterator object that has to be mentioned (where range () produces an iterator object), the python generator object, needs to be converted to other types of output as long as it remembers that what comes directly out of this statement is an iterator object. See in detail

In fact, this is another important manifestation of python, the reasons for various types of derivations.

2405. String replacement

def replace_string(str_1: str, str_2: str) -> None:
    '''
    :param str_1: Input string
    :param str_2: Input string
    :return: None
    '''
    # -- write your code here --
    t=str_1.replace('*','career')
    m=str_2.replace('*','career',1)
    print(t)
    print(m)

Nothing to say, as mentioned earlier, the use of three parameters for replace, which is 1, means how many times to replace

2395. Count the number of occurrences of strings

def count_string(str_1: str) -> tuple:
    '''
    :param str_1: Input string
    :return: Count the number of occurrences of a string
    '''
    # -- write your code here --
    t=str_1.count('a')
    m=str_1.count('going',0,40)
    return t, m

It's actually a simple operation on strings, and it's Common search methods In fact, relative sequences operate in the same way.

2390. Complete string judgment as required

The built-in method startwith determines who started with, and endwith is similar. Note that this is also where you can specify the beginning and end of the query.

def check_string(str_in: str) -> None:
    # Judging str_ Does in start with Nobody
    if str_in.startswith('Nobody'):
        print('str_in starts with Nobody')
    else:
        print('str_in does not start with Nobody')
    # Judging str_ Whether in starts with a with character with a subscript of 13
    if str_in.startswith('with', 13):
        print('str_in starts with the character with a subscript of 13')
    else:
        print('str_in starts with a subscript of 13 and does not begin with with')
    # Judging str_ Does the in subscript start with people in character fragments from 23 to 29
    if str_in.startswith('people', 23, 29):
        print('The str_in subscript starts with people in the character fragment from 23 to 29')
    else:
        print('str_in subscript from 23 to 29 in a character fragment that does not start with people')

Another is to use regular matching, which is not stated here.

# Judging str_ Does the in subscript start with people in character fragments from 23 to 29
    if re.match(r'\w{23}^people$', str_in):
        print('The str_in subscript starts with people in the character fragment from 23 to 29')
    else:
        print('str_in subscript from 23 to 29 in a character fragment that does not start with people')

2383. Titled string

str_in.title()

This is used directly, then add two more: upper () and lower (), which literally means it can be used to store data. When the accuracy of user input (case) cannot be guaranteed, this unified storage ensures accurate storage.

2371. Change the specified Fahrenheit temperature to Celsius

<All floating point numbers are inaccurate!!>

def temperature_conversion(float_in: float) -> float:
    """
    :param float_in: The float of first input Parameter about temperature
    :return: A new float after Fahrenheit to Celsius about temperature
    """
    # write your code here
    return round((float_in - 32) / 1.8, 1)

Used here round Is actually "rounding" in floating-point numbers, but actually takes a different approach in python3.

Another way to deal with floating-point numbers is to use integers to represent the numbers after that decimal point to achieve a more accurate purpose.

def temperature_conversion(float_in: float) -> float:
    """
    :param float_in: The float of first input Parameter about temperature
    :return: A new float after Fahrenheit to Celsius about temperature
    """
    # write your code here
    float_out = 5/9 * (float_in - 32)
    float_out = "%.1f" % float_out
    return float_out

See'5/9'in the code for details, which is expressed as a fraction, not as a floating point number after approximation.

What you haven't noticed before, The second role of%in python

2351. Stitch two strings together

This is actually mentioned earlier, using + to stitch strings.

Look at a person who listed three ways to do string splicing, and the other two are,

Using format format control

s = "{}{}".format(s1, s2)

Using lists and join s

arr = [s1, s2]
s = "".join(arr)

2330. Calculate the time after x seconds

Finally, there are time-related issues to be noted, although this is relatively simple.

I would like to reiterate that for the writing format of the input:

Using the map implementation, format control is done before, followed by strip and split

hh, mm, ss = map(int, input().strip('\n').split(':'))

There is also format control with output, a convenient representation of tuples.

My own writing is too complex to list. Here's a quotation from a select topic (no code snippets, no infringement):

Solution 1: Using divmod to achieve modulus and divide

Solving problems

Dividing 60 by ss + x gives the progress of the minute (mm). Dividing 60 by ss + x gives the answer of the final time seconds. After getting the advance of the minute (mm), assuming it is y, dividing 60 by mm + y gives the advance of the minute (hh). Dividing 60 by mm + y gives the answer of the final time minute, and doing the same for the last hour. Note that 24 is modeled for hours. The divmod function in python is also used to implement modularization and division.

source code

python

hh, mm, ss = map(int, input().strip('\n').split(':'))
x = int(input())

x, new_ss = divmod(x + ss, 60) # Modulating and dividing ss + x at the same time
x, new_mm = divmod(x + mm, 60) # divmod returns quotient and the remaining two parameters
x, new_hh = divmod(x + hh, 24)

print(f'{new_hh:0>2d}:{new_mm:0>2d}:{new_ss:0>2d}')

Solution 2: Use'//'and'%' to complete the integer division and modulus operation

Solving problems

Same as Solution, the difference is that instead of using the divmod function, integer division and modularization are done using'//'and'%'.

source code

python
hh, mm, ss = map(int, input().strip('\n').split(':'))
x = int(input())

x, new_ss = (x + ss) // 60, (x + ss) % 60  
x, new_mm = (x + mm) // 60, (x + mm) % 60
x, new_hh = (x + hh) // 24, (x + hh) % 24

print(f'{new_hh:0>2d}:{new_mm:0>2d}:{new_ss:0>2d}')

Key Points of Knowledge

1. Modulus Operation and Remainder Operation

In computer language, there is an arithmetic operator:'%'.

The% operation is a binary operation consisting of two operands, such as a\%b a%b, which is used to find the remainder of a divided by B.

Theorem: For a positive integer n n, there must be an equation n = k * p+r n = k p+r, which means n n can be split into k k p p and the next r r.

For example, 13 \%3 = 113%3 = 1 for the following reason: 13 = 4 * 3 + 113 = 4 3 + 1, that is, rr in the above theorem is the result of n \%p n%p.

In mathematics, there is a similar operation called the complement operation, which is not different from the operation on positive integers at all, but for negative integers, there are the following differences: ** kk in the remainder formula is close to 00, kk in the modulus formula is close to negative infinity (-<).

The specific differences are as follows:

Operational methodsRequest kkOperational FormulasAnswer
-13 to 3 modelling-13/3 = -4.3333, kk closes to negative infinity (-;), and -4.333 takes -5(-13) = -5 * 3 + 22
13 pairs-3 modelling13 / -3 = -4.3333, kk closes to negative infinity (-u), and -4.333 takes -513 = (-5) * (-3) - 2-2
-13 pairs-3 modelling-13 / -3 = 4.3333, kk closes to negative infinity (-u), 4.333 takes 4(-13) = 4 * (-3) - 1-1
-13 to 3-13/3 = -4.3333, kk close to 00, -4.333 take -4(-13) = (-4) * 3 - 1-1
13 pairs-3 redundancy13 / -3 = -4.3333, kk close to 00, -4.333 take -413 = (-4) * (-3) + 11
-13 pairs-3 redundancy-13/ -3 = 4.3333, kk closes to 00, 4.333 takes 4(-13) = 4 * (-3) - 1-1

Because modularization and redundancy differ on negative integers, different languages also use different methods to implement the% operation.

For example, in Python, the percent operation is modular, while in Java, the percent operation is redundant.

Example:

print(13 % 3) 
print((-13) % 3) 
print(13 % (-3)) 
print((-13) % (-3))

The above example compiles and runs as follows:

1 
2 
-2 
-1

2.divmod function

The divmod function is provided in Python to combine divisor and remainder results and return a tuple containing quotients and remainder (a // b, a% b).

Example:

a, b = divmod(9, 4) # Simultaneous calculation of 9//4 and 9%4 results
print(a, b)

x = divmod(23, 4)
print(type(x)) # Verify the return type of divmod

The above example compiles and runs as follows:

2 1
<class 'tuple'>

2324. Output string in reverse order

for loop traverses output backwards: (remember that end=''controls output not to wrap)

s = input() 
for i in range(len(s) - 1, -1, -1): 
    print(s[i], end='') 

Tile implementation-1:

print(s[::-1])

List and str are converted using the parameter reverse or reverse function in the list's built-in function sort to invert the list:

s = list(input())
s.reverse()
print(''.join(s))

2288. ascll code of string

ord() method, the return value is ascll for the character

Normally with chr(), chr() returns ascll characters, which are built-in functions.

2264. Convert case in string

def str_conversion(str_in: str) -> str:
    return str_in.swapcase()

This is the built-in method, swapcase(), that generates a new, case-to-case conversion of all letters within the string

By judgment,

def str_conversion(str_in: str) -> str:
    """
    :param str_in: The first input str
    :return: The new str after conversion str case
    """
    # write your code here
    str_out = ''
    for i in str_in:
        if i.islower():
            j = i.upper()
            str_out += j
        elif i.istitle():
            j = i.lower()
            str_out += j
        else:
            str_out += i
    return str_out

A one-letter judgment takes advantage of islower() and isupper() judgment methods. (Additionally, there is the isalnum() method, which determines whether it is all letters or numbers)

2240. Update string

def str_update(txt: str) -> str:
    return txt[7:] + " welcomes!"

2226. Determines if a specified string exists in a string

It can also be achieved with a written if-else, but there is a so-called derivation in python, in which the writing is more concise

if-else in list generation in python

print('H in str_1' if 'H' in str_1 else 'H not in str_1')
print('M in str_2' if 'M' in str_2 else 'M not in str_2')

2216. String addition, repeat output, slicing

Specifically, in the defined function, return is used as the return value of the function.

def add_repeat_slicing(str_1: str, str_2: str) -> tuple:
    """
    :param str_1: The first source string
    :param str_2: The Second source string
    :return: tuple: A tuple containing three new strings
    """
    # -- write your code here --
    return str_1+str_2,str_1*2,str_1[1:4]

2211. Judging Palindrome Number

There are many ways to solve this problem in other languages:

Similar two pointer two-way approach comparison:

Use two pointers, one pointing to the head and one pointing to the tail, and then judge if the elements pointed by the two pointers are equal. If the two pointers are equal, the head pointer adds 1 and the tail pointer subtracts 1. Continue to judge until the two pointers meet.

def is_palindrome(str_1: str) -> bool:
    '''
    :param str_1: Input a string
    :return: Whether it is a palindrome number
    '''
    m = len(str_1) # Take String Length
    i, j = 0, m - 1 # Head pointer to 0, tail pointer to m - 1
    while i < j: # while loop traversal judgment
        if str_1[i] != str_1[j]:
            return False # There is an unequal but not palindrome string, returning False
        i += 1
        j -= 1
    return True

This time, instead of using a double pointer, we use only one subscript to make a judgment by transforming the subscript into another coordinate.

def is_palindrome(str_1: str) -> bool:
    '''
    :param str_1: Input a string
    :return: Whether it is a palindrome number
    '''
    m = len(str_1) # Take String Length
    for i in range(m // 2): # for loop traversal, just need to traverse the normal length
        if str_1[i] != str_1[m - i - 1]: # The subscript corresponding to subscript i is m - i - 1
            return False
    return True

Operations that slice strings in python:

def is_palindrome(str_1: str) -> bool:
    '''
    :param str_1: Input a string
    :return: Whether it is a palindrome number
    '''
    return str_1 == str_1[::-1]

This is to use the reverse order, to write out three ways to reverse the order of the questions in the front column, which can also be obtained by direct comparison.

For some tests with or without return values, it is mainly easy for you to remember the errors:

Two methods, sort (reverse=True) and reverse (). Discovered a modification to the original list without changing the address.

a='15689'
print(list(a) == list(a).reverse())  #False
lis=list(a).reverse()
lis1=list(a).sort(reverse=True)
print(lis1)                          #None
print(lis)                           #nONE
print(list(a))                       #['1', '5', '6', '8', '9']
print(list(a)==lis)                  #False
print(list(a) == list(a)[::-1])      #False
print(list(a))                       #['1', '5', '6', '8', '9']
print(list(a)[::-1])                 #['9', '8', '6', '5', '1']
input_list = list(a)
input_list.reverse()
if input_list == list(a):            #false
    print('true')
else:
    print('false')

Note that there are two additions here:

The built-in function sorted() sorts, returns values, and does not change the original list

a=sorted(b,reverse=True)
/*
b=sorted(a)
print(b==a)                         #False
print(b)                            #['1', '5', '6', '8', '9']
c=sorted(a,reverse=True)
print(c)                            #['9', '8', '6', '5', '1']
*/

Built-in function reversed(), note that the returned iterator object is in reverse order and does not change the original sequence

2142. Replace elements in strings

Tips are interesting:

String is a common data type in Python, and when converting it to a list, you can use the characters in split() brackets as separators.

We can iterate through the elements of any sequence through a for loop, use if to make a judgment, and perform certain actions when a condition is met

for i in range(len(var_list)):
    if condition:
        do sth

List Deletion Review

Use note of remove operation in list!! There may be escapes

Honestly follow the previous exercises to see character manipulation (strip,split,replace,remove)

    var_str = var_str.strip("#")      # Remove the specified character from the beginning and end of a string
    var_list1 = var_str.split("#")      # split returns a list
    var_list2 = []
    var_list3 = []

    for i in var_list1:
        i = i.replace("_", " ")
        var_list2.append(i)

    for j in var_list1:
        j = j.replace("_", " ")
        j = j.replace("Zhuge Dan", "Zhuge Liang")
        var_list3.append(j)

    print(var_list2)
    print(var_list3)

The deduction is still not written. When you see the deduction in other people's problems, you suddenly get an idea and sharpen it:

def solution(var_str):
    print([i for i in var_str.replace('_',' ').split('#') if i != ''])
    print([i for i in var_str.replace('Zhuge_Dan','Zhuge Liang').replace('_',' ').split('#') if i != ''])

2139.print format outputs course information

Only one thing to note is that after 3.6 there is an f string ( Detailed f-string explanations in links and even the use of specific descriptors for format control ) appears, acts like format! (It's clear in the 2137 tip below)

print(f"course_name:{course_name},number:{number}")

2137. Print out SMS verification code

The hint is clear:

Prit is Python's most basic way of learning a language, and it may be the first way we come across it

When outputting a string, sometimes we can use the format method to output variables together

var = 
f"var is {var}"
"var is {}".format(var)
"var is {v}".format(v=var)

The questions are:

print(f"Hello, {name}! Your validation code is {SMS_verification_code}, please keep it in secret.")

In 2022/1/2 1:11

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

Simple (10 channels)

Medium (6 lanes)

Difficulty (1)

Super Hard (1)

Topics: Python Algorithm