Python problem sets

Time:2021-4-11

Find all prime numbers within one million

The first method

thinking: if the current number is I, then all the numbers smaller than int (sqrt (I)) + 1 can not be divisible. If yes, they are prime numbers

theory: if we traverse all divisor J smaller than I and if J > int (sqrt (I)), if J can round I, then there must be a number less than int (sqrt (I)) that can round I, so we only need to traverse the number within int (sqrt (I)) + 1

code

cnt = 0
for i in range(2,1000000):
    for j in range(2, int(i ** 0.5) + 1):
        if i % j == 0:
            break
    else:
       cnt += 1 
print(cnt)

The output is as follows

78498

The second method

theory

  • If an integer is a composite number, there must be a prime less than it as its factor. For example, 9 is a composite number, and the prime number 3 is a factor of it.
  • If we know all prime numbers less than a number, we only need to determine whether the number can be divided by these prime numbers. If it cannot be divisible, then the number must be a prime. On the contrary, it is not.
  • That is to say, when we get a prime number, we can mark all its multiples as non prime numbers, so when we traverse a number, it is not marked as non prime by any prime number less than it, then we can determine that the number is a prime number.
  • For example, starting from 2, 2 is prime at initialization. 3 is similar. When traversing to 4, 4 has been marked by Prime 2. Skip directly

thinking

  • Initialize a list in a large range. At the beginning, all numbers are prime numbers. When traversing, mark all non prime numbers according to the above theory

code

cnt = 0
is_prime = [True]*1000000
is_prime[0] = False
is_prime[1] = False
for i in range(2, 1000000):
    if is_prime[i] is False:
        continue
    cnt += 1
    k = i
    while k * i < 1000000:
        is_prime[k * i] = False
        k += 1
print(cnt)

Output results

78498

<!–more–>

Print 99 multiplication table

thinking: each inner loop J only needs to loop to the outer loop I

code

#!/usr/bin/env python 
#coding=utf-8

def multiplicationTable():
    for i in range(1,10):
        for j in range(1,i+1):
            r=i*j
            print("%d*%d=%-3d"%(i,j,r),sep='',end=' ')
        print('\n')
if __name__=='__main__':
    multiplicationTable()

The output is as follows

1*1=1   

2*1=2   2*2=4   

3*1=3   3*2=6   3*3=9   

4*1=4   4*2=8   4*3=12  4*4=16  

5*1=5   5*2=10  5*3=15  5*4=20  5*5=25  

6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36  

7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49  

8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64  

9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81  

Finding the nth term of geometric series

thinking

  • The form of geometric series is:a+a*q+a*q^2+a*q^3+...+a*q^n
  • A, Q, n are required

code

# !/user/bin/env python
# coding = utf-8

A = int (input ('Please input a: ') of geometric series)
Q = int (input ('Please input Q: ') of geometric series)
N = int (input ('Please input n: ') of geometric series)
sum=0
for i in range(0,n+1):
    sum += a * q  ** i
print(sum)

The input and output results are as follows

Please input a: 3 of geometric series
Please input Q: 2 of geometric series
Please input n: 4 of geometric series
93

Finding the 101st digit of Fibonacci sequence

Write the recursive formula first and then write the implementation. The recursive formula is as follows

thinking

  • FIB [0] = 1 when I = 0
  • FIB [1] = 1 when I = 1
  • FIB [i] = FIB [I-1] + FIB [I-2] when I > 1
  • The 101st bit of FIB is FIB [100] = FIB [99] + FIB [98]

code

a = 0
b = 0
for i in range(0,101):
    if i == 0:
        a = 1
    elif i ==1:
        b = 1
    else:
        c = a + b
        a = b
        b = c
print(b)

The output is as follows

573147844013817084101

Finding the value of the nth row and the kth column of Yang Hui triangle

#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/26/17 5:03 PM
@author: Flowsnow
@file: YangHuiTriangle.py
@Function: find the value of the nth row and the kth column of Yang Hui triangle
"""


def yang_hui_triangle(n, k):
    lst = []
    for i in range(n+1):
        row = [1]
        lst.append(row)
        if i == 0:
            continue
        for j in range(1, i):
            row.append(lst[i-1][j-1] + lst[i-1][j])
        row.append(1)
    print(lst[n][k])


if __name__ == '__main__':
    yang_hui_triangle(6, 4)

String to numeric

Description: the string form of integer or floating-point number into int or float, do not use int and float functions

#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/26/17 5:52 PM
@author: Flowsnow
@file: str2num.py 
@Function: convert the integer or floating point number in the form of string to int or float without using int and float functions
"""


def str2num(s: str):
    mapping = {str(x): x for x in range(10)}
    i, _, f = s.partition('.')
    # print(i, f)
    ret = 0
    for idx, x in enumerate((i+f)[::-1]):
        ret += mapping[x] * 10 ** idx
    return ret / 10 ** len(f)

if __name__ == '__main__':
    s = '1230.0541640'
    print(str2num(s))

Remove duplicate elements from a list and keep the list in its original order

#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/26/17 6:30 PM
@author: Flowsnow
@file: rm_elements.py 
@Function: remove duplicate elements from a list and keep the list in its original order
"""

def remove_elements(lst: str):
    ret = []
    for x in lst:
        if x not in ret:
            ret.append(x)
    return ret

if __name__ == '__main__':
    lst = [1, 2, 4, 5, 2, 3, 1, 2, 6, 7, 8, 3, 2, 3, 4]
    print(remove_elements(lst))

Flat dictionary

For example:

  • After {a ‘: {B’: 1} flattening, it is {A.B ‘: 1}
  • After {a ‘: {B’: {C ‘: 1,’d’: 2},’x ‘: 2} flattening, it is {a.x’: 2, ‘A.B.C’: 1, ‘a.b.d’: 2}

Characteristics of initial dictionary

  • Every key in a dictionary is hashable, so it won’t be a dictionary
  • The initial dictionary is not empty
  • The value depth of the dictionary can be infinitely nested

thinking: using recursion, the recursion depth will change every time, that is to say, the path will change. You can use a path variable to record the path

  1. If the nested V is not a dictionary, add a new element directly: desict [‘{}. {}’. Format (path, K). Lstrip (‘)] = v
  2. If the nested V is an empty dictionary, it is directly replaced by an empty string: dedict [‘{}. {}’. Format (path, K). Lstrip (‘)] =’ “
  3. If the nested V is not an empty dictionary, the path is directly increased, and V is recursed next time: flatten_ dict(v, desDict, path)
  4. Each recursive return indicates that the current depth dictionary has been traversed and the path needs to be shortened
  5. Rstrip functions are not modified in situ, and all returned are copies

Determine whether the variable is a dictionary

  • type()
  • isInstance()

code

#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/26/17 8:26 PM
@author: Flowsnow
@file: flatten_dict.py 
@Function: flattening dictionary
"""


def flatten_dict(srcDict: dict, desDict: dict,  path: str):
    for k, v in srcDict.items():
        if not isinstance(v, dict):
            desDict['{}.{}'.format(path, k).lstrip('.')] = v
        else:
            if v == {}:
                desDict['{}.{}'.format(path, k).lstrip('.')] = ''
            else:
                path = '{}.{}'.format(path, k).lstrip('.')
                flatten_dict(v, desDict, path)
                path = path.rstrip('.{}'.format(k))


if __name__ == '__main__':
    srcDict = {'a': {'b': {'c': 1, 'd': 2}, 'x': 2}}
    # srcDict = {'a': {'b': 1}}
    desDict = {}
    flatten_dict(srcDict, desDict, '')
    print(desDict)

Implementation of Base64 encoding and decoding algorithm

The idea of Base64 coding

  • The data is recoded with 64 basic ASCII characters. It splits the data to be encoded into byte arrays. In groups of 3 bytes. Arrange the 24 bit data in order, and then divide the 24 bit data into 4 groups, that is, 6 bits in each group. Then fill two zeros in front of the highest bit of each group to make up one byte. In this way, a 3-byte group of data is re encoded into 4 bytes. When the number of bytes of the data to be encoded is not an integral multiple of 3, that is to say, the last group is less than 3 bytes. At this time, the last group is filled with 1 to 2 0 bytes. And add 1 to 2 “=” at the end after the final encoding.

Base64 encoding example: ABC will be Base64 encoded

  1. First, take the ASCII value corresponding to ABC. A(65)B(66)C(67);
  2. Then take the binary value a (01000001) B (01000010) C (01000011);
  3. Then connect the three byte binary codes (0100000100000101000011);
  4. Then, it is divided into four data blocks with 6 bits as a unit, and the highest bit is filled with two zeros to form the encoded value of four bytes, (00010000) (00010100) (00001001) (00000011)
  5. Then convert the four bytes of data into a decimal number to get (16) (20) (9) (3);
  6. Finally, according to the 64 basic character table given by Base64, find out the corresponding ASCII characters (q) (U) (J) (d). The value here is actually the index of the data in the character table.

Base64 character table: up to six bytes, so the maximum range is 0-63, so a total of 64 characters

  • ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

Conversion between character and ASCII code: single character

  • Convert ord character to ASCII
  • Chr ASCII to character

Conversion between string and ASCII code: String

  • map(ord, “a test String: 123456”)

Encryption examples

  • CBdaF3FVThe result of coding isQ0JkYUYzRlY=
  • CBdaF34FVThe result of coding isQ0JkYUYzNEZW
  • CdaF3FVThe result of coding isQ2RhRjNGVg==
  • ABCThe result of coding isQUJD

effect

  • Mainly used to convert binary to string

Code 1: handle as string

#Base64 encoding
def base64Encode(s):
    base64StrList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    ret = ''
    bList = list(map(ord, s))
    bStr = ''
    #print(bList)
    for x in bList:
        tmpS = str(bin(x))
        bStr += '0' * (10 - len(tmpS)) + tmpS.lstrip('0b')
    print(bStr)
    i = 0
    while i + 6 < len(bStr):
        tmpX = bStr[i: i+6]
        #print(tmpX)
        ret += base64StrList[int(tmpX, 2)]
        i += 6
    rest = bStr[i:]
    if len(rest) == 2:
        ret += base64StrList[int(rest + '0000', 2)]
        ret += '=='
    elif len(rest) == 4:
        ret += base64StrList[int(rest + '00', 2)]
        ret += '='
    else:
        RET + = base64strlist [int (rest, 2)] # a complete 6 bits is left after the while part is processed
    print(ret)


#Base64 decoding
def base64Decode(s):
    base64StrList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    bStr = ''
    ret = ''
    for x in s:
        if x == '=':
            continue
        i = base64StrList.find(x)
        s1 = str(bin(i))
        bStr += '0'*(10-len(s1)-2) + s1.lstrip('0b')

    cnt = s.count('=')
    bStr = bStr[: -2 * cnt + len(bStr)]

    i = 0
    while i < len(bStr):
        b = bStr[i: i + 8]
        ret += chr(int(bStr[i: i + 8], 2))
        i += 8

    print(ret)

Code 2: treat as byte array

Advantages: byte array + bit operation, improve processing speed, reduce memory occupation.

#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/26/17 9:11 PM
@author: Flowsnow
@file: base64.py 
@Function: implementation of Base64 encoding and decoding algorithm: byte array + bit operation
"""


#Base64 encoding
def b64encode(data: bytes) -> str:
    table = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    encoded = bytearray()
    c = 0
    for x in range(3, len(data)+1, 3):
        i = int.from_bytes(data[c: x], 'big')   # bytes to int
        for j in range(1, 5):
            encoded.append(table[i >> (24 - j*6) & 0x3f])
        c += 3
    r = len(data) - c
    if r > 0:
        i = int.from_bytes(data[c:], 'big') << (3-r) * 8
        for j in range(1, 5-(3-r)):
            encoded.append(table[i >> (24 - j*6) & 0x3f])
        for _ in range(3-r):
            encoded.append(int.from_bytes(b'=', 'big'))
    return encoded.decode()


#Base64 decoding
def b64decode(data:str) -> bytes:
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    decoded = bytearray()
    s = 0
    for e in range(4, len(data)+1, 4):
        tmp = 0
        for i, c in enumerate(data[s:e]):
            if c != '=':
                tmp += table.index(c) << 24 - (i+1) * 6
            else:
                tmp += 0 << 24 - (i+1) * 6
        decoded.extend(tmp.to_bytes(3, 'big'))
        s += 4
    return bytes(decoded.rstrip(b'\x00'))


if __name__ == '__main__':
    print(b64encode(b'abc'))
    print(b64decode('YWJj'))

Implementation counter, you can specify the cardinality and step size

The use of generator and anonymous function

#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/27/17 9:30 AM
@author: Flowsnow
@file: make_inc.py 
@Function: implement counter, you can specify base and step size
"""


def make_inc(base, step):
    def counter():
        nonlocal base
        nonlocal step
        x = base
        while True:
            x += step
            yield x
    c = counter()
    return lambda : next(c)

if __name__ == '__main__':
    #The function of Inc encapsulates a generator C and executes next (c) every time Inc is called
    inc = make_inc(2, 3)
    print(inc())
    print(inc())
    print(inc())
    print(inc())

Finds the longest common substring of two strings

  • Violence method: find out all the substrings of two strings, and then compare them one by one to update the longest value
  • Dynamic planning:

    1. The two strings are S1 and S2
    2. S1 [i] and S2 [J] denote the I and j th characters respectively (character order starts from 0)
    3. Let l [I, J] denote the maximum length of the same substring ending in S1 [i] and S2 [J].
    4. L [I, J] = l [I-1, J-1] + 1 if S1 [i] = = S2 [J]
    5. L [I, J] = 0 if S1 [i]! = S2 [J]
#!/usr/bin/env python  
# encoding: utf-8  

"""
Created on 2/27/17 9:48 AM
@author: Flowsnow
@file: longest_common_substring.py 
@function: 
"""


def longest_common_substring(s1: str,s2:str):
    s = ''
    dp = []
    Maxl = 0 # the longest length of the record substring
    Maxi = 0 # record the longest subscript of the substring
    for i, x in enumerate(s1):
        dp.append([])
        for j, y in enumerate(s2):
            if x == y:
                if i > 0 and j > 0:
                    dp[i].append(dp[i - 1][j - 1] + 1)
                else:
                    dp[i].append(1)
                if dp[i][j] > maxL:
                    maxI = i
                    maxL = dp[i][j]
            else:
                dp[i].append(0)
    S = S1 [Maxi + 1 - maxl: Maxi + 1] # Maxi is the subscript
    for i in dp:
        print(i)
    return s
if __name__ == '__main__':
    s1 = 'I-love-Python'
    s2 = 'snow-love-other'
    s = longest_common_substring(s1, s2)
    print(s)

Output results

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
'-love-'

Implement command distributor

Implementation function can take any parameters (except variable parameters), parsing parameters and require user input

Implement LS command

Implement the – L – A – H option

Implementation of find command

Implement – name – type – CTime – Mtime – cnewer – executable – newer – GID – uid test

Implement CP command

Implement the – R – P option

Implementation of LinkedList

Function implementation

Class implementation

Implement priority queue

Function implementation

Class implementation

Implementation dictionary

Function implementation

Class implementation


Remember to praise me!

We have carefully arranged video courses and e-books from entry-level, advanced and practical in all directions of computer. We can always find the learning materials you need according to the reasonable classification of the catalogue. What are you waiting for? Pay attention to download it!!!

Python problem sets

If you don’t forget, there will be an echo. Please give me a compliment. Thank you very much.

I am a bright brother in the workplace, YY Senior Software Engineer, with four years of working experience. I refuse to be a leading slash programmer.

Listen to me, more progress, a shuttle of procedural life

If you are lucky enough to help you, please give me a “like” to pay attention to it. If you can comment on it and give me encouragement, I will be very grateful.

List of articles of workplace bright brother:More articles

Python problem sets

All my articles and answers have cooperation with the copyright protection platform. The copyright belongs to brother Liang in the workplace. Without authorization, reprint must be investigated!

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]