python basic 60 training questions

1. Merge dictionary: a1.update(a2)

2. List de-duplication: a= [11,22,33,44,11,22] print (list (set(a))

3. Distinction of range(100) between Python 2 and python 3

python 2 returns the list, python 3 returns the iterator, saving memory

4. List [1, 2, 3, 4, 5]. Please use map() function to output (1, 4, 9, 16, 25), and use list derivation to extract genera greater than 10, and finally output [16, 25]

a = [1,2,3,4,5]
b=map(lambda x:x*x,a)
res=[i for i in b if i >10]

5. python randomly generates integers, random decimals, decimals between 0 and 1

import random
import numpy
import string

res1=random.randint(1,100)#Random integer

res2=numpy.random.randn(8)#8 random decimal numbers

res3=random.random()#Decimal between 0 and 1

res4= random.sample(range(1,100),9) #Random Generation of 9 Non-repetitive Integers between 1-100

res5=numpy.random.choice(range(1000),9,replace=False) #Random generation of nine non-repetitive integers between 1 and 1000 is much more efficient than random.sample when the number of integers to be generated is large.

for i in range(10): #Random generation of 10 non-repetitive strings with length of 8
	str_list=random.sample(string.digits + string.ascii_letters,8)

6. <div class='nam'> country </div> matches the contents of the label ("country") regularly, in which the type of class is uncertain.

import re
res=re.findall(r'<div class=".*">(.*?)</div>',str)
print(res)#Returns a list of ['countries']

re.match('',str) #Match only the beginning of the string,. span () prints the matched index, and group(1) prints the matched value.'',str) #Match the entire string, the rest with match

7. Data table student has id,name,score,city fields, in which the name can be repeated, need to eliminate duplicate rows, sql statements;

select distinct name from student

8. s = ajldjlajfdljfddd, and output "adfjl" from small to large order

s = "ajldjlajfdljfddd"
s.sort() #Sort sorts sort lists only
print("".join(s)) #Lists are merged into strings
s = "-+abacsdadjhfjab="
print(s.strip()) #Delete empty characters on the left and right sides of a string
print(s.strip('-=+')) #Delete the - += sign on the left and right sides of the string

new_s=s[:2]+s[3:] #Delete a single fixed position character: slice + splice

res1=s.replace('ab',"") #Delete any position character, ab, which can be used to delete strings
print(res1) #acsdadjhfj

res=s.translate(str.maketrans('','','ab')) #Delete many different characters a and b at the same time
print(res) #The third parameter is to replace the parameter directly with None.

#The first parameter is a string of characters to be replaced, and the second parameter is a mapping, i.e. replacing a with 1 and b with 2.

9. Multiplication of Two Numbers by lambda Function

multipy=lambda x,y:x*y

10. Dictionaries are sorted by keys from small to large

import collections
dict = {"name":"watermelon","age":18,"city":"shenzhen","tel":12345}
s=sorted(dict.items(),key=lambda x: x[0])#dicts.items() returns a list of nested dictionaries whose key-value pairs of tuples x[0] are sorted by key and x[1] by value.
new_dic=collections.OrderedDict()   #Create ordered dictionaries to keep the order after sorting
for i in s:    

#Method 2. Deduction formula with zip + dictionary
dict = {"name":"zs","sex":"man", "city":"bj"}
foo=zip(dict.keys(),dict.values()) #Dictionary list nested tuples or dict.items()

b=sorted(foo,key=lambda x:x[0])
print(b)#[('city', 'bj'), ('name', 'zs'), ('sex', 'man')]

new_dict={i[0]:i[1] for i in b} #Dictionary Derivative Construction of New Dictionary
print(new_dict) #{'city': 'bj', 'name': 'zs', 'sex': 'man'}

11. Use the Count method of collections library to count the number of occurrences of each word in a string

from collections import  Counter
a = "kjalfj;ldsjsfl;hdsllfdhg;lahfbl;hl;ahlf;h"
res=Counter(a) #Return print(res) from large to small in key-to-value pairs

12. String a = not 404 found s Zhang San99 Shenzhen. Each word is blank in the middle. Use regular filter to filter out English and numbers, and eventually output "Zhang Sanshen".

import re
a = "not 404 found Zhang San99 Shenzhen"
list_a=a.split(" ") #For string slicing, split divides num+1 substring A. split (", 3) if num parameter is followed.
s=re.findall(r"\d+|[a-zA-Z]+",a) #\d Matched digits[0-9],+Match the previous expression one or more times.|Connect multiple matching modes#s returns a list of matched English and numbers
res=[i for i in list_a if i not in s]  #Filter out the list of Chinese characters
print(" ".join(res)) 

13. The filter method finds all odd numbers in the list and constructs a new list, a = 1,2,3,4,5,6,7,8,9,10

# The filter() function is used to filter sequences, filter out unqualified elements, and return a new list of qualified elements.
# Receive two parameters, the first is a function and the second is a sequence.
a = [1,2,3,4,5,6,7,8,9,10]
def f(a):    
    return a%2==1 #Screen out odd numbers
new_list=filter(f,a) #Returning is the decorator.
print([i for i in new_list])

#Method Two List Generation Formula
new_list1=[i for i in a if i%2==1]

14. List Adding Elements

a = [1,2,3,4,5,6,7,8,9,10]
a.append(11) #End Added
a.insert(3,11)#z Specified Location Index adds 11 at 3
a.extend([12,13]) #End Added List  
c=a+b #Additional attention at the end is not additive, but equivalent to extend.

15. Method of deleting files with python and linux commands

import os
import shutil
os.remove(root_dir+'/') #Delete files in directories os.rmdir(path)#Delete empty directory files

shutil.rmtree(path) #Delete empty directories or directories containing files or subdirectories
print('After directory deletion:%s'%os.listdir(root_dir))

rm -rf /var/log/ #Delete all files and folders under / var/log /.
rm -rf /var/log/access.log  #Delete access.log file

16. In log log log, we need to record the occurrence time of error, warning and so on with timestamp. Please print the current timestamp "2018-04-01 11:38:54" with datetime module.

import datetime
print('%Y-%m-%d %H:%M:%S') + ' Weekly:'+str(

17. How many times each element appears in the statistical list, and extract the element with the most repetitions, or sort the elements according to the number of repetitions of the elements

from collections import  Counter
print(counter_obj) # Counter({'test': 3, 'hello': 2, 'world': 1})
most= counter_obj.most_common() #Returns all elements without passing parameters# [('test', 3), ('hello', 2)]
print(counter_obj.most_common(2)) #stay lst1 The first two elements that appear most frequently are arranged in descending order.# [('test', 3), ('hello', 2), ('world', 1)]
#Arrange in ascending order according to element size
most.sort(key=lambda x:x[0]) #Sort by key
most.sort(key=lambda x:x[1],reverse=True) #In descending order of occurrence

18, [1, 2], [3, 4], [5, 6] expand the list and get [1, 2, 3, 4, 5, 6]

#List Generator
x=[j for i in a for j in i]
print(x) #[1,2,3,4,5,6]
#The list can also be converted into a numpy matrix, and the matrix can be folded into a one-dimensional array by the flatten() method of numpy.
import numpy as np

19. What is the difference between (. *) and (. *?) matching in regular expression matching?

(. *) is a greedy match that matches as many backwards as possible to satisfy the regularity
 (*? ) Non-greedy matching will match as little as possible that satisfies the regularity
s = '<a>Ha-ha</a><a>Ha-ha</a>'
import re
res1=re.findall('<a>(.*)</a>',s) #Greedy Matching
print(res1) # ['Haha </a > < a > Haha']

res2=re.findall('<a>(.*?)</a>',s) #Non-greedy matching
print(res2) #['Haha','Haha']

20, x= "abc", "y="def","z=["de", "de", "f"] respectively, the return results of x.join(y) and x.join(z) are obtained.

# In join() parentheses, the iteratable object is inserted into the middle of the iteratable object to form a string.
print(x.join(y)) #dabceabcf
print(x.join(z)) #deabcdeabcf

21. Illustrate the significance of try except other final in exception module with examples

try...else does not catch an exception and executes the else statement
 try...finally executes the final statement whether or not an exception is caught
    content=input('Please enter 1-100 Inner integer')    
    if not isinstance(int(content),int) or int(content)>100:        
        raise Exception("Input is not an integer or a value greater than 100")  #Custom throw exception
except Exception as e:    
    print("Input error:%s" %e)
    print("Correct input")

22. Exchange the values of two numbers in python:

#Method 2

23. Illustrate the usage of zip() function with examples

# When the zip() function runs, it takes one or more sequences (iteratable objects) as parameters and returns a list of meta-ancestors. At the same time, the elements in these sequences are paired side by side.
# zip() parameter can accept any type of sequence, but also can have more than two parameters; when the length of the parameters is different, zip can automatically intercept the shortest sequence length, and obtain the primitive ancestor.
res1=[i for i in zip(a,b)]
print(res1) #[(1, 3), (2, 4)]

res2=[i for i in zip(a,b)]
print(res2) #[(1, 3), (2, 4)]

res3=[i for i in zip(a,b)]
print(res3) #[('a', 'x'), ('b', 'y')]

#Create a dictionary:
print(dict(a))  #{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

dic={k:random.randint(4,9) for k in ["a",'b','c','d']} #Dictionary Derivation
print(dict) ##{'a': 4, 'b': 8, 'c': 6, 'd': 5}

#Find the longest common prefix for list elements
sub_str=[i for i in zip(*lst)] #* lst is unpacking and returns flower flow float flat
for x in sub_str:
    if len(set(x))==1:

24, a = Zhang Ming 98, replacing 98 with 100

a = "Zhang Ming 98" #replace function of string
print(res1)#Zhang Ming's 100 points

import re #Use regular expressions
print(res2)#Zhang Ming's 100 points

25. Write 5 Common sql Statements

show databases;
show tables;
select * from Table name;
delete from Table name where id=5;
update student set gender=0,homework="OK" where id=6;

26. Brief description of the difference between mysql and redis

# redis: Memory-based non-relational database, data stored in memory, fast
 # mysql: relational database, data stored on disk, retrieval, there will be some IO operations, access speed is relatively slow

27. How to deal with bug s

# 1. Errors in details can be executed to print() by printing (), which indicates that there is no problem with the above code and whether there is a problem with the piecewise detection program; if it is js, aler or console.log can be used.

# 2. If some third-party frameworks are involved, they will check official documents or some technical blogs.

# 3. To summarize the management and classification of bugs, general tests record the tested bugs with teambin and other bug management tools (vsts, testlink use cases), and then revise them one by one. The process of modification is also a way to understand the business logic and improve their logic meticulousness. I will collect some notes and records.# 

4. Guide problem, display error caused by multi-tone words in city location

28. Regular Matching, Matching Date 2018-03-20#

url = ''
import re

29, list = [2,3,5,4,9,6], sort from small to large, no sort, output [2, 3, 4, 5, 6, 9] (sort and quick sort)

list = [2,3,5,4,9,6]
print(b) #[2, 3, 4, 5, 6, 9]

def quickSort(list):    
    if len(list)<2:        
        return list    
        greater=[i for i in list[1:] if i >basevalue]        
        equal=[i for i in list if i == basevalue]        
        less=[i for i in list[1:] if i < basevalue]    
    return quickSort(less)+equal+quickSort(greater)print(quickSort(list))

print(quickSort(list)) #[2, 3, 4, 5, 6, 9]

30. Use min() method to get the minimum value, delete the minimum value from the original list, add the minimum value to the new list, recursively call the function to get the minimum value, and repeatedly operate.

list = [2,3,5,4,9,6]
def get_min(list):    
    if len(list)>0:        
    return new_list

print(new_list1) #[2, 3, 4, 5, 6, 9]
print(list) #[]

31. Keep two decimal places

print(a,type(a)) # 1.33 <class 'str'>

b=round(float(a),1) # Returns the rounded value of the floating point number, leaving a decimal number.
print(b,type(b))#1.3 <class 'float'>

Note: Floating point arithmetic is inaccurate and can only be estimated. Actuarial calculation is multiplied by 1W, then divided by 1W.

32. Find three ways to print results

def fn(k,v,dict={}):    
fn('one',1) #{'one': 1} Direct i passes key-value pairs to the dictionary
fn('two',2) #{one': 1,'two': 2} Because dictionaries are variable data types in memory, pointing to the same address and passing new parameters would be equivalent to adding key-value pairs to dictionaries.
fn('three',3,{}) #{'three': 3} Because a new dictionary was passed, all dictionaries were no longer the default parameters.

33. List common HTTP status codes and their significance

200:  OK
 204: No Content request was successfully processed and no entity returned
 301: Permanent mobile, resources have been permanently allocated new uri
 302: Temporary Mobility
304: not modified
 400: Request message grammar error or parameter error
 401: Unauthorized current request requires user authentication or authentication failure
 403: Forbidden server understands the request, but refuses to execute. Note the difference from 401: Authentication does not provide any help and requests are not submitted repeatedly.
404: The request failed, not found
 500: Server failure or web application failure
 503: Server Overload or Outage Maintenance

34. Describe the performance optimization of web project from front-end, back-end and database respectively.

Front-end optimization:
1. Reduce http requests, such as making wizard maps
 2. HTml and css are placed at the top of the page, while javascript is placed at the bottom of the page. Because js load is slower than HTML and css load, it is necessary to load HTML and css first in order to prevent page display being incomplete, performance being poor and user experience being affected.

Backend optimization:
1. Cache stores data with high read-write times and little change, such as information on the home page of the website, information on goods, etc. When an application reads data, it usually reads from the cache first. If it cannot read or the data is invalid, it accesses the disk database and writes the data to the cache again. redis
 2. Asynchronous mode, if there are time-consuming operations, can be used asynchronous, such as MQ
 3. Code optimization to avoid too many iterations and judgments. If multiple if else judgments are made, priority judgments are most likely to occur first.

Database optimization: 1. If conditions permit, data can be stored in redis and read quickly.
2. Indexing, foreign keys, etc.

35. Use pop and del to delete the "name" field in the dictionary. dic={"name": "zs", "age": 18}

dict = {"name": "zs", "age": 18}
del dict['name']

36. dict () New Method of Creating Dictionary

s=dict([['name','zs'],['age',18]])#List Nested List
print(s) # {'name': 'zs', 'age': 18}

s1=dict([('name','zs'),('age',18)]) #List nested tuples
print(s1)#{'name': 'zs', 'age': 18}

A=zip(('a','b','c','d','e'),(1,2,3,4,5)) #zip creates Dictionaries
A0=dict(A)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

A2=[i for i in A1 if i in A0] #[] The bond abcde of A0 is not in range(10)
A3=[A0[s] for s in A0] #Returns the value of the dictionary [1, 2, 3, 4, 5]

37. A Brief Introduction to Homologous Strategies

Need to be satisfied at the same time:
1. The same protocol (http and https are different)
2. Domain names are identical
 3. Same port

38. Brief description of the difference between cookie and session

1. session is on the server side and cookie is on the client side.
2. Session runs on session id, session runs on session id, and session ID exists in cookie. That is to say, if the browser disables cookie, session will also fail. When storing session, the key is the same as session ID in Cookie, and the value is the key-value pair information set by developers. Coded, expiration time set by developers
 3. Cook is less secure than session

39. Brief description of multi-threading and multi-process

1. The basic unit of resource allocation and scheduling in an operating system, where multiple processes are independent of each other.
2. Good stability, if a process crashes, it will not affect other processes, but the process consumes a lot of resources, and the number of processes opened is limited.

1. The basic unit of resource allocation and scheduling in CPU. Threads are part of a process, and they are smaller than processes and can run independently. Threads under a process can share all the resources of the process.
2. If IO operation is intensive, it can run multi-threads efficiently. The disadvantage is that if a thread crashes, it will cause process crash.

IO-intensive multi-threading, user input, sleep, can switch to other threads to execute, reduce waiting time
 CPU intensive use of multi-process, because if IO operation is less, multi-threading, because threads share a global interpreter lock, currently running threads will occupy GIL, other threads without GIL, can not make full use of the advantages of multi-core CPU.

40. What elements in python are false and the list is duplicated

0, empty string, empty list, empty dictionary, empty tuple, None, False

b=[]   #Use append method to add in turn
for i in a:    

c=a.copy() #Using the built-in copy method

d=a[:] #Section

e=a #It can't be copied directly. a and b are the same (id is the same). Addition, deletion and modification will affect each other.

41. The difference between copy and deep copy in python

# Invariant data types: deep and shallow copies of values, strings, tuples and assignment operations = are the same, as is id; values before and after copying are not changed, which is equivalent to redefining a variable;
# Variable data types: lists, dictionaries, collections. copy changes the values before and after copying. Depcopy does not change the values after copying.
import copy
a = [11, 12]
b = [21, 22]
num = 555
c = [a, b,num] #[[11, 12], [21, 22], 555]
c1=copy.copy(c) #[[11, 12], [21, 22], 555]
a[0]=16 #Variable element modification modifies the values of c and c1
c[2]=666 #Modification of immutable elements only modifies the original value, but not the duplicated value.
num=777 #It does not change the values of c1 and c2, which is equivalent to redefining a variable num.
print(c) #[[16, 12], [21, 22], 666]
print(c1) #[[16, 12], [21, 22], 555]

#print(c1) #[[11, 12], [21, 22], 555]

42. For foo sorting, the output is= [0, 2, 4, 8, 8, 9, -2, -4, -4, -5, -20], with positive numbers from small to large and negative numbers from large to small.

foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4]
a=sorted(foo,key=lambda x:(x<0,abs(x)))
print(a) #[0,2,4,8,8,9,-2,-4,-4,-5,-20]

43. List Sorting

# List nested dictionary sorting, sorted by age and name, respectively
foo = [{"name":"zs","age":19},{"name":"II","age":54},{"name":"wa","age":17},{"name":"df","age":23}]

a=sorted(foo,key=lambda x:x['name'])
b=sorted(foo,key=lambda x:x['age'])
print(a)#[{'name': 'II', 'age': 54}, {'name': 'df', 'age': 23}, {'name': 'wa', 'age': 17}, {'name': 'zs', 'age': 19}]
print(b)#[{'name': 'wa', 'age': 17}, {'name': 'zs', 'age': 19}, {'name': 'df', 'age': 23}, {'name': 'II', 'age': 54}]

#List nested meta-ancestors, sorted by letters and numbers, respectively
foo = [("age",19), ("ll",54), ("wa",17), ("df",23)]
a=sorted(foo,key=lambda x:x[0])#Letter
b=sorted(foo,key=lambda x:x[1])#number
print(a)#[('age', 19), ('df', 23), ('ll', 54), ('wa', 17)]
print(b)#[('wa', 17), ('age', 19), ('df', 23), ('ll', 54)]

#List nested list, the same number of age how to do?
foo = [["age",19], ["ll",54], ["wa",17], ["df",23],["xf",23]]
a = sorted(foo, key=lambda x:(x[1],x[0]))  # Add parameters, sorted alphabetically
print(a)#[['wa', 17], ['age', 19], ['df', 23], ['xf', 23], ['ll', 54]]

44. Sort by string length

b=sorted(s,key=lambda x:len(x))

#Method 2
print(s) #['a', 'ab', 'abc', 'djhfdh']

45. Examples of SQL injection and solution

When writing in string format, if the user enters;+SQL Statement, followed by SQL Statements are executed, such as in the example SQL Injection deletes the database demo
input_name = 'zs'
sql = 'select * from demo where name="%s"' %(imput_name)
print('Natural SQL language', sql)

# input_name = 'zs;drop database demo'
sql = 'select * from demo where name="%s"' %(imput_name)
print('SQL Injection statement', sql)

# Solution: Solving SQL Injection by Passing Parameters
find_name = input("Please enter the item name:")

# Create Connection Connections
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# Get the Cursor object
cs1 = conn.cursor()

# Safe Ways
# Construct parameter list
params = [find_name]
# Execute the select statement and return the number of rows affected: Query all data
count = cs1.execute('select * from demo where name="%s"' ,params)
# Be careful:
# If you have multiple parameters, you need to parameterize
# Then params = [numeric 1, numeric 2...], where there are multiple% s in the sql statement 

# Print the number of affected rows

46, s = info:xiaoZhang 33 shandong, and output ['info','xiaoZhang','33','shandong'] using regular segmentation strings

s ='info:xiaoZhang 33 shandong'
import re
res=re.split(r':| ',s)

47. Regular matching of mailboxes ending at

email_list = ['','xiaoWang@16.comheihei','']
import re
for email in email_list:    
    if res:        
        print('{}It is a regular mailbox address. The result of matching is:{}'.format(email,    
        print('{} Non-conformity'.format(email))

48. Recursive summation and completion of 1+2+3+... + 10 and

def get_sum(num):    
    if num >=1:        
        res=num + get_sum(num-1)    
    return res

print(res) #55

49. python dictionary and json string conversion method

import json
dic = {"name":"zs"}
print(res,type(res)) #Dictionary String {"name": "zs"} <class'str'>

print(ret,type(ret))#String-to-string dictionary {name':'zs'} <class'dict'>

50. Regular matching is not a cell phone number ending in 4 and 7

tels = ['13100001234','18912344321','10086','18800007777']
import re
for tel in tels:
	ret = re.match('1\d{9}[0-3,5-6,8-9]',tel) # \d Match a numeric character {9} Matching deterministic N second [0-3,5-6,8-9] Match numbers other than 47#     
	if ret:         
		print('The desired result',    
		print('{} Not the phone number you want'.format(ret))

51. Brief description of python reference counting mechanism

# python garbage collection is mainly based on reference counting, supplemented by marker-clearance and generation-clearance, in which marker-clearance and generation-recycling are mainly used to deal with the problem of cyclic reference.

# Reference Counting Algorithms
 # When a variable holds a reference to an object, the reference count for that object is increased by 1
 # When del is used to delete the object pointed to by the variable, if the reference count of the object is not 1, such as 3, then only the reference count will be reduced by 1, that is, to 2, and to 1 when del is called again.
# If you call del one more time, the object will be deleted.

52. Find the intersection, difference and union of two lists

a = [1, 2, 3, 4]
b = [4, 3, 5, 6]
jj1 = [i for i in a if i in b]  # stay a Medium i,And also b The middle is the intersection. print('intersection', jj1)  # [3, 4]

jj2 = list(set(a).intersection(set(b)))
print('intersection', jj2)  # [3, 4]

bj1 = list(set(a).union(set(b)))  # Consolidation union Method print('Union', bj1)  # [1, 2, 3, 4, 5, 6]

cj1 = list(set(a).difference(set(b)))  # There is one in a and none in b.
cj2 = list(set(b).difference(set(a)))  # There is one in b and none in a.

print('Difference set', cj1)  # [1, 2]
print('Difference set', cj2)  # [5, 6]

53. Regular expressions match the first URL

s = '<img src="" ' \    'class="account-fifa-coins" alt="wow eu gold">,' \    '<img alt=" Lowest Price. Anywhere you see lower Price, Any Items, Message me for Discount - All Servers delivery!" ' \    'src="">'

import re
res=re.findall(r'https://.*?\.jpg',s)[0]# The extract is a list
print( #search needs to be extracted by adding group()

54. Linux redirection > and > >

# Linux command redirection > and > >
# Linux allows redirection of command execution results to a file
 # To output/append the content that should be displayed on the terminal to the specified file
 #> Represents output, overwriting the original content of the file
 #>> Represents an addendum that adds content to the end of an existing document

# Save the echo output information to 1.txt in echo Hello Python > 1.txt
 # Append the echo output to the end of the 1.txt file echo Hello Python > > 1.txt

55, r, R +, rb, Rb + file opening mode differences

56. The difference between requesting get post s in HTTP

Get generates a TCP packet, the browser sends http header with data, and the server responds 200
 POST generates two TCP packets. The browser sends http header first, the browser returns 100 continue, the browser sends data again, and the server responds 200 ok.

57. python read excel method

import pandas as pd
df = pd.read_excel('33.xlsx')

58. Given an array of integers nums and a target value target, you can find the two integers that sum to the target value in the array and return their array subscripts. You can assume that each input corresponds to only one answer. However, you can't reuse the same elements in this array. Binary search

def halfSearch(nums, target):    
    low=0 #Initial Index    
    high=len(nums)#Final Index    
    while low<high:        
        mid=int((low+high) /2) #Intermediate Index        
        guess=nums[mid] #The value of the intermediate index        
        if guess==target:            
            return mid        
        if guess > item:            
    return None

nums=[2, 7, 11, 15]
print(halfSearch(nums,target)) #2

59. Find the file whose name contains the specified string in the current directory and all subdirectories of the current directory, and print out the relative path

import os
def search_file(dir, sname=None):    
    if sname==None:        
        return os.listdir(dir)    
    if sname in os.path.split(dir)[1]:#Verify that the file name contains sname
        print(os.path.relpath(dir))#Print relative path, relative to current path
    if os.path.isfile(dir): # If the incoming dir is directly a file directory, he does not have a subdirectory and does not need to traverse its subdirectory again.        
        return None    
    for dire in os.listdir(dir): #Traversing through subdirectories where dire is the current file name
        search_file(os.path.join(dir,dire),sname) ##jion becomes the absolute path to the current file.
dir=os.getcwd() #Get the current path

60. Brief Introduction of Optimistic Lock and Pessimistic Lock

Pessimistic Lock
 Always assume the worst case. Every time you go to get the data, you think someone else will modify it, so every time you get the data, you lock it, so that someone else will block it until it gets the lock. (Shared resources are only used by one thread at a time, other threads block, and then transfer the resources to other threads after use up.) Thread).
Traditional relational databases use many of these locking mechanisms, such as row lock, table lock, read lock, write lock, etc., which are locked before doing operations.

Pessimistic Lock Use Scenario
 It is more suitable for scenarios where writing operations are frequent. If there are a large number of read operations, each read will be locked, which will increase the overhead of a large number of locks and reduce the throughput of the system.

Optimistic Lock
 Always assume the best situation, every time you go to get the data, you think that others will not modify it, so you will not lock it, but when you update, you will judge whether others have to update the data during this period, you can use version number mechanism and CAS algorithm to achieve.
Optimistic locks are suitable for multi-read application types, which can improve throughput. Like the write_condition mechanism provided by the database, optimistic locks are actually provided.   

Optimistic lock usage scenario
 It is more suitable for scenarios where read operations are frequent. If there are a large number of write operations, the possibility of data collision will increase. In order to ensure data consistency, the application layer needs to constantly retrieve data, which will increase a large number of query operations and reduce the throughput of the system.

Tags: Python Lambda SQL Session

Posted on Sat, 07 Sep 2019 01:48:19 -0700 by Vidya_tr