python入门之算法学习
作者:321yu 时间:2021-05-16 19:38:19
前言
参考学习书籍:《算法图解》[美]Aditya Bhargava,袁国忠(译)北京人民邮电出版社,2017
二分查找 binary_search
实现二分查找的python代码如下:
def binary_search(list, item):
low = 0 #最低位索引位置为0
high = len(list)- 1 #最高位索引位置为总长度-1
while low <= high:
mid = (low + high)//2 #检查中间的元素,书上是一条斜杠,我试过加两条斜杠才行
guess = list[mid]#python自动圆整
if guess == item: #找到了元素
return mid
if guess > item: #猜的数字大了,就修改high
high = mid - 1
else: #猜的数字小了,就修改low
low = mid + 1
return None #没有指定的元素
测试代码:
>>> if __name__ == "__main__":#我试过加上好用
my_list=[1,3,5,7,9]
print (binary_search(my_list,3))#把binary_search也加上括号
1#表示3的索引位置为1
>>> if __name__ == "__main__":
my_list=[1,3,5,7,9]
print (binary_search(my_list,0))
None#表示0不在列表中
选择排序 selectionSort()
实现选择排序的python代码如下:
def findSmallest(arr):
smallest = arr[0]
smallest_index =0
for i in range(1,len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index= i
return smallest_index
def selectionSort(arr):
newArr = []
for i in range(len(arr)):
smallest = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr
测试代码:
#样式1,把selcetionSort()作为新的值给arr,打印arr
>>> number=[5,3,6,2,10]
>>> arr=selectionSort(number)
>>> arr
[2, 3, 5, 6, 10]
#样式2,加上if __name__ == '__main__':(我也不知道啥作用)
>>> if __name__ == '__main__':
number=[5,3,6,2,10]
print(selectionSort(number))
[2, 3, 5, 6, 10]
#样式3,直接输出,最简洁
>>> number=[5,3,6,2,10]
>>> print(selectionSort(number))
[2, 3, 5, 6, 10]
来源:https://blog.csdn.net/weixin_53592372/article/details/115863806
标签:python,算法,入门
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python自动化测试selenium指定截图文件名方法
2022-01-03 04:51:49
![](https://img.aspxhome.com/file/2023/6/112946_0s.png)
Python模块的制作方法实例分析
2021-09-06 05:57:26
Python读取配置文件-ConfigParser的二次封装方法
2023-06-15 09:19:58
![](https://img.aspxhome.com/file/2023/1/59651_0s.png)
python变量赋值方法(可变与不可变)
2021-02-14 08:51:55
![](https://img.aspxhome.com/file/2023/9/69559_0s.jpg)
python能自学吗
2023-09-25 09:33:47
Python3爬虫带上cookie的实例代码
2021-11-10 18:06:58
python编写脚本之pyautogui的安装和使用教程
2021-06-17 09:48:11
![](https://img.aspxhome.com/file/2023/8/92498_0s.png)
Python Pandas读取Excel日期数据的异常处理方法
2021-12-10 11:22:55
![](https://img.aspxhome.com/file/2023/6/75386_0s.png)
python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)
2021-05-15 16:25:58
PHP中Trait及其应用详解
2023-11-24 06:33:05
![](https://img.aspxhome.com/file/2023/8/111028_0s.jpg)
Python对象循环引用垃圾回收算法详情
2021-03-02 23:29:14
![](https://img.aspxhome.com/file/2023/6/77706_0s.png)
python 实现提取log文件中的关键句子,并进行统计分析
2022-04-19 06:24:09
两组字符串数据比较合并相同数据
2008-07-31 17:27:00
Python基于回溯法子集树模板解决旅行商问题(TSP)实例
2023-04-27 15:39:32
![](https://img.aspxhome.com/file/2023/5/82665_0s.jpg)
Python探索之Metaclass初步了解
2023-12-22 10:25:37
Python读取txt内容写入xls格式excel中的方法
2023-08-31 22:29:17
Python urllib模块urlopen()与urlretrieve()详解
2022-01-17 02:32:02
JS获取checkbox的个数简单实例
2023-08-20 15:17:55
Python和Pycharm 环境部署详细步骤
2022-09-25 02:25:45
![](https://img.aspxhome.com/file/2023/0/75260_0s.png)
微信小程序-拍照或选择图片并上传文件
2023-09-04 20:22:45
![](https://img.aspxhome.com/file/2023/5/56275_0s.jpg)