HW written test questions

HW written test questions

Reference:
Huawei Written Test April 6,
2021 Huawei Autumn Recruitment Written Test Questions
Huawei Written Test Questions Detailed Explanation 2021-08-18)


哔哩哔哩-Vannuo coding

Urban Tourism Planning

[NIO] Analysis of 7.13 written test questions [Double Pointer] [Sliding Window]
insert image description here

Algorithm analysis:
This question as a whole belongs to the problem of sliding windows in the array
1) First, sort the cities according to the cost value of the cities
2) Perform conventional sliding window processing on the sorted cities, that is:
3) When two When the cost difference of the city is less than k, the right pointer ++, plus the corresponding happy value; otherwise, the left pointer ++, subtract the corresponding happy value

Python source code

# 输入处理
N, k = map(int, input().split(' '))
city_xy = dict()
for i in range(N):
    x, y = map(int, input().split(' '))
    city_xy[x] = y
# 对键进行排序
keys_sorted = sorted(city_xy.keys())
# 定义双指针
left = right = 0
happy_vals = 0
max_happy = 0
while right < len(keys_sorted):
    happy_vals += city_xy[keys_sorted[right]]
    # 两个城市之间的花费差值不小于k
    # 左指针就要右移,同时要减去对应的开心值
    if keys_sorted[right] - keys_sorted[left] >= k:
        happy_vals -= city_xy[keys_sorted[left]]
        left += 1
    # 取当前较大的开心值
    max_happy = max(max_happy, happy_vals)
    right += 1
print(max_happy)

Maximize pig distance

Netease 2022 Spring Recruitment Written Examination Real Questions Analysis [Two Points Search]
insert image description here

Algorithm analysis:
This question as a whole belongs to the problem of binary search in the array, but it is hidden deeply and it is difficult to analyze it directly

Python source code

N, M = map(int, input().split(' '))
room = list(map(int, input().split(' ')))
room.sort()
# 判断在当前间隔下,是否满足放下M条猪的情况
def check(mid):
    pre = room[0]
    count = 1
    for i in range(1, len(room)):
        if pre + mid <= room[i]:
            count += 1
            pre = room[i]
    return count >= M
# 二分查找间隔
maxGap = (room[-1] - room[0]) // (M - 1)
left, right = 0, maxGap
res = maxGap
while left <= right:
    mid = (left + right) // 2
    if check(mid):
        res = mid
        left = mid + 1
    else:
        right = mid - 1
print(res)

Min Attack Defense Poor

Analysis of Tencent 0424 pen test questions [prefix sum] [simulation]
insert image description here

Algorithm analysis:
This question as a whole belongs to the problem of prefix sum
1) Traverse the entire array from front to back, and count the attack power corresponding to each subscript
2) Traverse the entire array from back to front, and count the defense power corresponding to each subscript
3) Subtract the two data results, and the position with the smallest absolute value difference is the cutting position

Python source code

strInput = input()
# 为了避免初始化,attack和defender都扩充了一个元素
# attack扩充的是第一个元素
# defender扩充的是最后一个元素
attack = [0] * (len(strInput) + 1)
defender = [0] * (len(strInput) + 1)
# 从前往后遍历
for i in range(1, len(strInput)+1):
    # 如果遇见0,则再前一个值的基础上加上当前下标
    if strInput[i-1] == '0':
        attack[i] = attack[i-1] + i
    else:
        attack[i] = attack[i-1]
# 从后往前遍历
for i in range(len(strInput)-1, -1, -1):
    # 如果遇见1,则再前一个值得基础上加上前下标
    if strInput[i] == '1':
        defender[i] = defender[i+1] + i+1
    else:
        defender[i] = defender[i+1]
# 移除扩充元素
attack = attack[1:]
defender = defender[:-1]
res = float('inf')
for i in range(len(attack)):
    res = min(res, abs(attack[i]-defender[i]))
print(res)

2021-Cheng

Critical Path - Directed Acyclic Graph

[Data structure] key path and code implementation (with c, java, python code)
diagram to find the key path (python) implementation
insert image description here

Algorithm analysis:
1) Generate adjacency matrix
2) Find Ve(v): The earliest occurrence time refers to the maximum path length from the starting point to the vertex Vk
-a) From front to back, take the largest value: Ve(v) of the direct predecessor node j) + the weight of the arrival edge (the edge pointing to the vertex), whichever is larger if there are multiple values ​​- b
) the first node Ve(j) is known, which is 0
3) Find Vl(v): the latest occurrence Time, on the premise of not postponing the entire duration, the latest allowed occurrence time of event vk
-a) From the back to the front, take a small value: Vl(j) of the immediate successor node - outgoing edge (edge ​​from the vertex) The weight of multiple values, whichever is smaller
- b) The terminal Vl(j) is known, which is equal to its Ve(j))
4) Find d(v): activity time margin, d(v) = l(v) - e(v), equal to 0 is the key point, that is, no delay

Python source code

def demo(matrix):
    # 最迟发生时间
    ve = [0] * len(matrix)
    que = [0] # 定义一个先进先出的队列
    while que:
        index = que.pop(0) # 取出队列中第一个元素,即matrix中的第index行
        for i in range(len(matrix)): # 遍历matrix中的第index行
            if matrix[index][i]: # 如果当前matrix元素不为零
                # 判断从index到i的距离是否大于之前的距离
                ve[i] = max(ve[i], ve[index]+matrix[index][i])
                # 将i节点添加到队列中
                que.append(i)
    print('ve={}'.format(ve))

    # 最早发生时间
    vl = [ve[-1]] * len(matrix)
    for index in range(len(matrix)-1, -1, -1): # matrix从下往上遍历
        # 再从左往右遍历
        for i in range(len(matrix)):
            if matrix[index][i]: # 如果当前matrix元素不为零
                # 判断从i到index的距离是否小于之前的距离
                vl[index] = min(vl[index], vl[i]-matrix[index][i])
    print('vl={}'.format(vl))

    res = []
    for i in range(len(ve)):
        if ve[i] == vl[i]:
            res.append("V" + str(i+1))
    return res

matrix = [[0, 6, 4, 5, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 2, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 9, 7, 0],
        [0, 0, 0, 0, 0, 0, 0, 4, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 2],
        [0, 0, 0, 0, 0, 0, 0, 0, 4],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]]
keyPoint = demo(matrix)
print('Key point: ' + ' '.join(keyPoint))

Solution two:

def demo(matrix):
    passed = [0]
    nopass = [i for i in range(len(matrix)) if i != 0]
    maxDis = matrix[0]
    path = dict()
    for i in range(len(maxDis)):
        if maxDis[i] != 0:
            path[i+1] = [1]

    while nopass:
        index = nopass[0]
        for k in nopass:
            if maxDis[k] > maxDis[index]: index = k

        passed.append(index)
        nopass.remove(index)

        for k in nopass:
            if matrix[index][k] != 0:
                if maxDis[index] + matrix[index][k] > maxDis[k]:
                    maxDis[k] = maxDis[index] + matrix[index][k]
                    path[k+1] = path[index+1] + [index+1]

    print('ve={}'.format(maxDis))
    print('path(1->9): {}'.format(path[9]))
    return maxDis
    # ve=[0, 6, 4, 5, 7, 7, 16, 14, 18]
	# path(1->9): [1, 2, 5, 7]

Dijstra algorithm (Dijstra)

Detailed implementation of Dijkstra's algorithm in python
insert image description here
Find the shortest path from the starting node (1) to the ending node (6)

Python source code

def demo(matrix):
    passed = [0] # 默认从第0个节点开始,以邻接矩阵的第0行为准
    nopass = [i for i in range(len(matrix)) if i != 0]
    minDis = matrix[0]
    # 初始化起始路径
    path = dict()
    for i in range(len(minDis)):
        if minDis != float('inf'):
            path[i+1] = [1]

    while nopass:
        # 取出nopass中在minDis中路径最小的节点
        index = nopass[0]
        for i in nopass:
            if minDis[i] < minDis[index]: index = i
        
        nopass.remove(index)
        passed.append(index)

        for i in nopass:
            if matrix[index][i] != float('inf'):
                if minDis[index] + matrix[index][i] < minDis[i]:
                    minDis[i] = minDis[index] + matrix[index][i]
                    path[i+1] = path[index+1] + [index+1]
        
    print('minDis={}'.format(minDis))
    print('path(1->6): {}'.format(path[6]))
    return minDis

inf = float('inf')
matrix = [[0, 1, 12, inf, inf, inf],
        [inf, 0, 9, 3, inf, inf],
        [inf, inf, 0, inf, 5, inf],
        [inf, inf, 4, 0, 13, 15],
        [inf, inf, inf ,inf, 0, 4],
        [inf, inf, inf, inf ,inf, 0]]
keyPoint = demo(matrix)
# minDis=[0, 1, 8, 4, 13, 17]
# path(1->6): [1, 2, 4, 3, 5]

2020-Tan

HJ82 Decomposition of real fractions into Egyptian fractions

insert image description here
Algorithm:
The core idea is a greedy algorithm.
The input is a/b, a is the numerator, and b is the denominator
1) Divide b by a to get the quotient q=b//a + 1, +1 means rounding up to get the remainder mod= b%a. Use the obtained quotient q as the denominator of the decomposed Egyptian fraction, that is, the first decomposed Egyptian fraction is 1/q
2) ​​Subtract the decomposed Egyptian fraction 1/q from the original fraction a/b to update the remaining The following score value a/b=(a-mod)/(b*q)
3) If the numerator becomes 1, or b can divide a evenly, jump out of the loop at this time, otherwise continue to repeat steps 1 and 2
4) Jump out After the cycle, if the numerator becomes 1 at the end, add 1/b; if the last b can divide a, add 1/(b//a)

In order to speed up, in the third step there is a judgment whether a is equal to 1, or whether b can divide a, and a judgment can also be added, that is, to judge whether a is equal to 3 and b can be divisible by 2. At this time, it can be directly decomposed into 1/ (b//2)+1/b

Python source code

while True:
    try:
        strInput = input()
        a, b = map(int, strInput.split('/'))
        res = []
        while a != 1 and b % a != 0:
            q = b // a + 1
            mod = b % a
            res.append('1/'+str(q))
            a -= mod
            b *= q
        if a == 1:
            res.append('1/'+str(b))
        else:
            res.append('1/'+str(b//a))
        print('+'.join(res))
    except:
        break

quick code

while True:
    try:
        strInput = input()
        a, b = map(int, strInput.split('/'))
        res = []
        while True:
            if a == 1:
                res.append('1/'+str(b))
                break
            elif b % a == 0:
                res.append('1/'+str(b//a))
                break
            elif a == 3 and b % 2 == 0:
                res.append('1/'+str(b//2))
                res.append('1/'+str(b))
                break
            else:
                q = b // a + 1
                a -= b % a 
                b *= q 
                res.append('1/'+str(q))
        print('+'.join(res))
    except:
        break

It can also be implemented recursively

def convert(a, b):
    if a == 1:
        print('1/%d' % b)
    elif b % a == 0:
        print('1/%d' % (b//a))
    elif a == 3 and b % 2== 0:
        print('1/%d+1/%d' % (b//2, b))
    else:
        q = b // a + 1
        print('1/%d' % q, end='+')
        a -= b % a 
        b *= q
        convert(a, b)

while True:
    try:
        strInput = input()
        a, b = map(int, strInput.split('/'))
        convert(a, b)
    except:
        break

Payment statistics

The person in charge of the procurement team is making information statistics, and the array arr stores the expenditures of the procurement team this month. The person in charge needs to find out the amount that is less than or equal to each data (arr[]) before (excluding this data), and calculate the sum of these data.
Please help him design an efficient algorithm to count their sum. When summing, you need to take the modulo 1e9+7 (1000000007). For example, if
the length of the initial array arr is greater than or equal to 1 and not more than 50000, each sum is an integer greater than or equal to 1 and not more than 20000. The initial result is: 1000000008, please return 1.
Input: 1 3 5 2 4 6, Output: 27

Algorithm analysis:
I feel that this question should be an optimization algorithm, but I really haven’t figured it out. What I think of
now is to solve it violently
1) Traverse the entire array
2) Traverse all the elements in front of the current element
3) Find all the previous elements that are less than or equal to the current element elements and add them to res
4) Modulo

Python source code

nums = list(map(int, input().split(' ')))
res = 0
for i in range(len(nums)):
    for j in range(i):
        if nums[j] <= nums[i]:
            res += nums[j]
out = res % 1000000007
print(out)

Solving Linear Equations

Given a real number matrix A, a real number vector b, and the number of columns of matrix A is equal to the number of rows of vector b, find the column vector x that makes the modulus of Ax-b the
smallest
,0;0,1] (newline) [2;3], output:

Algorithm analysis:
Common iterative solutions:
Jacobi iteration method
Gauss-Seidel iteration method
SOR iteration method
Here is one thing worth mentioning:
the difference between Gauss-Seidel iteration method and Jacobi iteration method is:
1) Jacobi iteration method Yes, all values ​​are uniformly updated according to the previous value of x
2) The Gauss-Seidel iteration method is to get the update equation of the next element for the elements that have been updated, instead of using the last value for all elements. This speeds up the iterative process

Jacobi iterative method and Gauss-Seidel iterative
method based on python Iterative method for solving linear equations Python implementation Python
Jacobi iterative method/Gauss-Seidel iterative method
python iterative method to solve equations_Python solve linear equations example

Python source code

The solution of solve in numpy linalg

import numpy as np
A = np.asarray(A)
B = np.asarray(B).T
x_cur = np.linalg.solve(A, B)
res = []
for x in x_cur:
    res.append(str(round(x)))
print('['+';'.join(res)+']')

Jacobi iterative solution

strA = input()[1:-1].split(';')
A = []
for v in strA:
    A.append(list(map(int, v.split(','))))
B = list(map(int, input()[1:-1].split(';')))
# Jacobi求解
x_pre = [0] * len(A[0])
x_cur = [0] * len(A[0])
error = 0.1
while True:
    min_error = 0
    for i in range(len(B)):
        sum_row = 0
        # 在当前x的值下,计算等号前面等式的结果
        for j in range(len(A[0])):
            sum_row += A[i][j] * x_pre[j]
        # 核心公式!!!更新x的值
        x_cur[i] = x_pre[i] + ((B[i] - sum_row)) / A[i][i]
        # 计算误差
        min_error = min(min_error, abs(x_cur[i] - x_pre[i]))
    # 当最小的误差都满足条件时,就跳出循环
    if min_error < error:
        break
    # 更新x_pre的值
    x_pre = x_cur
res = []
for x in x_cur:
    res.append(str(round(x)))
print('['+';'.join(res)+']')

more than the temperature of the day

The temperature has dropped a bit recently. Everyone hopes that the temperature will rise. In order to understand the recent weather conditions, Xiao Ming specially checked the recent daily temperature. Please help Xiao Ming calculate the temperature based on a certain day. Exceeding the temperature of the day, if the temperature has not risen, it means that the temperature will be lower than the current temperature after that day. It takes 0 days for the temperature to exceed the current temperature.
Input description:
1. Input an integer array, the value of each element in the array is between [-10, 40]
2. Assume that the problem of a certain few days is 1 3 4 6 1 4 2 8
3. Between two integers Use space intervals
4. Refer to the sample for the input and output formats.
Output description:
1. Output array, how many days does it take for the current index date of each value in the array to exceed the temperature of the index corresponding date
2. The corresponding output is 1 1 1 4 1 2 1 0
3. The temperature on the first day is 1, and the temperature on the second day is 3. If it is greater than 1, it only takes one day to exceed the temperature on the first day. 4. The temperature on the second day
is 3, and the temperature on the third day is 4. It is greater than 3, only It takes one day to exceed the temperature of the second day
...
5. The temperature on the fourth day is 6, the temperature on the fifth day is 1, less than 6, the temperature on the sixth day is 4, less than 6, the temperature on the seventh day is 2, less than 6, the temperature on the fifth day is 2, less than 6, The temperature of the eighth day is 8, which is greater than 6, so it takes 4 days for the temperature to exceed the fourth day
...
6. The temperature of the eighth day is 8, and there is no more, so it takes 0 days.
Test example:
Input: 1 3 4 6 1 4 2 8. Output: 1 1 1 4 1 2 1 0

Algorithm analysis
The first idea is to solve violently. .
1) Traverse all elements
2) Traverse the elements behind the current element
3) Find the first value greater than the current element, calculate the distance between the two, and store it in res; if it has not been found, store 0
(Huawei's this The finale question is so simple that I can’t believe it.. Am I thinking too much or am I thinking too little?)

Python source code

temperature = list(map(int, input().split(' ')))
res = []
for i in range(len(temperature)-1):
    for j in range(i+1, len(temperature)):
        if temperature[j] > temperature[i]:
            res.append(str(j-i))
            break
        if j == len(temperature) - 1:
            res.append(str(0))
res.append(str(0))
print(' '.join(res))

2019-Long

8 times string

Continuously input strings (the number of input strings is N, the length of each string is not greater than 100, and the input strings are separated by space keys), please split each string according to the length of 8 and output to a new string Array, the output strings are sorted in ascending order.
If the length of the string is not an integer multiple of 8, please add the number 0 at the end, and the empty string will not be processed.
Input content: 2 abc 123456789
Input description: Enter 2 strings (separated by spaces), one of which is abc, and the other is 123456789 Output
result: 12345678 90000000 abc00000
Output description: The string abc needs to be appended with zeros, and 123456789 is split For 12345678 and 90000000, all strings are output in ascending order (separated by spaces).

Relatively simple, no analysis

Python source code

inputList = input().split(' ')[1:]
res = []
for strT in inputList:
    if len(strT) <= 8:
        res.append(strT+'0'*(8-len(strT)))
    else:
        while len(strT) > 8:
            res.append(strT[:8])
            strT = strT[8:]
        if len(strT) > 0:
            res.append(strT+'0'*(8-len(strT)))
res.sort()
print(' '.join(res))

string expansion

Given a string, the string contains numbers, uppercase and lowercase letters, and brackets (including braces, brackets, and parentheses). The brackets can be nested, that is, numbers and brackets can appear inside the brackets. Expand the string according to the following rules, without considering the mismatching of parentheses. The use case ensures that the parentheses match, and at the same time, the use case ensures that there are parentheses after each number, regardless of the fact that there are no parentheses after the number, that is, 2a2( b) This situation is not considered.
1) The number indicates the number of repetitions of the string in the brackets, and the expanded string does not contain the brackets.
2) Expand the string in reverse order.
Output the final expanded string.
Input content: abc3(A), output result: AAAcba

Algorithm analysis reference: the shorthand method of repeated characters in
the real interview algorithm questions of major factories

Python source code

strInput = input()
stack = []
repeat_times = []
pairs = {
    
    ')': '(', ']': '[', '}': '{'}
for i in range(len(strInput)):
    # 如果是数字就将其记录到重复次数repeat_times栈中
    if strInput[i].isdigit():
        repeat_times.append(int(strInput[i]))
    # 如果是右边括号,则需要展开括号里面的内容
    elif strInput[i] in pairs:
        val = stack.pop()
        temp_stack = []
        # 取出最近的一次重复内容temp_stack
        while val != pairs[strInput[i]]:
            temp_stack.append(val)
            val = stack.pop()
        # 取出最近的一次重复次数temp_times
        temp_times = repeat_times.pop()
        # 根据重复次数将重复的内容再次压入stack栈中
        for t in range(temp_times):
            for v in range(len(temp_stack)-1, -1, -1):
                stack.append(temp_stack[v])
    # 如果是其他字符,则依次压入stack栈中
    else:
        stack.append(strInput[i])
print(''.join(stack[::-1]))

Crack the encrypted password

Xiao Wang's safe password is a string of numbers arranged in ascending order . But Xiao Wang can't remember his password, so Xiao Wang encrypts his password and saves it in a text file. The encryption process is as follows: 1.
Replace the number itself with the English word of the number. For example, 134699 becomes onethreefoursixninenine
2. Use the "Xiaowang Encryption Algorithm" to process the appeal string. This algorithm will change the order of the original string characters according to certain rules, and also change the case of certain letters. For example, onethreefoursixninenine becomes NeNohuiroNNiNeteefersix after being encrypted
. Since the "Xiaowang Encryption Algorithm" was designed by Xiaowang himself, Xiaowang thinks that only he can restore the encrypted string.
In fact, there are loopholes in Xiao Wang's encryption algorithm. Even if you don't know the specific implementation details of "Xiaowang Encryption Algorithm", you can restore the original password. Please write a program to crack Xiao Wang's password.
Input: ONEthrEEfoursixNiNENiEN, Output: 134699

Algorithm Analysis
Let’s take a look at the English letters of the numbers 0 to 9.
0: zero
1: one
2: two 3
: three 4
: four
5: five
6: six
7: seven
8: eight
9: nine
In fact, this question is a search for rules Question
1) First of all, we will find that there are several numbers with special letters. In other words, if the letter is given to you, it must be a number. Let's find out which numbers meet this condition. There are 0 (Zero), 2 (tWo), 4 (foUr), 6 (siX), 8 (eiGht). It can be found that
if there is Z, there must be 0 , if there is W, there must be
2, if there is U, there must be 4 , if there is X, there must be 6 , if there is G, there must be 8, and if there is no, they are all even numbers! I don't know if this is a coincidence in English numbers. . 2) After removing 0, 2, 4, 6, and 8, the remaining numbers 1 (one), 3 (three), 5 (five), 7 (seven), 9 (nine) are all odd numbers. We can find in the odd numbers : If there is an O, there must be a 1. If there is a T, there must be a 3. If there is an F, there must be a 5. If there is an S, there must be a 7. 3) 9 is worse. After removing all the letters above, if there are still letters left at the end, it can only be 9











Python source code

strInput = input().lower()
# 记录下第一批拥有特殊字母的数字
special1 = {
    
    'z': '0', 'w': '2', 'u': '4', 'x': '6', 'g': '8'}
# 记录下第二批拥有特殊字母的数字
special2 = {
    
    'o': '1', 't':'3', 'f': '5', 's': '7'}
# 数字和英文字母之间的对应关系
number2alpha = {
    
    '0': 'zero',
                '1': 'one',
                '2': 'two',
                '3': 'three',
                '4': 'four',
                '5': 'five',
                '6': 'six',
                '7': 'seven',
                '8': 'eight',
                '9': 'nine'}
# 遍历整个输入str,将其存入一个字典里面,记录每个字母出现的次数
strDict = dict()
for s in strInput:
    if s in strDict: strDict[s] += 1
    else: strDict[s] = 1
res = []
special = [special1, special2]
# 先遍历第一批特殊字母,然后第二批
for sp in special:
    # 遍历特殊字母
    for keyStr, keyNum in sp.items():
        while True:
            # 如果输入字符串strDict中存在特殊字母
            if keyStr in strDict:
                # 记录下对应的数字
                res.append(keyNum)
                # 移除对应数字的所有字母
                numStr = list(number2alpha[keyNum])
                for k in numStr:
                    strDict[k] -= 1
                    # 如果遇见次数为0的字母,则从strDict中移除
                    if strDict[k] == 0: del strDict[k]
            # 如果不存在,则跳出循环
            else: break
# 如果此时strDict还不为空,那剩的一定就是数字9了
if strDict:
    # 统计一下会有几个9
    times = strDict['e'] # 看字母i或者e都行,唯独不能看n,看的话记得除以2~~
    for t in range(times):
        res.append('9')
del strDict
# 升序的密码
res.sort()
print(''.join(res))

Guess you like

Origin blog.csdn.net/qq_33757398/article/details/125826025