some interview question

  1. The combined dictionary: merge the two dictionaries below a = { "A": 1, "B": 2}, b = { "C": 3, "D": 4}

    dict1 = {"A": 1, "B": 2}
    dict2 = {"C": 3, "D": 4}
    
    # 方式一  **表示打散
    print({**dict1, **dict2})  # *   ** 都表示打散可迭代对象
    
    # 方式二 update方法
    dict1.update(dict2)   # 合并字典
  2. Tuple Operation: How tuples ( "a", "b") and the tuple (1,2), the dictionary becomes { "a": 1, "b": 2}

    # zip的使用
    a = ("a", "b")
    b = (1, 2)
    print(dict(zip(a, b)))
  3. Exchange dictionary of keys and values

    dict1 = {"A": 1, "B": 2}
    res = {k: v for v, k in dict1.items()}
    print(res)
  4. We know that the list can be selected using the slicing of some elements, then how to achieve the same functionality of the object generator type it?

  5. Python exchange two variables

    a,b=b,a

    This is not a tuple unpacked, in exchange of two values ​​at the top of the stack.

  6. read()/readline()/readlines()

    with open('test.txt', 'r', encoding='utf-8') as f:
        text = f.read()
        print(text)
    with open('test.txt', 'r', encoding='utf-8') as f:
        try:
            line = f.readline()
            if line:
                print(line)
        except:
            pass
    with open('test.txt', 'r', encoding='utf-8') as f:
        try:
            lines = f.readlines()  # 全部加载到内存
            for line in lines:
                print(line)
        except:
            pass
  7. json serialization, data types can be supported is str / int / tuple / dict / bool / None, but does not support datetime json serialization.

  8. json serialization encountered Chinese converted to Unicode, you want to keep the Chinese how to do?

    import json
    
    a = json.dumps({"name": "张三"})
    print(a)
    """
    {"name": "\u5f20\u4e09"}
    """
    import json
    
    a = json.dumps({"name": "张三"}, ensure_ascii=False)
    print(a)
    """
    {"name": "张三"}
    """
  9. AB two documents which are letters, read out after a good sort, written in C file inside

    with open('test1.txt', 'r') as f1:
        line1 = f1.readline()
    with open('test2.txt', 'r') as f2:
        line2 = f2.readline()
    line = line1 + line2
    line = sorted(line)
    print(line)
    with open("test3.txt", "a+") as f:
        f.write("".join(line))
    
  10. Seek plus N days based on the current time on the date

    import datetime
    def datetime_operate(num:int):
        now = datetime.datetime.now()
        _new_date=now+datetime.timedelta(days=num)
        # 再将这个数字转换为标准的时间
        new_date = _new_date.strftime("%Y%m%d")
        return new_date
    if __name__=="__main__":
        res = datetime_operate(10)
        print(res)
  11. What is wrong with the following code

    def strappend(num):
        str='first'
        for i in range(num):
            str+=str(i)
        return str

    Questions are as follows:

    1. str is a built-in function, should not be used as variable names.
    2. str is an immutable object, each iteration will occupy the new space, the greater the num, the greater the wasted space into a generator to yield.
    3. From the naming convention in terms of function, function names, use delimiter better.
    def str_append(num):
        s = 'first'
        for i in range(num):
            s += str(i)
            yield s
    
    if __name__ == '__main__':
        for i in str_append(3):
            print(i)
  12. with the statement of the role, to write a piece of code?

    with the statement that the context management protocol, which contains this __enter__and __exit__two methods. statement for the occasion with access to resources, ensuring that regardless of whether an exception occurs during use to perform the necessary cleanup operations, the release of resources, such as files automatically shut down after, thread lock automatically acquired and released.

    class Test:
        def __enter__(self):
            print('__enter__() is called!')
            return self
        def dosomething(self):
            print('do something!')
        def __exit__(self,*args,**kwargs):
            print('__exit__() is called!')
    with Test() as sample:
        sample.dosomething()
  13. Statistics document the number of uppercase letters

    with open('A.txt') as f:
        count=0
        for word in f.read():
            if word.isupper():
                count+=1
        print(count)
  14. Redis basic types

    • string
    • hash
    • list
    • set
    • zset (sorted set: an ordered collection)
  15. Python connection MySQL / MongoDB / Redis

  16. Three database paradigm

  17. Distributed Lock

  18. Redis Affairs

  19. Decorator What is the role? for example?

Decorator is a function, without changing any code changes to the premise of a function to add additional functionality, play a decorative effect.

Scenario:

  • Insert log

  • Performance Testing

  • Transaction Processing

  • Cache

  • Check permissions

    from functools import wraps
    def log(label):
        def decorate(func):
            @wraps(func)
            def _wrap(*args,**kwargs):
                try:
                    func(*args,**kwargs)
                    print("name",func.__name__)
                except Exception as e:
                    print(e.args)
                return _wrap
            return decorate
    @log("info")
    def foo(a,b,c):
        print(a+b+c)
        print("in foo")
    
    if __name__=="__main__":
        foo(1,2,3)
     # mark一下,这个还需要认真琢磨琢磨。

    ------------------

  1. Python garbage collection

    For Python language is concerned, the object type and memory are determined at runtime, which is why we called Python language is dynamically typed reasons.

    Garbage collection:

    • Application counting mechanism
    • Mark - Clear
    • Generational recovery
  2. Magic function __call__how to use?

    class Bar:
        def __call__(self,*args,**kwargs):
            print("in call")
    
    if __name__=="__main__":
        b=Bar()
        b()
  3. Determine a target is a function or method?

    from types import MethodType, FunctionType
    
    
    class Bar:
        def foo(self):
            pass
    
    
    def foo1():
        pass
    
    
    print("foo是函数", isinstance(Bar().foo, FunctionType))
    print("foo是方法", isinstance(Bar().foo, MethodType))
    
  4. The mass participation python is pass by value or address?

    Parameter passing in Python is neither value nor the transfer address pass, pass application object.

  5. Python Metaclass (the metaclass that) Example of use.

  6. What is a monkey patch?

  7. Memory Management

  8. Regular Expressions

  9. enumerate

    enumerate can be an object in the iteration time, and at the same time to get the current index value of the object

    from string import ascii_lowercase
    from string import ascii_uppercase
    s = ascii_uppercase
    for index, value in enumerate(s):
        print(index, value)
    
  10. It lists five standard modules

    • pathlib route operation module
    • urllib network requesting module
    • asyncio Python asynchronous library
    • re a regular expression module
    • itertools operation module number generator
  11. Python exception handling

    try:
        1 / 0
    except Exception as e:
        print(e)
    '''
    division by zero
    '''
  12. The maximum number of recursion in python

    A: The maximum number of defaults to 1000, general computer can only reach 998.

    import sys
    sys.setrecursionlimit(1500)
    # 这个只是修改的Python解释器允许的最大递归次数,此外限制还和OS有关。
  13. Object-oriented mro

    Call the class object mro () method to get their inheritance.

  14. Affirm:

    Python is the assertion statement to achieve this function, the general expression to true, the procedures to be adopted.

    # assert() 断言成功,程序继续执行,断言失败,程序报错。
    # 断言能够帮助别人活着未来的你理解代码
    # 找出程序中逻辑不对的地方
    # 一方面,断言会提醒你某个对象应该处于何种状态
    # 另一方面 ,如果某个时候断言为假,会抛出异常
    def foo(a):
        assert a==2,Exception('不等于2')
        print('ok',a)
    if __name__=='__main__':
        foo(1)
  15. lambda expression is an anonymous function is often used as an argument in the function programming.

  16. 5 include the exception type as well as its meaning Python

    • AttributeError object does not have this property
    • Methods NotImplementedError unfulfilled
    • StopIteration iterator no more value
    • TypeError invalid type of operation
    • IndentationError indentation errors
  17. Sort of the difference between listed and sorted:

    Similarities sorted can be sorted and sort the list of elements, sort () and sorted () is different from that, sort list is rearranged in situ and sorted () is to generate a new list. The method is applied on the sort of the list, sorted can be sorted objects operate all iterations. list sort method returns a list of the existing operation, the built-in function sorted method returns a new list, rather than operation performed on the basis of the original.

  18. Ary issues

    print(int(0b1010))
    print(bin(0xf))
    print(oct(8))
    print(hex(16))
    '''
    10
    0b1111
    0o10
    0x10
    '''



Algorithms and data structures:

  1. Implement a binary function looks with Python

    def binary_search(arr, num):
        n = len(arr)
        left = 0
        right = n - 1  # 最右边的index
        while left <= right:
            mid = (left + right) // 2
            if num == arr[mid]:
                return "index:" + str(mid)
            elif num < arr[mid]:
                right = mid - 1  # 比中间的小
            else:
                left = mid + 1  # 比中间的大
        return False  # 从这个循环里面跳出来说明木有找到,返回False
    
    
    if __name__ == "__main__":
        lst = [1, 3, 4, 5, 7, 100]
        res = binary_search(lst, 7)
        print(res)

Guess you like

Origin www.cnblogs.com/gaofeng-d/p/11442662.html