• 【使用 Python 实现算法】01 语言特性


    【使用 Python 实现算法】目录

    最近加入了公司同事组织的刷题群,会定期参加 LeetCode 等平台的算法比赛。

    作为一个资深 Pythonist,我一向是使用 Python 来实现各种算法题目的。Python 本身也提供了一些不错的语言特性、内置函数和标准库来更高效简洁的编写各类算法的代码实现。

    本系列博客是我根据个人使用 Python 工作和刷题的经验总结的一些使用 Python 实现各类算法的一些技巧。

    作为系列博客的第一篇文章,本期的主题是 Python 的语言特性。

    解构赋值

    交换两个变量的值是一个很常见的场景,在 C 和 C++语言中,我们需要使用一个临时变量。代码会比较冗长,并且会有微小的性能开销。

    1. int tmp = x;
    2. int x = y;
    3. int y = x;

    利用 Python 的解构赋值特性,我们可以使用一个赋值语句交换两个变量的值。

    x, y = y, x
    

    在算法实现中,解构赋值的一个常见用法是一次初始化多个变量。

    ans, total, n = 0, 0, len(lst)
    

    Python 的解构赋值同样可以用在 for 循环中。

    1. points = [(1, 2), (2, 3), (3, 4)]
    2. for x, y in points:
    3. pass

    我们也可以使用一些更复杂的解构赋值语句。

    1. (x, y), z = (1, 2), 3
    2. assert (x, y, z) == (1, 2, 3)
    3. first, *rest = list(range(5))
    4. assert (first, rest) == (0, [1, 2, 3, 4])

    列表推导式

    使用声明式的列表推导式语法替代命令式的 for 循环,代码的可读性更强,并且有一定的性能提升(Python 解释器对列表推导式有专门的优化)。

    1. # find first num in list nums which test(a) is True
    2. def first(nums: list[int], test: Callable[[int], bool]) -> int:
    3. for num in nums:
    4. if test(num):
    5. return num
    6. def first(nums: list[int], test: Callable[[int], bool]) -> int:
    7. return next(num for num in nums if test(num))

    生成器

    定义一个生成器函数在很多情况下可以避免维护一个可变的列表(或其他容器),使得代码更简洁。

    1. @dataclass
    2. class TreeNode:
    3. val: int
    4. left: Optional["TreeNode"] = None
    5. right: Optional["TreeNode"] = None
    6. # 普通实现的先序遍历
    7. def preorder(root: TreeNode | None) -> list[int]:
    8. ans = []
    9. def dfs(root: TreeNode | None) -> None:
    10. if not root:
    11. return
    12. ans.append(root.val)
    13. dfs(root.left)
    14. dfs(root.right)
    15. dfs(root)
    16. return ans
    17. # 生成器版本的先序遍历
    18. def preorder(root: TreeNode | None) -> list[int]:
    19. def dfs(root: TreeNode | None) -> Generator[int, None, None]:
    20. if not root:
    21. return
    22. yield root.val
    23. yield from dfs(root.left)
    24. yield from dfs(root.right)
    25. return list(dfs(root))

    结构化模式匹配

    结构化模式匹配是 Python 3.10 的新特性,利用好这个特性可以写出更优雅的代码。

    1. # 快速排序的一个概念性实现
    2. def quicksort(arr: list[int]) -> list[int]:
    3. match arr:
    4. case first,:
    5. return [first]
    6. case first, second:
    7. return [first, second] if first <= second else [second, first]
    8. case first, *rest:
    9. return (
    10. quicksort([num for num in rest if num <= first])
    11. + [first]
    12. + quicksort([num for num in rest if num > first])
    13. )

    上是一些我认为可以有效帮助到算法实现的 Python 语言特性,合理利用的话可以为各类算法编写出更高效简洁、可读性强的 Python 代码实现。

    下一篇博客将介绍一些 Python 的内置类型和内置函数在算法实现中的巧妙作用。

  • 相关阅读:
    btc钱包探索纪实
    什么是MySQL的回表?
    【SpringBoot】常用的的各种注解(二):Controller层相关注解
    【R语言】R语言的管道操作符 %>%, %T>%, %$% 和 %<>%
    快速幂,逆元的求解
    美国海运价格,美国专线直达怎么收费?
    后悔怎么没早点看到!腾讯T3整理实战书籍:(Spring MVC +MyBatis快速开发与项目实战pdf)
    酒店报修管理系统哪家好?设备巡检系统对酒店运营有什么帮助?
    Outlook邮箱后缀如何修改?怎么添加后缀?
    羧酸研究:Lumiprobe 磺基花青7二羧酸
  • 原文地址:https://blog.csdn.net/m0_72444380/article/details/125589256