problem-solving-with-algorithms-and-data-structure-usingpython(使用python解决算法和数据结构) -- 算法分析
1. 计算前n个整数的和
def sumOfN(n):
theSum = 0
for i in range(1,n+1):
theSum += i
return theSum
print(sumOfN(10))
解法一
def sumOfN(n):
return (n*(n+1))/2
print(sumOfN(10))
解法二
2. 乱序字符串检查
乱序字符串是指一个字符串只是另一个字符串的重新排列。
例如,'heart' 和 'earth' 就是乱序字符串。'python' 和 'typhon' 也是。
为了简单起见,我们假设所讨论的两个字符串具有相等的长度,并且他们由 26 个小写字母集合组成。
我们的目标是写一个布尔函数,它将两个字符串做参数并返回它们是不是乱序。
def anagramSolution1(s1,s2):
alist = list(s2)
pos1 = 0
stillok = True
while pos1 < len(s1) and stillok:
pos2 = 0
found = False
while pos2 < len(alist) and not found:
if s1[pos1] == alist[pos2]:
found = True
else:
pos2 += 1
if found:
alist[pos2] = None
else:
stillok = False
pos1 += 1
return stillok print(anagramSolution1('abcd', 'dcba'))
解法一:检查

即使 s1,s2 不同,它们都是由完全相同的字符组成的。
所以,我们按照字母顺序从 a 到 z 排列每个字符串,如果两个字符串相同,那这两个字符串就是乱序字符串。 def anagramSolution1(s1,s2):
alist1 = list(s1)
alist2 = list(s2) alist1.sort()
alist2.sort() pos = 0
matches = True while pos < len(s1) and matches:
if alist1[pos] == alist2[pos]:
pos += 1
else:
matches = False
return matches print(anagramSolution1('abcde', 'edcba'))
解法二:排序和比较
首先你可能认为这个算法是 O(n),因为只有一个简单的迭代来比较排序后的 n 个字符。
但是,调用 Python 排序不是没有成本。正如我们将在后面的章节中看到的,排序通常是O(n^2) 或 O(nlogn)。
所以排序操作比迭代花费更多。最后该算法跟排序过程有同样的量级。
算法分析
利用两个乱序字符串具有相同数目的 a, b, c 等字符的事实。
我们首先计算的是每个字母出现的次数。
由于有 26 个可能的字符,我们就用 一个长度为 26 的列表,每个可能的字符占一个位置。
每次看到一个特定的字符,就增加该位置的计数器。
最后如果两个列表的计数器一样,则字符串为乱序字符串。 def anagramSolution1(s1,s2):
c1 = [0]*26
c2 = [0]*26 for i in range(len(s1)):
pos = ord(s1[i]) - ord('a') # ord 函数:返回对应的 ASCII 数值
c1[pos] += 1
for i in range(len(s2)):
pos = ord(s2[i]) - ord('a') # ord 函数:返回对应的 ASCII 数值
c2[pos] += 1
j = 0
stillok = True
while j < 26 and stillok:
if c1[j] == c2[j]:
j += 1
else:
stillok = False
return stillok print(anagramSolution1('apple', 'pleap'))
解法三:计数和比较
同样,这个方案有多个迭代,但是和第一个解法不一样,它不是嵌套的。
两个迭代都是 n, 第三个迭代,比较两个计数列表,需要 26 步,因为有 26 个字母。
一共T(n)=2n+26T(n)=2n+26,即 O(n),我们找到了一个线性量级的算法解决这个问题。
算法分析
3. 生成一个从0开始的n个数字的列表
def test1():
l = []
for i in range(1000):
l = l + [i]
test1
def test2():
l = []
for i in range(1000):
l.append(i)
test2
def test3():
l = [i for i in range(1000)]
test3
def test4():
l = list(range(1000))
test4
列表操作的效率
| 操作 | O()值 |
| index[] | O(1) |
| append | O(1) |
| pop() | O(1) |
| pop(i) | O(n) |
| insert(i,item) | O(n) |
| del operator | O(n) |
| iteration | O(n) |
| contains(in) | O(n) |
| get slice[x:y] | O(k) |
| del slice | O(n) |
| set slice | O(n+k) |
|
reverse |
O(n) |
| concatenate | O(k) |
| sort | O(n*logn) |
| multiply | O(n*k) |
字典操作的效率
| 操作 | O()值 |
| copy | O(n) |
| get item | O(1) |
| set item | O(1) |
| delete item | O(1) |
| contains(in) | O(1) |
| iteration | O(n) |
时间复杂性:https://wiki.python.org/moin/TimeComplexity
总结:
1. 算法分析是一种独立的测量算法的方法
2. 大O表示法允许根据问题的大小,通过其主要部分来对算法进行分类
problem-solving-with-algorithms-and-data-structure-usingpython(使用python解决算法和数据结构) -- 算法分析的更多相关文章
- 学习笔记之Problem Solving with Algorithms and Data Structures using Python
Problem Solving with Algorithms and Data Structures using Python — Problem Solving with Algorithms a ...
- [Algorithms] Tree Data Structure in JavaScript
In a tree, nodes have a single parent node and may have many children nodes. They never have more th ...
- CDOJ 483 Data Structure Problem DFS
Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/proble ...
- [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
- hdu-5929 Basic Data Structure(双端队列+模拟)
题目链接: Basic Data Structure Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 65536/65536 K (Ja ...
- HDU 5929 Basic Data Structure 模拟
Basic Data Structure Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Oth ...
- hdu 4217 Data Structure? 树状数组求第K小
Data Structure? Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) ...
- (*medium)LeetCode 211.Add and Search Word - Data structure design
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
- Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/ Design a data structure tha ...
- 211. Add and Search Word - Data structure design
题目: Design a data structure that supports the following two operations: void addWord(word) bool sear ...
随机推荐
- mysql 数据备份 crontab
每天凌晨 2 点备份数据 crontab -e 0 2 * * * mysqldump ${mysqldir}/bin/mysqldump -h$host -P$port -uadmin -p&qu ...
- 一个钓鱼WiFi的破解
在开始前我们先安装下工具 git clone [url]https://github.com/P0cL4bs/WiFi-Pumpkin.git[/url] [/size] [size=4][size= ...
- [微信小程序]——bug记录
记录日常开发小程序遇到的一些小问题: input 输入框(unfixed) 描述:输入框focus的时候,placeholder会往上面跳动一下 当 scroll-view 遇上 fixed 描述:给 ...
- js有关数组的函数
map()和filter()函数 js的数组迭代器函数map和filter,可以遍历数组时产生新的数组,和python的map函数很类似1)filter是满足条件的留下,是对原数组的过滤(筛选):2) ...
- yolov3源码分析keras(一)数据的处理
一.前言 本次分析的源码为大佬复现的keras版本,上一波地址:https://github.com/qqwweee/keras-yolo3 初步打算重点分析两部分,第一部分为数据,即分析图像如何做等 ...
- 关于C++中操作符重载的疑问 :四个运算符=, ->, [], ()不可以重载为全局函数(友员函数)
转载自:http://blog.csdn.net/u014610226/article/details/47679323 以下是对C++中不能重载为友元函数的四个运算符进行了详细的分析介绍,需 ...
- python开发环境安装配置
需要安装的软件: Python2.7.14和Python3.6.4 要在电脑上同时安装两个版本 开发工具:PyCharm 是一个jetbrains的python开发工具 idea系列之一 Pyt ...
- Python远程连接主机之paramiko模块
Python的paramiko模块能够连接远程主机,并在该主机上执行命令,和该主机之间进行文件传输.paramiko支持用明文密码登录远程主机和秘钥登录.使用之前要安装一下这个模块哈,pip inst ...
- px、pt和em的区别
(转载)http://www.1z1b.com/one-blog-a-week/px-em-pt/ 这里引用的是Jorux的“95%的中国网站需要重写CSS”的文章,题目有点吓人,但是确实是现在国内网 ...
- win10装系统--笔记
U盘安装WIN10时显示 windows无法安装到这个磁盘 选中的磁盘采用GPT分区形式 一.原因分析 win8/win10系统均添加快速启动功能,预装的win8/win10电脑默认都是UEFI引导和 ...