Interview preparation after the 30-year-old test aunt was laid off by the manufacturer (continuously updated) 2

Posted by MarcB on Wed, 29 Dec 2021 18:48:18 +0100

1. Output the value of a key in the json file

// config.json
{"key": "demo",
"value": "demo value"}
import json
with open("config.json", "r") as f:
    json_str = f.read()
your_dict = json.loads(json_str)
# get key
print(your_dict["key"])
methoddescribeusage
json.dumpsEncodes Python objects into JSON stringsdata2 = json.dumps(data)
json.loadsDecodes the encoded JSON string into a Python objecttext = json.loads(jsonData)

python tutorial

2. Output the two arrays in json format in the form of key value pairs;

A = ['a',1,'c']
B = ['e',2,3]
D = dict(zip(A,B))
print(json.dumps(D))

3. The difference between tuple and list;

Tuples and lists belong to sequences, and they can store a group of elements in a specific order. The types are unlimited, as long as they are python supported types. The list is similar to the lyrics written on paper with a pencil. If it is wrong, it can be erased; Tuples are similar to those written with a pen and cannot be erased unless the paper is changed. difference:

differencelisttuple
variableThe list is a variable sequence, and the elements can be modified or deleted at any timeTuples are immutable sequences and cannot be modified unless they are replaced as a whole
methodThe list can use the append()\extend()\insert()\remove()\pop() methodTuples cannot be deleted, modified or added, and the above methods cannot be used
sectionLists you can use tiles to access and modify list elementsTuples support slice access elements, and modification is not supported
Access and processing speedThe list is relatively slowTuples are faster than list access and processing, so it is recommended to use tuples to improve performance without modifying only access
DictionariesA list cannot be used as a key for a dictionaryTuples can

python tutorial

List methodexplain
List name Append (element object)Add element
List name a.extend (list name b)Append b list to a
List name Remove (element value)Delete element values at indeterminate locations
List name Count (element)Counts the number of times an element appears in the list
List name Insert (index position, element object)Inserts the specified object into the list at the specified location
List name pop()Removes an element from the list (the default last element) and returns the value of that element.

4. Strings are in reverse order, and the time complexity is 0 and 1;

#String inversion
 Method 1: String slicing
str = input()
print(str[::-1])

Abbreviation: print(input()[::-1])

Method 2: reversed function
str = input()
a = reversed(str)
print(''.join(a))

Method 3: reverse function
while True:
    try:
        s = input()
        b = list(s)
        b.reverse()
        print(''.join(b))
    except:
        break
  • Time complexity to be learned... Continuously updated

5. What should I pay attention to when testing redis;

Redis is an open source, high-performance key value database, which can be used as database, cache and message middleware. Multiple types of data structures are supported. In most cases, the main scenario of using redis is to help the relational database mysql reduce access pressure and improve query efficiency.

Precautions for redis testSpecific description
Data expirationDo you want to set the expiration time? Is the expiration time reasonable? The expiration time is set. Will the data be deleted after expiration?
redis storage spaceWhat is the maximum space required by redis during peak periods? Metadata + business data to judge; Can the currently set memory size be satisfied?
performancePay attention to the delay and timeout of redis. Query whether there are slow logs. Query whether there are abnormal redis logs. Query whether the number of rejected connections is 0.
cache hit rate Query and analyze whether the cache hit rate and cache miss rate are reasonable
1 what is avalanche, how to cause it, 2 solutions1) Cache avalanche refers to the large number of data in the cache to the expiration time, and the huge amount of query data causes excessive pressure on the database or even down the machine. Different from cache breakdown, cache breakdown refers to the concurrent query of the same data. Cache avalanche refers to the query of the database because different data are expired and many data cannot be found; 2) The expiration time of cached data is set randomly to prevent the expiration of a large amount of data at the same time. If the cache database is distributed, the hot data will be evenly distributed in different cache databases. Set hotspot data to never expire.
What is cache penetration and how it works? 3 solutions?An id database does not exist. Hackers always access this id, resulting in service crash. 1) Verification is added in the interface layer, such as user authentication verification, basic verification for id, and direct interception for id < = 0; 2) The data that cannot be retrieved from the cache is not retrieved in the database. In this case, the key value pair can also be written as key null. The cache effective time can be set to a short time, such as 30 seconds (setting too long will make it impossible to use under normal conditions). This can prevent the attacking user from repeatedly attacking with the same id; 3) add a bloom filter to quickly judge whether the key is in the database, Then filter the database requests.
Cache breakdown, solutionThe hot data is expired, and a large number of requests are hit on an expired hot data, resulting in the collapse of the database. 1) The hot data will never expire. If the number of visits reaches a certain amount within a certain time, the expiration time will be reset, so that the hot data will not expire; 2) Mutex, only one thread fetches data
Data consistency(1) Eliminating cache is a common cache processing formula. (2) there is no doubt about the timing of eliminating cache before writing to the database. (3) service is a general way to shield the underlying database and cache complexity from the business
Second kill activity ideas1) Front end - when the second kill starts, replace the javascript file, and the gray button becomes clickable - > set 5s to clickable once. 2) Back end - > a uid 5s request can only arrive once - > the back end adds a task queue to control the business - > use the cache and put the data in the cache

redis test point
Avalanche, breakdown, penetration
Architecture - second kill system optimization idea reference
Cache architecture design

6. Write a redis syntax;

Set key value pair:
redis 127.0.0.1:6379> SET runoobkey redis
OK
 Take out key value pairs:
redis 127.0.0.1:6379> GET runoobkey
"redis"

redis tutorial

7. The idea of fast platoon;

Quick sort is actually improved on the basis of bubble sort. Bubble sorting is that each traversal is compared in pairs, and the largest one is put behind.
The basic idea of quick sort is to divide the data to be sorted into two parts through one-time sorting. All the data in one part is smaller than all the data in the other part, and then quickly sort the two parts of data according to this method. The whole sorting process is recursive, so as to turn the data into an ordered sequence.
According to the rule of one-time fast scheduling, determine a key data, which is usually the first place of the data, and then compare it.

Quick sort
Time complexity of sorting algorithm
Quick row

8. Score candy evaluation;

There are N children standing in a row, and each child has a score
Now you should distribute candy to the children according to the following rules:
Each child should get at least one candy
Children with high scores get more candy than those with low scores
How many sweets do you have to hand out at least?

class Solution:
    def candy(self , ratings ):
        res=[1]*len(ratings)
        for i in range(1,len(ratings)):
            if ratings[i]>ratings[i-1]:
                res[i]=res[i-1]+1
        for i in range(len(ratings)-1,0,-1):
            if ratings[i-1]>ratings[i] and res[i-1]<=res[i]:
                res[i-1]=res[i]+1
        return sum(res)

Divide candy

9. Returns the first element and position that appears only once in a string;

Python: returns the first non repeating letter and position in a string
If it is a subscript, i+1 does not need to be returned

# -*- coding: utf-8 -*-
def first_char(str):
    dict1 = {}
    for i in range(len(str)):
        #Cumulative number of occurrences of characters
        if str[i] in dict1:
            dict1[str[i]] += 1
        #Only once, the value corresponding to the key is recorded once
        else:
            dict1[str[i]] = 1
    for i in range(len(str)):
        if dict1[str[i]] == 1:
            return str[i], i+1
if __name__ == '__main__':
    str1 = input('please input string:')
    print(first_char(str1))

The second way to write

while True:
    try:
        a = input()
        for i in a:
            if a.count(i) == 1:
                print(i)
                break
        else:print(-1)
    except:break

Find the first character in the string that appears only once

10. Find the longest common substring in two strings a and B

while True:
    try:
        s1=input()
        s2=input()
        if len(s1)>len(s2):#General idea: take substrings from short strings to see if they exist in long strings
            s1,s2=s2,s1
        length=0
        for i in range(len(s1)):
            for j in range(i+1,len(s1)):
                sub=s1[i:j+1]
                if sub in s2 and j-i>length:
                    res=sub
                    length=j-i
        print(res)
    except:
        break

Longest common substring

11. Counts the number of each character in the output string

st = input("Input string")
dic = {}
for i in st:
    if i in dic:
        dic[i] +=1
    else :
        dic[i] = 1
print(dic)

[whining] life at the end of December 2021 is not just a matter of indifference, but also layoffs and epidemic situation. thank you!

Writing here, I really want to sing a song
Not a hero, don't read the Three Kingdoms
If you are a hero, how can you not understand loneliness
Walking down Changbanpo alone, the moonlight is too gentle
~~
After being cut, the lyrics are full of sadness [polite but embarrassing smile] 🙂😢

Code questions come on + come on
Learn about the 28 law and pay attention to the center of gravity

Topics: Interview