China Electronics Society May 2023 Youth Software Programming Python Level Examination Paper Level 5 Real Questions (Including Answers)

2023-05 Python Level 5 Real Exam Questions

Score: 100

Number of questions: 38

Test duration: 60min

1. Multiple-choice questions (25 questions in total, 50 points in total)

1. There is a list L=['UK','china','lili',"Zhang San"], what is the result of print(L[-2])? (C)

A.  UK

B. 'lili','Zhang San'

C.  lili

D.  'UK','china','lili'

Answer analysis: List element positioning

2. Countdowns are widely used in daily life. Python uses range to implement reversed numbers. Which statement below can correctly output positive integers within 15 in reverse order? (D)

A.  print(list(range(15, -1, 1)))

B.  print(list(range(-1, 15, 1)))

C.  print(list(range(15, 1, -1)))

D.  print(list(range(15, 0, -1)))

Answer analysis: high-level applications of range(start, stop[, step])

3. A string s="iloveyou" is known. Construct a new list li=['i', 'oveyou'] by operating on this string. Which of the following options does not construct a new list li? (A)

A.  li = s.split("l",0)

B.  li = s.split("l",1)

C.  li = s.split("l",2)

D.  li = s.split("l",3)

Answer analysis: This question mainly examines the usage of the split() function. Split the string. Slice the string by specifying the delimiter and return the split string list (list). The syntax rules are: str.split(str="",num=string.count(str)) str: expressed as a separator, the default is a space, but it cannot be empty (''). If there is no delimiter in the string, the entire string is treated as an element of the list num: represents the number of divisions. If the parameter num exists, it will only be divided into num+1 substrings, and each substring can be assigned to a new variable.

4. There is the following program. What is the execution result of this program? (D) 

tup1 = (12,'bc',34,'cd')

tup1[1] = 23

print(tup1[3])

A.CD

B.  12

C.  34

D. There is an error in the program

Answer analysis: The elements of the tuple cannot be modified.

5. There is the following python program segment. Which of the following statements is wrong? (D)

s={1,2,3,4,5}

print(s)

s.clear() 

print(s)

A. "{1,2}+{5,6}" is a wrong statement

B. s data type is a collection

C. The function of this program segment is to output the original set s and the set s after removing the data.

D. s data type is dictionary

Answer analysis: Creation and related operations of collections.

6. Existing campus library borrowing information collection data list for the last week (Monday to Sunday): borrow = [502, 387, 612, 545, 702, 855, 962], currently it is necessary to print out the data from Monday to Friday Information, what is the correct action? (C)

A.  print(borrow[1:n-2])

B.  print(borrow[0:n-1])

C.  print(borrow[:-2])

D.  print(borrow[::-2])

Answer analysis: List slicing operation, the correct operation for this question is print(borrow[:-2]).

7. The sensor list sensor = ['shengyin', 'chaoshengbo', 'guangmin', 'huidu'] used in the practical work of the technology team currently needs to add the list element 'hongwai'. What is the correct operation? (B)

A.  sensor.insert('hongwai')

B.  sensor.append('hongwai')

C.  inset sensor['hongwai']

D.  append sensor['hongwai']

Answer analysis: The Python append() function is used to add new objects at the end of the list.

8. Strings in Python can be escaped using backslashes to achieve certain effects that are difficult to express using characters. What is the escape character that can realize horizontal tabulation (jumping to the next TAB position)? (C)

A.  \b

B.  \n

C.  \t

D.  \r

Answer analysis: String escaping, \t can achieve horizontal tabulation (jumping to the next TAB position).

9. The existing string S = "No mountain is more high than one." Now we need to calculate and output the number of times 'o' appears in S in the string. What is the correct statement? (D)

A.  print(S.find('o',1))

B.  print(S.index('o'))

C.  print(S.index('o',0,len(S)))

D.  print(S.count('o'))

Answer analysis: The count function is used to count the number of times a certain character appears in a string.

10. What are the functions of the following programs? (B)

shu=10000

result=[a for a in range(1,shu+1) if shu%a==0]

print(result)

A. Calculate and output prime numbers within 10,000

B. Calculate and output the divisor of 10000

C. Calculate and output multiples of 10000

D. Calculate and output integer 10 numbers within 1-10000

Answer analysis: The syntax format of list comprehension is as follows: [expression for iterable variable in iterable object [if conditional expression] ]

11. Run the following program: list(range(2,9,2)) What is the output result? (B)

A.  2, 4, 6, 8

B.  [2, 4, 6, 8]

C.  [1, 3, 5, 7, 9]

D.  1, 3, 5, 7, 9

Answer analysis: Convert the numbers 2, 4, 6, and 8 produced by range() into a list.

12. The following books is a dictionary with a for loop as follows:

    for  info1,info2 in books.items( ):

       print(info2)

What can be obtained from the above info2? (B)

A. key

B. Value

C. Key-value

D. Dictionary

Answer analysis: A simple application of dictionary keys/values ​​can get the dictionary value.

13. Set A is the people who have traveled to Yunnan, and set B is the people who have traveled to Hainan. If you now want to get the people who have been to Hainan but have never traveled to Yunnan, which collection function can you use? (D)

A.  A & B

B.  A | B

C.  A - B

D.  B - A

Answer analysis: The difference operation of sets returns a new set including elements that are in set B but not in set A.

14. Find all the numbers within 1-100 that are divisible by 7 but not divisible by 3. What is the correct list comprehension? (D)

A.  print([for x in range(0, 100) if x % 7 == 0 and x % 3 != 0])

B.  print([for x in range(1, 101) if x % 7 == 0 and x % 3 != 0])

C.  print([x for x in range(0, 100) if x % 3 == 0 and x % 7 != 0])

D.  print([x for x in range(1, 101) if x % 7 == 0 and x % 3 != 0])

Answer analysis: The syntax format of list comprehension is as follows: [expression for iterable variable in iterable object [if conditional expression] ]

15. Using the time module, which of the following statements is correct to output the current date? (B)

A.  print(time.ctime('%y%m%d'))

B.  print(time.strftime('%y%m%d'))

C.  print(time.nowdate('%y%m%d'))

D.  print(time.local('%y%m%d'))

Answer analysis: The Python time strftime() function is used to format time and return the local time expressed as a readable string. %y is a two-digit year representing (00-99) %m month (01-12) %d month A day within (0-31).

16. Which statement can be used to randomly generate floating point numbers between 1 and 100 in Python? (A)

A.  print(random.uniform(1,100))

B.  print(random.randint(1,100))

C.  print(random.sample(1,100))

D.  print(random.shuffle(1,100))

Answer analysis: Python random.uniform(a, b) is used to generate a random floating point number within a specified range. One of the two parameters is the upper limit and the other is the lower limit.

17. It is known that there is a list lst = [2,3,4,5,6]. Which of the following operations can find the minimum value? (B)

A.  sum(lst)

B.  min(lst)

C.  max(lst)

D.  MIN(lst)

18. It is known that there are tuples tup1=('a','b'), tup2=(1,2,3), tup3=('china','UK'), execute print(tup1+tup2+tup3) What is the final output? (C)

A.  ['a', 'b', 1, 2, 3, 'china', 'UK']

B.  (('a','b'),(1,2,3),('china','UK'))

C.  ('a', 'b', 1, 2, 3, 'china', 'UK')

D.  'a', 'b', 1, 2, 3, 'china', 'UK'

19. str1="You are a great hero", which of the following options can be executed to output "A great hero is you"? (B)

A.  print((str1(0,0))

B.  print(str1[::-1])

C.  print(str1[0])

D.  print(str1[0:5])

20. In Python, the range function means to generate a sequence, and range(6) means to generate a sequence? (B)

A.  0-6

B.  0-5

C.  1-6

D.  1-5

21. What is the result after running the following code? (D)

dp={}

dp["2^10"]=1024

print(dp)

A.  ['2^10': 1024]

B.  {"2^10"}

C.  1024

D.  {'2^10': 1024}

22. After running the following code, the corresponding output result is obtained. Which derivation formula is used? (C)

a = [i for i in range(10) if i % 3 ==0]

print(a)

#output: [0, 3, 6, 9]

A. Set derivation formula

B. String derivation formula

C. List derivation formula

D. Tuple derivation formula

23. What is the output result of the following Python code? (B)

a = {i**2 for i in (6,7,8) if i>3}

print(a)

A.  (36,49,64)

B.  {64, 49, 36}

C.  {64,49}

D.  {2,36,64}

Answer analysis: The format of the collection derivation is: {expr for value in collection} or: {expr for value in collection if condition}

24. What is the result after running the following code? (C)

import jieba

str ="大家好,我叫龙云!请多多关照!"

jieba.suggest_freq(("龙云"),True)

print(jieba.lcut(str))

A. 'big', 'home', 'good', ',', 'I', 'call', 'dragon', 'yun', '!', 'please', 'Duoduo', 'Care', '!'

B. ['everyone', 'good', ',', 'I', 'call', 'dragon', 'yun', '!', 'please', 'take care of me', '!']

C. ['Everyone', 'Okay', ',', 'I', 'Calling', 'Long Yun', '!', 'Please', 'Take care of me', '!']

D. ('everyone', 'good', ',', 'I', 'call', 'Long Yun', '!', 'please', 'take care of me', '!')

Answer analysis: jieba library application in python. Some words appear in some sentences, but are separated into two separate words. Although the lexicon can be adjusted in this way, you only need to reload the custom lexicon. In addition, we can also solve this problem by adjusting word frequency. Question, this question forces the name "Long Yun" to be a word instead of splitting it into two separate characters. jieba.suggest_freq(("Long Yun"),True) is a full-mode syntax.

25. What is the result after running the following code? (D)

import math

a=math.floor(10.2)

print(a)

A.  10.20

B.  10.0

C.  11

D.  10

Answer analysis: Math library application in python. math.floor is the rounding down function

2. True or False Questions (10 questions in total, 20 points in total)

26. In the Python language, strings are ordered sequences. ( right)

Answer analysis: The description of the question stem is correct. Python lists, tuples, and strings are all ordered sequences.

27. You cannot access elements in a collection by reference to an index, but you can use a for loop to traverse the elements in a collection. (wrong)

28. multiples = [i for i in range(30) if i % 3 == 0] , in this derivation, there are 10 elements in multiples. ( right)

29. In the new semester, the calligraphy club has added new students. There are currently n people in total. Xiaogang, as the information officer of the club, used Python to create a list. The list index starts from 1 and ends with n. ( wrong)

Answer analysis: Python creates a list, and the list index starts from 0 and ends at n-1.

30. The elements of a tuple in Python cannot be changed in place. ( right)

31. In Python, you can use .replace() to remove spaces at the beginning and end of a string. (wrong)

Answer analysis: In Python, you can use .replace(old,new[,max]) to replace the old string in the string with a new string. If the third parameter max is specified, the replacement will not exceed max times.

32. The enumerate() function is a built-in function of Python. It can be used to traverse an iterable object. It can also get the index position of the current element while traversing. (right)

33. The "value" of a dictionary (dict) in Python can be a list (list), dictionary (dict), or set (set) type. (right)

Answer analysis: The keys of a Python dictionary can be integers, strings, or tuples, as long as they meet the unique and immutable characteristics; the values ​​of the dictionary can be any data type supported by Python.

34. For musical instrument club activities, Xiao Ming wrote a summary program in Python. In his program, the elements of the musical instrument collection can be the same. ( wrong)

Answer analysis: Set elements in Python cannot be the same.

35. After the PyInstaller command is executed, two folders, dist and build, will be generated in the directory where the source file is located. (right)

Answer analysis: The build folder is mainly used by PyInstaller to store temporary files, and the packaged program is stored in the dist folder.

3. Programming questions (3 questions in total, 30 points in total)

36. It is known that the format of IPv6 address string is X:X:X:X:X:X:X:X, where each X represents a string of length 4. For example: an IPv6 string is "2A08:CCD6:0088:108A:0011:0002:202F:AA05". The IPv6 notation requires the leading zeros of each X to be omitted. The program output is as shown below:

 

The program is now designed to automatically delete the leading zeros of the IPv6 address. Please fill in the appropriate code in the underlined area.

s="2A08:CCD6:0088:108A:0011:0002:202F:AA05"

        ①       

flag=False

for i in range(len(s)):

    if s[i]==":":

                ②       

        flag=False

    elif         ③        :

        ans+=s[i]

        flag=True

print("原 IPv6 地址为:",s)

print("去前导零后:",ans)

Reference procedure:

s="2A08:CCD6:0088:108A:0011:0002:202F:AA05"

ans=""  

flag=False

for i in range(len(s)):

    if s[i]==":":

        ans+=s[i]

        flag=False

    elif s[i]!="0" or flag==True:

        ans+=s[i]

        flag=True

print("原 IPv6 地址为:",s)

print("去前导零后:",ans)

   

Grading:

(1) ans=""; (3 points)

(2) ans+=s[i]; (3 points)

(3)s[i]!="0" or flag==True。(4分)

37. Write a program to calculate the piecewise function. The values ​​of the piecewise function are as shown in the table below. Requirement: You can enter 5 times in a row (that is, enter 5 x values ​​and find the corresponding y value). After finding the y value according to the corresponding expression, convert the result into an integer and add it to list a. Please determine whether the five elements existing in list a are prime numbers. If they are non-prime numbers, they will be converted into tuples and stored in b1. If they are prime numbers, they will be converted into tuples and stored in b2. Output the non-prime numbers in b1 and b2 respectively. Prime numbers and their elements and number of elements.

 

a=[]
a1=[]#暂时存储非素数的值
a2=[]#暂时存储素数的值
b1=()
b2=()
for i in range(5):
    x=int(input("输入x="))
    if x<0:
        y=0
    elif 0<=x<5:
        y=x
    elif 5<=x<10:
        y=3*x-5
    elif 10<=x<20:
        y=0.5*x-2
    elif x>=20:
        y=2*x
            ①        
for  i  in  a:   
    if         ②        :
       a1.append(i)
    else:
        flag=True
        for j in range(2,i):
            if  i%j==0:
                        ③         
                break
        if         ④        :
            a2.append(i)
        else:
            a1.append(i)
b1=tuple(a1)
b2=tuple(a2)                
print("非素数的个数有"+str(len(b1))+"个,","非素数为:",b1)
print("素数的个数有"+str(len(b2))+"个,","素数为:",b2)

Reference procedure:

a=[]
a1=[]#暂时存储非素数的值
a2=[]#暂时存储素数的值
b1=()
b2=()
for i in range(5):
    x=int(input("输入x="))
    if x<0:
        y=0
    elif 0<=x<5:
        y=x
    elif 5<=x<10:
        y=3*x-5
    elif 10<=x<20:
        y=0.5*x-2
    elif x>=20:
        y=2*x
    a.append(int(y))   
for  i  in  a:   
    if  i==0 or i==1:
       a1.append(i)
    else:
        flag=True
        for j in range(2,i):
            if  i%j==0:
                flag=False  
                break
        if flag==True:
            a2.append(i)
        else:
            a1.append(i)
b1=tuple(a1)
b2=tuple(a2)                
print("非素数的个数有"+str(len(b1))+"个,","非素数为:",b1)
print("素数的个数有"+str(len(b2))+"个,","素数为:",b2)

Grading:

(1)a.append(int(y));(2分)

(2)i==0 or i==1;(2分)

(3) flag=False; (3 minutes)

(4) flag==True. (3 minutes)

    Display address: click to browse

38. Given a string str consisting entirely of numeric characters ('0', '1', '2',..., '9'), please write the p-type encoding string of str. For example: the string 1335554668 can be described as "1 1, 2 3s, 3 5s, 1 4, 2 6s, 1 8", so we say that the p-type encoding string of 1335554668 is 112335142618; 00000000000 can be described is "11 0s", so its p-type coding string is 110; similarly, the coding string 101 can be used to describe 1111111111; 110003444225 can be described as "2 1s, 3 0s, 1 3, 3 4s , 2 2s, and 1 5", so its p-type encoding string is 213013342215. If you enter non-numeric characters, it will prompt that the input is invalid.

Based on the above algorithmic ideas, complete the following code.

s=input("请输入字符串str:")
s+=' '
lens=len(s)
for i in range(0,        ①        ,1):
    if '0'<=s[i]<='9':
                ②        
    else:
        print('输入无效!')
        exit()
sum=1
i=0
while i<lens-1:
    if          ③        :
        sum+=1
    else:
        print(sum,end='')
        print(s[i],end='')
                ④        
    i+=1

Reference procedure:

s=input("请输入字符串str:")
s+=' '
lens=len(s)
for i in range(0,lens-1,1):
    if '0'<=s[i]<='9':
        continue
    else:
        print('输入无效!')
        exit()
sum=1
i=0
while i<lens-1:
    if s[i]==s[i+1]:
        sum+=1
    else:
        print(sum,end='')
        print(s[i],end='')
        sum=1
    i+=1

Grading:

(1) lens-1 or equivalent answer; (2 points)

(2) continue or equivalent answer; (2 points)

(3) s[i]==s[i+1] or s[i+1]==s[i] or equivalent answer; (3 points)

(4)sum=1 or equivalent answer. (3 points)

Guess you like

Origin blog.csdn.net/m0_46227121/article/details/131225782