python text written because the Internet

Python face questions

python programming

  1. *argsAnd **kwargs参数的含义和使用方法
    * args parameter indicates the position, will accept any number of parameters, and the parameters passed to the function as a tuple,
    using the following example:
    def func(*args):
    	for  i in args:
        	print(i)
    func(8,4,5,1,3)
    
    ** kwargs represents keyword parameter is a parameter for a position in front of the dictionary keyword parameters.
    Use examples:
    def func(**kwargs):
    	for i in kwargs:
       		print(i,kwargs[i])
    func(a=1,b=2,c=3)
    
  2. Describe the difference between python2 and python3, such as the type of inspection
    python2 and python3 have a lot of differences compared to python3 for more rigorous, such as:
    (1) in terms of the type of non-python2 float and have long int, but in python3 only int, long integer no long
    (2) is python2 Print statement, python3 print is a function
    (3) python2 range () returns a list, xrange () returns an iterator. python3 in range () returns an iterator, xrange does not exist
    (4) and python3 added many new features and third-party libraries. For example python3.6 provides a new string formatting method f-Strings.
  3. Please column common python library, and the effect of using a basic example
    (1) request Python's simple and easy to implement Use of HTTP libraries
    (2) virtualenv tool to create a virtual Python environment
    (3) pip Python package and dependency management tool.
    Management Tools (4) SQLAlchemy python database
    rich (5) IPython very effective, perfect python interactive, functional tool
  4. Description python development, coroutines, threads, processes and asyncio the similarities and differences, please write a python program parallel execution on multi-core the CPU
    python in the process is composed of several threads, a process has at least one thread, a thread can also be a number a coroutine.
    Process is the allocation of system resources unit, the thread is a unit of CPU scheduling and allocation of resources required for the process of switching is the largest, low efficiency, resource thread switch requires general efficiency in general,
    coroutine switch tasks resources is very small, high efficiency, multi-process, multi-thread based on the number of cpu core is not as likely to be parallel, but coroutines is in a thread so that concurrent. asyncio provides comprehensive support for asynchronous IO.
    import os
    import sys
    import multiprocessing
    def dump_file(input_dir):
        if not os.path.exists(input_dir):
            print('dir {} not exists'.format(input_dir))
            return
        path_list = [os.path.join(input_dir, f).strip('\n') for f in os.listdir(input_dir)]
        file_path_list = filter(lambda file_path: os.path.isfile(file_path),path_list)
        for file_path in file_path_list:
            print('{}:{} size:{}'.format(os.getpid(), file_path,os.path.getsize(file_path)))
    if __name__ == '__main__':
        pool_size = multiprocessing.cpu_count()
        pool = multiprocessing.Pool(processes=pool_size,)
    for i in range(pool_size):
        if len(sys.argv) > 1:
            pool.apply_async(dump_file, args=(sys.argv[1],))
        else:
            pool.apply_async(dump_file, args=(os.getcwd(),))
        pool.close()
        pool.join()
    

Regular Expressions

  1. re.search and re.match difference between
    the beginning of re.match check whether the string matches if the beginning of the string does not conform to the regular expression, the match fails, the function returns None.
    re.search match the entire string, finds the first matching value in the string, and then return, there is no match, None is returned.
  2. Greedy matching / non-greedy matching difference
    greedy match: match the longest string as
    a non-greedy match: match the shortest possible string
    match are greedy mode by default, if you want to change the non-greedy mode, just behind quantifier with a question mark?.
  3. Please write with a python regular expression matching the following realization and realization of structured data
 acb8af4a-02fb-4aa5-71ae-c3589jfabc0     AC009C    关于公司为全资子公司San Jose  USA, L.L.C.申请融资提供担保的公告    2018-02-29
{
'uuid': 'acb8af4a-02fb-4aa5-71ae-c3589jfabc0',
'code': 'AC009C',
'title': '关于公司为全资子公司San Jose USA,L.L.C.申请融资提供担保的公告',
'date': '2018-02-29'
}
import re
a = 'acb8af4a-02fb-4aa5-71ae-c3589jfabc0  AC009C 关于公司为全资子公司 San Jose  USA, L.L.C.申请融资提供担保的公告   2018-02-29'
ret1 = re.match('[\w]*[\W][\w]*[\W][\w]*[\W][\w]*[\W][\w]*', a)
ret2 = re.sub('[\w]*-[\w]*[\W][\w]*[\W][\w]*[\W][\w]*\s', '', a)
ret3 = re.match('\d{6}', ret2)
ret4 = re.sub('[\d]{6}\s', '', ret2)
ret5 = re.search('\d{4}-\d{2}-\d{2}', ret4)
ret6 = re.sub('\d{4}-\d{2}-\d{2}', '', ret4)
list = {}
list['uuid'] = ret1.group()
list['code'] = ret3.group()
list['title'] = ret6
list['date'] = ret5.group()
print(list)

python debugging method

  1. A program running in the process is to monitor network requirements, database read operation, run correlation algorithm for data write operation, responding to network requests. If the entire process flow is very slow, how to diagnose and monitor
    if the entire flow of the process is relatively slow, time-consuming to view each module, to see which module is based on time-consuming slower, then optimize

  2. How to implement python program set breakpoints and step through how to implement remote debugging (please points and there is no IDE IDE introduced in both cases)
    have PyCharm:
    (1) to set breakpoints: Click behind the line number to generate the breakpoint, click again to cancel the breakpoint
    (2) running the debugger: press "Shift + F9", before running to a breakpoint
    (3) click under "Console" window "Show Python Prompt", you can enter commands into the state
    (4) to enter their To get the variable name
    without IDE:
    single-step debugging Python
    where appropriate, add the following statement, adding endpoint
    Import pdb
    pdb.set_trace ()
    start the program, python -m pdb ** py plus debugging parameters -m pdb.
    enter debug after the mode for debugging the following command (gdb mode bit to the operation in the command line)
    L: where to display the current line;
    n-: single-step operation;
    S: single-step operation, if the current behavior of the function call statement, function proceeds;
    P para_name: para_name print variable values;
    B line_number: setting a breakpoint at the first line of the file line_number;
    R & lt: returns the current function;
    C: skip next endpoint

  3. How python prints the current call stack implementation of
    traceback.print_stack ()

Programming

  1. Flatten the following functions to achieve complete conversion
nested_json = {
    "a": 1,
    "b": [35, 26],
    "c": [{
            "d": [2, 3, 4],
            "e": [
                {
                    "f": 1,
                    "g": 2
                    }
                ]
        }],
    "h": {}
    }

flattened_json = flatten(nested_json)

print(flattened_json)
{'a': 1,
 'b.0': 35,
 'b.1': 26,
 'c.0.d.0': 2,
 'c.0.d.1': 3,
 'c.0.d.2': 4,
 'c.0.e.0.f': 1,
 'c.0.e.0.g': 2,
 'h': {}
}
  1. Using python3 coding, the following complete sorting features:
输入:(9, 2), (3, 7), (7, 8), (3, 5), (1, 9)
输出:(1, 9), (3, 7), (3, 5), (7, 8), (9, 2)

Met: the input is a list of tuples, the group of sorting tuple first, and then in descending order according to a second dimension of tuples sorted in ascending order according to a first dimension of a tuple

# 获取列表的第二个元素
def getSecond(temp):
    return temp[1]
# 列表
temp = [(9, 2), (3, 7), (7, 8), (3, 5), (1, 9)]

# 指定第二个元素排序
result = sorted(temp, reverse=False)
result = sorted(result,key=getSecond,reverse=True)
print('排序列表:', result)

Linux interview questions

  1. The assumption here have a server address is 192.168.0.2, open port 6623, how to connect to a remote server operation?
    ssh [email protected]: 6623

  2. The assumption here have a server address is 192.168.0.2, open port 6623, how the / opt / data file server by copying a local directory?
    scp [email protected] : / opt / the Data / local directory

  3. By python server.pyopened a service, the service is now unresponsive, and ask how to find the process, and kill.
    ps -ef | grep service, find the process kill -9 process ID number

  4. Lists all json file folder, and delete files created yesterday
    find ./ -type f -name '* .json '

  5. How to check whether a port system has been in use by another program
    lsof -i: port number

  6. In the implementation of the Linux command, if only want to save the output to a file, and want to see the output content on the screen, how to deal with
    ./out | tee out.log

  7. git merge git rebase command and command what is the difference, two command What is the impact on the system.
    Branches merge and rebase
    git branch merge # merge the branch to the current branch
    git merge origin / master --no-ff # Do not merge Fast-Foward, which can generate merge submit
    git rebase master # the master rebase to the branch

  8. Listed systems often use the monitor command, including network, CPU, GPU and other usage monitoring
    network monitoring: ethtool view the bandwidth of the NIC netstat test the machine network connection of each port
    CPU monitoring: mpstat real-time system monitoring tool, it will report to the CPU relevant statistical information system in top condition and overall resource usage status of each process
    GPU monitoring: nvidia-smi single view watch -n 10 nvidia-smi: the case of periodic display the GPU and 10 is displayed once every 10 seconds

  9. Nothing to write file system data, issuing a preliminary examination of the file system is writable, but also 30% of the space is not used, there may try to analyze the problem
    most likely a rights issue, followed by a very small probability is full of inode there are many other less likely events, such as too deep a directory, the file name is too long or write command problems and so on itself

  10. How to set up regular tasks, if the scheduled task execution results of the command and the different results of the command executed directly from the command line, consider what the problem might exist
    in LINUX you should first enter the crontab -e, then there will be a vi editing interface, enter 0 3 * * 1 / clearigame2 content into it: wq save and exit.
    In LINUX, the duty cycle is generally performed by the cron daemon to handle [ps -ef | grep cron]. cron read one or more configuration files, the configuration file contains the command line and call time.
    cron configuration file is called "crontab", it is a "cron table" shorthand.
    Directly on the command line is executed in the current shell environment
    such as when it comes to some of the environmental variables must be executed in the current shell environment,
    perform the words in the script when the script execution will fork a child process all operations are conducted in the child
    If it comes to setting up the environment variables in the script ended things script environment variables will disappear

  11. pip installation package is too slow how to deal with, apt command to install the package too slow to deal with how
    to use apt-get, when pip installation tools such as downloading dependencies, because many sources are deployed overseas servers, download speed is unusually slow, often Download timeout error, the situation can not install the software properly,
    you can use the method are:
    (1) using a proxy server
    (2) in the country to find the mirror server, which is the most simple, download the source replacement for domestic mirror source

other:

  1. Please tell us about your technology stack used in the project, feel proud and good, let your headache points and how to solve
    it Recent punch assistant project done SSO single sign-on Weibo, through research and development documentation successful implementation of the project. Have found that start must complete account name and password each time authorization, and finally through the investigation found that the introduction of mandatory parameters logged when you log in,
    then forced landing parameter to forcelogin = false, although a very small point, but it was I thought process what went wrong, looking for a long time. Haha
  2. Please tell us about recently read five books and Why It 5
    (1) algorithm illustrated recently wanted to see algorithms and data structures, algorithms and data structures knowledge of university studies pick up
    (2) Flask Web Development: python-based web application development framework has been used in actual combat since the flask, so take a look at
    (3) To learn more about graphic HTTP and HTTP web
    Linux (4) Bird brother Linux private kitchens While it has been developed with Linux, but still want in-depth look at the system
    ( 5) this is indeed a recent collection of poems Xu watch, small like language, like modern poetry
  3. Please describe your next five-year plan
    in the future 1--2 years, I wish I could go to school in the post to more technical knowledge, continuous efforts to make their professional skills and the ability to get greater improvement. 3--4 years, towards more long-term development of the route, such as AI, big data and artificial intelligence direction or
    can develop slowly towards full stack, architects strive to do after ah, the road ahead will be long Come. . . . .

Guess you like

Origin blog.csdn.net/xili2532/article/details/91509447