Solutions to Thousand Questions of Digital IC Written Test--Programming && Scripting (8)

Preface

The summary of written test questions is to summarize the problems that may be encountered in the autumn recruitment. Solving the questions is not the purpose. The purpose is to discover your own loopholes in the process of doing the questions and consolidate the foundation.

All question results and explanations are given by the author. The answers are highly subjective. If there are any errors, please point them out in the comment area. The information is compiled from digital IC-related public accounts such as "Digital IC Workers", real questions from websites such as Niuke.com, and online written tests. Transcripts of real questions and interviews.

        Keep updated (2023.9.25) The article contains 270 single-choice questions, 106 multiple-choice questions, 16 fill-in-the-blank questions, 17 true-false questions, 72 short-answer questions, 3 logical reasoning questions, and 8 C language python script programming questions Tao .
All the codes provided by the author in this article are written as APIs and can be directly copied to the software to compile, run, and give results.  

        There are many questions, and even with previous analysis and the powerful ChatGPT, mistakes are inevitable. If you find any mistakes, please feel free to discuss them in the comment area.

        In addition, there is a little personal stuff~: At this moment, I feel that I must give...
The total number of words in the solution to the Thousand Questions of the Digital IC Written Test has reached 150,000+, and the webpage is severely stuck in coding, so it is divided into multiple parts to facilitate maintenance. The link is as follows: Solution to the Thousand Questions in the Digital IC Written Test--Single Choice Questions (1)
Digital
IC Solutions to Thousands of Questions in the Written Test - Single-Choice Questions (Part 2) Solutions to
Thousands of Questions in the Digital IC Written Test - Multiple-Choice Questions (Part 3) Solutions to Thousands of Questions
in the Digital IC Written Test - Fill-in-the-Blank Questions (Part 4) )
Solutions to thousands of questions in the digital IC written test - judgment questions (5) Solutions to
thousands of questions in the digital IC written test - short answer questions (6)
Solutions to thousands of questions in the digital IC written test - logical reasoning (7
) ​​​​Solutions to Thousand Questions of the Digital


python, C language, script programming questions

1. Please write a program in C language to count the number of each letter in the input string (the string only includes lowercase letters). For example, if the input string is: aaaaabbcccefff, the result is printed as: 5a2b3c1e3f. (MediaTek will be approved in advance in 2022)

Answer: For C language programming questions, you need to remember some basic syntax of C language and be familiar with pointers and arrays. This type of questions is generally not too difficult.


#include <stdio.h>

void main(){
    char str[100] = {0};
    int count[26] = {0};

    int i = 0;
    int count_index;

    scanf("%s", str);

    while(str[i] != '\0'){
        count_index = (str[i]- 'a');
        count[count_index] = count[count_index] + 1;
        i++;
    }
    for(i=0;i<26;i++){
        if(count[i]!=0){
            printf("%d%c",count[i],'a'+i);
        }
    }
    printf("\n");
}

Output result:

​​


2. [python] Please use a language you are familiar with (C, Java, Python) to define the nodes of the binary tree, and use depth-first search to obtain the maximum depth of a given binary tree and return the depth value. (MediaTek 2022 approved in advance) (also a Leecode easy question)

For example, given a binary tree [3, 9, 20, null, null, 15, 7],

3

/ \

9 20

/ \

15 7

Returns its maximum depth of 3.

Answer: Define a binary tree node structure TreeNode, and then use recursion to access all leaf nodes of the binary tree. The exit condition is not root, that is, root = None, that is, a node that does not exist. At this time, not root is true and exit. This recursive function.


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:

    def maxDepth(self, root):
        length = 0

        def dfs(root, d):
            nonlocal length
            if not root:
                return
            length = max(length,d)
            dfs(root.left, d+1)
            dfs(root.right, d+1)

        dfs(root, 1)
        return length


if __name__ == '__main__':
    # 定义题中所给的树
    root = TreeNode(3)
    root.left = TreeNode(9)
    node = TreeNode(20)
    root.right = node
    node.left = TreeNode(15)
    node.right = TreeNode(7)

    s = Solution()  # 例化类,才能调用类中的类函数
    print(s.maxDepth(root))

3. [python] Given a string expression s, please use a language you are familiar with (C Java, Python) to implement a basic calculator to calculate and return its value (the operation only contains +- and parentheses). (MediaTek will be approved in advance in 2022)

Example 1:

Input: s="1+1"

Output: 2

Example 2:

Input: s="2-1+2"

Output: 3

Example 3:

Input: s="2-1+2"

Output: 3

Example 3:

Input: s="(1+(4+5+2)-3)+(6+8)"

Output: 23

Code:

Use the stack to store results and symbols outside the current parentheses, and use recursion to process expressions within the parentheses. Handle numbers, plus signs, minus signs, and parentheses separately in a loop. If a number is encountered, the current number is calculated; if a plus or minus sign is encountered, the current number and symbol are pushed onto the stack and the current number and symbol are reset; if a left bracket is encountered, the inside of the bracket is processed recursively expression, and returns the calculation result within the brackets and the position at the end of the bracket; if a right bracket is encountered, the current number and symbol are pushed onto the stack, and the calculation result outside the brackets and the position at the end of the right bracket are returned.

Finally, we add all the numbers and symbols in the stack to get the result of the entire expression.


def calculate(s: str) -> int:
    num = 0     # 记录当前数字
    sign = 1    # 记录当前符号
    stack = []  # 用来存储当前括号外的结果和符号
    res = 0     # 用来记录最终结果

    for i in range(len(s)):
        if s[i].isdigit():
            num = num * 10 + int(s[i])
        elif s[i] == '+':
            res += num * sign
            num = 0
            sign = 1
        elif s[i] == '-':
            res += num * sign
            num = 0
            sign = -1
        elif s[i] == '(':
            stack.append(res)    # 先存结果,再存数字
            stack.append(sign)    
            res = 0
            sign = 1
        elif s[i] == ')':
            res += num * sign
            num = 0
            res *= stack.pop()
            res += stack.pop()
        
    return res + num * sign

if __name__ == '__main__':
    s = "(1+(4+5+2)-3)+(6+8)"
    print(calculate(s))

Output result: 23

4. [Python] Please write a program in python to achieve the following functions with as few statements as possible: define a function to determine whether the result.log file exists in a given directory. If it exists, find out all results.log files from the result.log file. Lines containing the word fail (case-insensitive) and save these contents to a file named fail.log. If the file does not exist, an exception will be thrown () (MediaTek 2022 advance batch)

Code: The join() function in the os module is used to splice the directory path and file name. The open() function opens the result.log in read-only mode and the fail.log file in write mode . The lower() function converts each The letters in the line string are converted to lowercase letters, and the writelines() function writes the lines containing the word fail to the fail.log file. The program also uses an exception handling mechanism to handle situations where the result.log file cannot be found.


import os

def find_fail_lines(dir_path):
    try:
        with open(os.path.join(dir_path, 'result.log'), 'r') as f1, open(os.path.join(dir_path, 'fail.log'), 'w') as f2:
            fail_lines = [line for line in f1 if 'fail' in line.lower()]
            f2.writelines(fail_lines)
            print('Successfully saved fail lines to fail.log')
    except FileNotFoundError:
        print('result.log file not found in the directory')

# example usage
find_fail_lines('E:/modelsim_project/file_handle/')

5. Please write a Python code, open a file, scan each line, if it matches "biren01", "biren02",... "biren99", use the line number Key to save the matched "birenxx" (2022 wall)

To write this code, you need to know that in Python, you can use the enumerate function to get the line number and content of the file at the same time, for example:


with open('file.txt') as file:
    for i, line in enumerate(file, 1):
        print(f"Line {i}: {line}",end="")

The variable i is the line number of the line, and the variable line stores an entire line. The results are shown as follows:

​​

Code:


keywords = {}  # 创建一个空字典,用于保存匹配到的关键字和行号
with open('file.txt') as file:
    for i, line in enumerate(file, 1):
        for j in range(1, 100):
            keyword = f'biren{j:02d}'  # 生成关键字,如 'biren01'、'biren02' 等
            if keyword in line:
                if i not in keywords:  # 如果当前行号还没有在字典中出现过,则添加新的键值对
                    keywords[i] = [keyword]
                else:  # 如果当前行号已经在字典中存在,则将匹配到的关键字添加到已有的列表中
                    keywords[i].append(keyword)
for key, value in keywords.items():
    print(f"行号 {key},匹配到的字符为:{value}")

The fifth line f'...' represents a format string, where {j:02d} is a placeholder, indicating that the value of j is formatted as two digits, and if j is less than two digits, it is filled in front. zero. d here means formatting j as a decimal integer. Therefore, for j=1 , the generated string is 'biren01' , and the code output is as follows:

​​


6. Use C language to count how many prime numbers there are in 100~1000, and print out all the prime numbers. Prime numbers are also called prime numbers. A prime number is a number that is not divisible by any integer except 1 and itself.

Write a function to determine whether it is a prime number, return True or False, make a loop, and traverse the range from i = 2 to i = root number num. If num modulo i is equal to zero, it means i is a factor of num.


#include <stdio.h>

int is_prime(int num) {
    if (num <= 1) {
        return 0;
    }
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return 0;
        }
    }
    return 1;
}

int main() {
    int count = 0;
    printf("素数有:");
    for (int i = 100; i <= 1000; i++) {
        if (is_prime(i)) {
            count++;
        }
    }
    printf("共有%d个素数\n", count);
    return 0;
}

7. [python] Now there are two arrays a=[1, 1, 2, 4, 5], b=[1, 1, 2, 3, 7]. Please use python/perl to find these two arrays. The intersection and union of

This is done directly using python's set variable set.


a = [1,1,2,4,5]
b = [1,1,2,3,7]
intersection_A_B = set(a)-(set(a)-set(b))
union_A_B = set(a).union(set(b))
print(intersection_A_B)
print(union_A_B)

Code results:

​​


8. Please use any a programming language to locate the largest element in the matrix(矩阵)and print largest value,row and column of this largest value.

Matrix: matrix [3][4]={ {0,1,2,3},{8,7,6,5},{-5,9,-3,4}}


#include <stdio.h>
int main(void){
    int matrix[3][4] = {
     
     {0,1,2,3},{8,7,6,5},{-5,9,-3,4}};
    int row,column,max;
    max = 0;
    for (int i =0;i<=2;i++){
        for(int j=0;j<=3;j++){
            if(matrix[i][j]>=max){
                row = i;
                column = j;
                max = matrix[i][j];
            }
        }
    }
    printf("max value is:%d,the row is:%d,the column is:%d\n",matrix[row][column],row+1,column+1);
}

​​

Guess you like

Origin blog.csdn.net/qq_57502075/article/details/133262037