some interview question

  1. 合并字典:请合并下面两个字典 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. 元组操作:如何把元组 ("a","b") 和元组 (1,2),变为字典 {"a":1,"b":2}

    # zip的使用
    a = ("a", "b")
    b = (1, 2)
    print(dict(zip(a, b)))
    
  3. 交换字典的键和值

    dict1 = {"A": 1, "B": 2}
    res = {k: v for v, k in dict1.items()}
    print(res)
    
  4. 我们知道对于列表可以使用切片操作进行部分元素的选择,那么如何对生成器类型的对象实现相同的功能呢?

  5. Python交换两个变量的值

    a,b=b,a
    

    这个不是元组解包,在栈的顶端做两个值的交换。

  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序列化,可以支持的数据类型是str/int/tuple/dict/bool/None,而datetime不支持json序列化。

  8. json序列化遇到中文会转换成Unicode,想要保留中文怎么办?

    import json
    
    a = json.dumps({"name": "张三"})
    print(a)
    """
    {"name": "u5f20u4e09"}
    """
    
    import json
    
    a = json.dumps({"name": "张三"}, ensure_ascii=False)
    print(a)
    """
    {"name": "张三"}
    """
    
  9. AB两个文件里面都是字母,读出来排序好后,写在C文件里面

    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. 求在当前时间的基础上加N天后的日期

    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. 下面代码会存在什么问题

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

    问题如下:

    1. str是内置函数,不应该作为变量名。
    2. str是不可变对象,每次迭代都会占用新的空间,num越大,浪费的空间就越大,是yield改成生成器即可。
    3. 从函数命名规范来讲,函数名改用分隔符比较好。
    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语句的作用,写一段代码?

    with语句,即上下文管理协议,这里面包含__enter____exit__两个方法。with语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的清理操作,释放资源,比如文件使用后自动关闭、线程中的锁自动获取和释放。

    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. 统计文件中大写字母的数量

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

    • string
    • hash
    • list
    • set
    • zset(sorted set:有序集合)
  15. Python 连接MySQL/MongoDB/Redis

  16. 数据库三范式

  17. 分布式锁

  18. Redis事务

  19. 装饰器有什么作用?举例说明?

装饰器就是一个函数,在不改变任何代码变动的前提下给一个函数增加额外功能,起到装饰效果。

应用场景:

  • 插入日志

  • 性能测试

  • 事务处理

  • 缓存

  • 权限校验

    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垃圾回收机制

    对于Python语言来讲,对象的类型和内存都是在运行时确定的,这也是我们称Python语言为动态类型的原因。

    垃圾回收机制:

    • 应用计数机制
    • 标记-清除
    • 分代回收
  2. 魔法函数__call__怎么使用?

    class Bar:
    	def __call__(self,*args,**kwargs):
    		print("in call")
    		
    if __name__=="__main__":
    	b=Bar()
    	b()
    
  3. 判断一个对象是函数还是方法?

    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. python的传参是传值还是传址?

    Python中传参既不是传值也不是传地址,传的是对象的应用。

  5. Python中的元类(metaclass)使用举例。

  6. 什么是猴子补丁?

  7. 内存管理

  8. 正则表达式

  9. enumerate

    enumerate可以在迭代一个对象的时候,同时获取当前对象的索引和值

    from string import ascii_lowercase
    from string import ascii_uppercase
    s = ascii_uppercase
    for index, value in enumerate(s):
        print(index, value)
    
    
  10. 列举五个标准模块

    • pathlib 路径操作模块
    • urllib 网络请求模块
    • asyncio Python异步库
    • re 正则表达式模块
    • itertools 操作生成器的一些模块
  11. Python异常处理

    try:
        1 / 0
    except Exception as e:
        print(e)
    '''
    division by zero
    '''
    
  12. python中递归的最大次数

    答:最大次数默认为1000,一般电脑只能达到998。

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

    调用类对象的mro()方法获取其继承关系。

  14. 断言:

    Python中是断言语句实现此功能的,一般表达式为true的情况下,程序才能通过。

    # assert() 断言成功,程序继续执行,断言失败,程序报错。
    # 断言能够帮助别人活着未来的你理解代码
    # 找出程序中逻辑不对的地方
    # 一方面,断言会提醒你某个对象应该处于何种状态
    # 另一方面 ,如果某个时候断言为假,会抛出异常
    def foo(a):
        assert a==2,Exception('不等于2')
        print('ok',a)
    if __name__=='__main__':
        foo(1)
    
  15. lambda表达式是一个匿名函数,在函数编程中经常作为参数使用。

  16. 列举5个Python中的异常类型以及其含义

    • AttributeError 对象没有这个属性
    • NotImplementedError 尚未实现的方法
    • StopIteration 迭代器没有更多的值
    • TypeError 对类型无效的操作
    • IndentationError 缩进错误
  17. 列举sort和sorted的区别:

    相同之处 sort 和 sorted 都可以对列表元素排序,sort() 与 sorted() 的不同在于,sort 是在原位重新排列列表,而 sorted() 是产生一个新的列表。 sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

  18. 进制问题

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



算法和数据结构:

  1. 用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)
    
原文地址:https://www.cnblogs.com/d9e84208/p/11442662.html