067、Python 高阶函数的编写:优质冒泡排序

2024-06-22 15:12

本文主要是介绍067、Python 高阶函数的编写:优质冒泡排序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

以下写了个简单的冒泡排序函数:

def bubble_sort(items: list) -> list:for i in range(1, len(items)):swapped = Falsefor j in range(0, len(items) - 1):if items[j] > items[j + 1]:items[j], items[j + 1] = items[j + 1], items[j]swapped = Trueif not swapped:breakif __name__ == '__main__':nums = [55, 66, 9, 22, 86, 35, 44, 97, 56]bubble_sort(nums)print(nums)  # 输出结果:[9, 22, 35, 44, 55, 56, 66, 86, 97]

上面写法虽然正确排好序了,但初始化变量nums的结果改变了,如果实际应用不需要把初始变量改变,该如何?

优化后:

def bubble_sort(items: list) -> list:items = items[:]  # 把列表数据赋给一个新变量并作为返回值for i in range(1, len(items)):swapped = Falsefor j in range(0, len(items) - 1):if items[j] > items[j + 1]:items[j], items[j + 1] = items[j + 1], items[j]swapped = Trueif not swapped:breakreturn itemsif __name__ == '__main__':nums = [55, 66, 9, 22, 86, 35, 44, 97, 56]print(bubble_sort(nums))  # 输出结果:[9, 22, 35, 44, 55, 56, 66, 86, 97]print(nums)  # 输出结果:[55, 66, 9, 22, 86, 35, 44, 97, 56]  原来值并没有改变

如此修改后初始化变量就可以保留,又可以输出排好序的数据了。

这点是基于以下编程思想:

在我们设计函数的时候,一定要注意函数的无副作用(调用函数不影响调用者)。优化后函数质量提升了。

但是该函数的功能还不够全面,假如我对于排序输出结果既要按升序输出,也要按降调输出,又该如何?

方法就是增加一个布尔值变量:

def bubble_sort(items: list, ascending=True) -> list:  # 增加一个bool变量items = items[:]  # 把列表数据赋给一个新变量并作为返回值for i in range(1, len(items)):swapped = Falsefor j in range(0, len(items) - 1):if items[j] > items[j + 1]:items[j], items[j + 1] = items[j + 1], items[j]swapped = Trueif not swapped:breakif not ascending:items = items[::-1]return itemsif __name__ == '__main__':nums = [55, 66, 9, 22, 86, 35, 44, 97, 56]print(bubble_sort(nums))  # 输出结果:[9, 22, 35, 44, 55, 56, 66, 86, 97]print(bubble_sort(nums, ascending=False))  # 输出结果:[97, 86, 66, 56, 55, 44, 35, 22, 9]

如此,我们就可以通过变量ascending的值来判断按升序还是降序输出结果。

但是优化后的函数还不够好,因为在if items[j] > items[j + 1]:语句存在一定的耦合性。那么又该如何解耦呢?

方法就通过引入函数变量:

def bubble_sort(items: list, ascending: bool = True, gt=lambda x, y: x > y) -> list:  # 增加一个bool变量,并引入一个Lambda函数items = items[:]  # 把列表数据赋给一个新变量并作为返回值for i in range(1, len(items)):swapped = Falsefor j in range(0, len(items) - 1):if gt(items[j], items[j + 1]):  # 通过调用函数做大小比较items[j], items[j + 1] = items[j + 1], items[j]swapped = Trueif not swapped:breakif not ascending:items = items[::-1]return itemsif __name__ == '__main__':nums = [55, 66, 9, 22, 86, 35, 44, 97, 56]print(bubble_sort(nums))  # 输出结果:[9, 22, 35, 44, 55, 56, 66, 86, 97]print(bubble_sort(nums, ascending=False))  # 输出结果:[97, 86, 66, 56, 55, 44, 35, 22, 9]

如此优化后,该函数质量就很高了,功能更全面,灵活性更高。

为什么这么说,看以下应用:


def bubble_sort(items: list, ascending: bool = True, gt=lambda x, y: x > y) -> list:  # 增加一个bool变量,并引入一个Lambda函数"""冒泡排序:param items: 待排序的列表:param ascending:是否使用升序:param gt: 比较两个元素大小的函数:return: 返回排序后列表"""items = items[:]  # 把列表数据赋给一个新变量并作为返回值for i in range(1, len(items)):swapped = Falsefor j in range(0, len(items) - 1):if gt(items[j], items[j + 1]):  # 通过调用函数做大小比较items[j], items[j + 1] = items[j + 1], items[j]swapped = Trueif not swapped:breakif not ascending:items = items[::-1]return itemsif __name__ == '__main__':nums = [55, 66, 9, 22, 86, 35, 44, 97, 56]print(bubble_sort(nums))  # 输出结果:[9, 22, 35, 44, 55, 56, 66, 86, 97]print(bubble_sort(nums, ascending=False))  # 输出结果:[97, 86, 66, 56, 55, 44, 35, 22, 9]words = ['Apple', 'Banana', 'Orange', 'Strawberry', 'Grape', 'Watermelon']print(bubble_sort(words, gt=lambda x, y: len(x) > len(y), ascending=False))# 输出结果 ['Watermelon', 'Strawberry', 'Orange', 'Banana', 'Grape', 'Apple']

如上,当一个列表数字是字符串,我需要把输出结果按字符串长度进行排序输出,那么只需要在调用函数的时候,修改函数变量的函数就可以实现了。

这就是高阶函数!

这篇关于067、Python 高阶函数的编写:优质冒泡排序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1084642

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用