Python interview questions [question + answer]

I recently encountered a python interview question, the question is relatively simple, and the time is controlled within one hour. The following are the interview questions and answers. The answers do not represent the optimal solution, but some ideas that came to mind at the time, and I will share them with you next.

Table of contents

1. Give the following print results

2. How to delete keys in dictionaries and how to merge two dictionaries

3. Which of the following regular expressions can match www.tencent-inc.com

4. There are some files, the path is as shown below

 module_x.py wants to refer to the method of module_y.py, how to write

 module_z.py wants to refer to the method of module_y.py, how to write

5. Please indicate whether the following program will report an error

6. Write a piece of Python code to delete duplicate elements in a list

7. Given a set of numbers 0,1,2...,n from small to large, find a missing number.

8. Given a string, which may contain "()" and "{}" brackets, please write a program to check whether the brackets of the string appear in pairs.

9. Please write code to implement a [singleton] class MoreFun, requiring that the __init__ function of this class can only be called once

10. Write code to implement the method get_time_in_range

 11. Given an integer array nums and a target value target, please find the two certificates whose sum is the target value in the array, and return their array subscripts. You can assume that there is only one answer for each input. However, the same element of the array cannot be used twice. ​edit


1. Give the following print results

Answer:

12.0 

6.0

This question is very simple. Two functions are defined, and x is used as a parameter to call the two functions and output the results.

Both functions judge whether the incoming list is empty, and the funcA function converts each element in the list to a floating point number using the float() method, and returns the maximum value in the list. Therefore, 12.0 is output.

funcB also converts each element in the list into a floating point number with float. When returning, first sum the list with the sum() method and then divide it by the length of the list. Therefore, the output is 6.0

2. How to delete keys in dictionaries and how to merge two dictionaries

answer:

       Delete key: 1. You can use the del keyword to delete the specified key from the dictionary

       For example, to delete the key "a" from dictA, you can use del dictA['a']

2. You can use the pop() method to delete the specified key. This method can return the value corresponding to the key. If the key does not exist, you can provide a default value as the second parameter of the pop() method.

如,result = dictA.pop('a',None)

      

       Merge dictionaries: 1. You can use the update() method to merge dictionaries.

       For example, dictA. update(dictB). At this time, dictA has merged with dictB.

2. Use the dict() constructor

如,dictA(dictA,**dictB)

3. Which of the following regular expressions can match www.tencent-inc.com

     ^\w+\.\w+\-\w+\.\w+$

     [w]{0,3}.[a-z\-]*.[a-z]+

     [c-w.]{3,10}[.][c-w.][.][a]

     [w][w][w][tencent-inc]+[com]+

     ^\w.*com$

     [w]{3}.[a-z\-]{11}.[a-z]{3}

Let's analyze one by one:

  1. ^\w+\.\w+\-\w+\.\w+$

    • Matches word1.word2-word3.word4strings of the form , each of which consists wordof one or more \w(letters, digits, or underscores).
    • Does not match "www.tencent-inc.com".
  2. [w]{0,3}.[a-z\-]*.[a-z]+

    • Matches any length w(lowercase "w") followed by any character, a string of lowercase letters followed by a hyphen ("-"), followed by a string of lowercase letters.
    • Does not match "www.tencent-inc.com".
  3. [c-w.]{3,10}[.][c-w.][.][a]

    • Matches a character in the range from cto w, a period ("."), a character in the range from cto w, a period ("."), and then a letter a.
    • Does not match "www.tencent-inc.com".
  4. [w][w][w][tencent-inc]+[com]+

    • Matches a string consisting of 3 consecutive lowercase letters w, one or more consecutive "tencent-inc", one or more consecutive "com", but does not match ".".
    • Does not match "www.tencent-inc.com".
  5. ^\w.*com$

    • Matches a string that starts with a letter, number, or underscore and ends with "com". ^Indicates the beginning of the string and $the end of the string.
    • matches "www.tencent-inc.com".
  6. [w]{3}.[a-z\-]{11}.[a-z]{3}

    • Matches 3 consecutive lowercase letters w, an 11-character string of lowercase letters and a hyphen ("-"), followed by a 3-character string of lowercase letters.
    • Does not match "www.tencent-inc.com".

Therefore, the regular expression that matches "www.tencent-inc.com" is:

  • [w][w][w][tencent-inc]+[com]+
  • ^\w.*com$

4. There are some files, the path is as shown below

  •  module_x.py wants to refer to the method of module_y.py, how to write

 答:import moudule_y

  •  module_z.py wants to refer to the method of module_y.py, how to write

Answer: relative import: create an empty __init__.py file in the package,

You can use from..subpackage1 import module_y to import the method of module_y

Absolute path import: from my_package.subpackage1 import y

5. Please indicate whether the following program will report an error

url='http://www.qq.com'

def func():

    print(url)

    url = url.split(".")[1]

    print(url)

if __name__=='__main__':

    func()

 Answer: The program will report an error. url is a global variable, and attempting to modify variables in the global scope inside the func() function will result in an error. Use the global keyword in the function to declare that url is a global variable to avoid error reporting, such as:

url='http://www.qq.com'

def func():

    global url

    print(url)

    url = url.split(".")[1]

    print(url)

if __name__=='__main__':

    func()

6. Write a piece of Python code to delete duplicate elements in a list

Answer: You can use the python built-in function set() to implement. set() is a collection, and duplicate elements are not allowed in the collection. like:

def func(list):

       return list(set(list))

7. Given a set of numbers 0,1,2...,n from small to large, find a missing number.

For example, given nums = [0, 0, 1, 3, 4] returns 2.

Answer: Get the largest number first, then generate a sequence from small to large, and compare the two to get the missing number.
def func(nums):
    num_range = list(range(nums[-1])) # Generate a sequence from small to large
    return set(num_range)-set(nums)

8. Given a string, which may contain "()" and "{}" brackets, please write a program to check whether the brackets of the string appear in pairs.

output:

true: indicates that the parentheses appear in pairs and are nested correctly, or the string has no parentheses.

false: The bracket characters are not used correctly.

Answer: count can count the number of occurrences of a character in a string

def func(str):
    if (str.count('(') != str.count(')')) or (str.count('{') != str.count('}')):
        return False
    else:
        return True

9. Please write code to implement a [singleton] class MoreFun, requiring that the __init__ function of this class can only be called once

answer:

class MoreFun:

    _instance = None  # 类变量,用于保存类的唯一实例

    def __new__(cls, *args, **kwargs):

        if cls._instance is None:

            cls._instance = super().__new__(cls)

        return cls._instance

    def __init__(self):

        if not hasattr(self, '_initialized'):

            self._initialized = True

            # 在这里进行初始化操作,确保__init__函数只被调用一次

10. Write code to implement the method get_time_in_range

Input: time start/end nodes in string form

Output: all integer hour nodes between two time nodes, left closed and right open

>>get_time_in_range( “2018/11/12 21:01:01”, “2018/11/13 01:01:01”)

>>[“2018/11/12/21/”, “2018/11/12/22/”, “2018/11/12/23/”, “2018/11/13/00/” , “2018/11/13/01/” ]

answer:

def get_time_in_range(start_time, end_time):

    time_format = "%Y/%m/%d %H:%M:%S"

    start_datetime = datetime.strptime(start_time, time_format)

    end_datetime = datetime.strptime(end_time, time_format)



    time_in_range = []

    current_datetime = start_datetime

    while current_datetime < end_datetime:

        time_in_range.append(current_datetime.strftime("%Y/%m/%d/%H/"))

        current_datetime += timedelta(hours=1)



    return time_in_range

 11. Given an integer array nums and a target value target, please find the two certificates whose sum is the target value in the array, and return their array subscripts. You can assume that there is only one answer for each input. However, the same element of the array cannot be used twice.

answer:

def func(nums , target):
    n = [] #定义已使用过的元素容器
    for i in range(len(nums)):
        #如果该元素使用过则跳过此次循环
        if nums[i] in n:
            continue
        for j in range(len(nums)):
            if nums[i]+nums[j] == target:
                print(nums[i],nums[j])
                n.append(nums[i])
                n.append(nums[j])
#验证
nums = [2,4,6,8,10,12]
target = 12
func(nums,target)

When dealing with interview questions, we can first guess what the test point of this question is, and answer the answer that the interviewer wants.

The above are the interview questions for today. I wish the students find a suitable job as soon as possible and have a successful career~

If this blog responds well, I will consider publishing a python interview column to answer the doubts of children's shoes, let us make progress together!

Guess you like

Origin blog.csdn.net/m0_62814033/article/details/132047256