Python之数据结构基础
一、数据结构基础
a、什么是数据结构

b、数据结构的分类

c、列表

import random
from timewrap import * def list_to_buckets(li, iteration):
"""
:param li: 列表
:param iteration: 装桶是第几次迭代
:return:
"""
buckets = [[] for _ in range(10)]
for num in li:
digit = (num // (10 ** iteration)) % 10
buckets[digit].append(num)
return buckets def buckets_to_list(buckets):
return [num for bucket in buckets for num in bucket]
# li = []
# for bucket in buckets:
# for num in bucket:
# li.append(num) @cal_time
def radix_sort(li):
maxval = max(li) #
it = 0
while 10 ** it <= maxval:
li = buckets_to_list(list_to_buckets(li, it))
it += 1
return li li = [random.randint(0,1000) for _ in range(100000)]
radix_sort(li)
列表
d、栈

二、栈的Python实现

a、栈的应用——括号匹配为题

def brace_match(s):
stack = []
match = {')':'(', ']':'[', '}':'{'}
match2 = {'(':')', '[':']', '{':'}'}
for ch in s:
if ch in {'(', '[', '{'}:
stack.append(ch)
elif len(stack) == 0:
print("缺少%s" % match[ch])
return False
elif stack[-1] == match[ch]:
stack.pop()
else:
print("括号不匹配")
return False
if len(stack) > 0:
print("缺少%s" % (match2[stack[-1]]))
return False
return True brace_match("[{()[]}{}{}")
括号匹配实现
b、队列


c、队列的实现


d、队列的实现原理——环形队列

e、队列的实现原理——环形队列

f、队列的内置模块

三、栈的应用——迷宫为题



解决思路

from collections import deque maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,1,0,0,1],
[1,0,1,1,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,1,0,1],
[1,1,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1]
] dirs = [
lambda x,y:(x-1,y), #上
lambda x,y:(x,y+1), #右
lambda x,y:(x+1,y), #下
lambda x,y:(x,y-1), #左
] def solve_maze(x1, y1, x2, y2):
stack = []
stack.append((x1,y1))
maze[x1][y1] = 2
while len(stack) > 0: # 当栈不空循环
cur_node = stack[-1]
if cur_node == (x2,y2): #到达终点
for p in stack:
print(p)
return True
for dir in dirs:
next_node = dir(*cur_node)
if maze[next_node[0]][next_node[1]] == 0: #找到一个能走的方向
stack.append(next_node)
maze[next_node[0]][next_node[1]] = 2 # 2表示已经走过的点
break
else: #如果一个方向也找不到
stack.pop()
else:
print("无路可走")
return False def solve_maze2(x1,y1,x2,y2):
queue = deque()
path = [] # 记录出队之后的节点
queue.append((x1,y1,-1))
maze[x1][y1] = 2
while len(queue) > 0:
cur_node = queue.popleft()
path.append(cur_node)
if cur_node[0] == x2 and cur_node[1] == y2: #到终点
real_path = []
x,y,i = path[-1]
real_path.append((x,y))
while i >= 0:
node = path[i]
real_path.append(node[0:2])
i = node[2]
real_path.reverse()
for p in real_path:
print(p)
return True
for dir in dirs:
next_node = dir(cur_node[0], cur_node[1])
if maze[next_node[0]][next_node[1]] == 0:
queue.append((next_node[0], next_node[1], len(path)-1))
maze[next_node[0]][next_node[1]] = 2 # 标记为已经走过
else:
print("无路可走")
return False solve_maze2(1,1,8,8)
迷宫问题

a、队列的应用


def solve_maze2(x1,y1,x2,y2):
queue = deque()
path = [] # 记录出队之后的节点
queue.append((x1,y1,-1))
maze[x1][y1] = 2
while len(queue) > 0:
cur_node = queue.popleft()
path.append(cur_node)
if cur_node[0] == x2 and cur_node[1] == y2: #到终点
real_path = []
x,y,i = path[-1]
real_path.append((x,y))
while i >= 0:
node = path[i]
real_path.append(node[0:2])
i = node[2]
real_path.reverse()
for p in real_path:
print(p)
return True
for dir in dirs:
next_node = dir(cur_node[0], cur_node[1])
if maze[next_node[0]][next_node[1]] == 0:
queue.append((next_node[0], next_node[1], len(path)-1))
maze[next_node[0]][next_node[1]] = 2 # 标记为已经走过
else:
print("无路可走")
return False solve_maze2(1,1,8,8)
迷宫问题——队列实现

四、链表

































import random
from timewrap import * def list_to_buckets(li, iteration):
"""
:param li: 列表
:param iteration: 装桶是第几次迭代
:return:
"""
buckets = [[] for _ in range(10)]
for num in li:
digit = (num // (10 ** iteration)) % 10
buckets[digit].append(num)
return buckets def buckets_to_list(buckets):
return [num for bucket in buckets for num in bucket]
# li = []
# for bucket in buckets:
# for num in bucket:
# li.append(num) @cal_time
def radix_sort(li):
maxval = max(li) #
it = 0
while 10 ** it <= maxval:
li = buckets_to_list(list_to_buckets(li, it))
it += 1
return li li = [random.randint(0,1000) for _ in range(100000)]
radix_sort(li)
列表


def insert_sort(li):
for i in range(1, len(li)):
# i 表示无序区第一个数
tmp = li[i] # 摸到的牌
j = i - 1 # j 指向有序区最后位置
while li[j] > tmp and j >= 0:
#循环终止条件: 1. li[j] <= tmp; 2. j == -1
li[j+1] = li[j]
j -= 1
li[j+1] = tmp def shell_sort(li):
d = len(li) // 2
while d > 0:
for i in range(d, len(li)):
tmp = li[i]
j = i - d
while li[j] > tmp and j >= 0:
li[j+d] = li[j]
j -= d
li[j+d] = tmp
d = d >> 1
练习i——插入
from timewrap import * @cal_time
def binary_search(li, val):
low = 0
high = len(li) - 1
while low <= high:
mid = (low + high) // 2
if li[mid] > val:
high = mid - 1
elif li[mid] < val:
low = mid + 1
else:
return mid
else:
return -1 def find_a(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target <= nums[mid]:
high = mid - 1
else:
low = mid + 1
#[1, 2, 2, 2, 4, 8, 10] if low < len(nums):
return low
else:
return -1 def find_b(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target < nums[mid]:
high = mid - 1
else:
low = mid + 1
if low < len(nums):
return low
else:
return -1 @cal_time
def linear_search(li, val):
try:
return li.index(val)
except ValueError:
return -1 li = [1,2,2,2,4,8,10]
print(find_a(li, 10))
def insert_sort(li):
for i in range(1, len(li)):
# i 表示无序区第一个数
tmp = li[i] # 摸到的牌
j = i - 1 # j 指向有序区最后位置
while li[j] > tmp and j >= 0:
#循环终止条件: 1. li[j] <= tmp; 2. j == -1
li[j+1] = li[j]
j -= 1
li[j+1] = tmp def shell_sort(li):
d = len(li) // 2
while d > 0:
for i in range(d, len(li)):
tmp = li[i]
j = i - d
while li[j] > tmp and j >= 0:
li[j+d] = li[j]
j -= d
li[j+d] = tmp
d = d >> 1
Python之数据结构基础的更多相关文章
- Python新手学习基础之数据结构-对数据结构的认知
什么是数据结构? 数据结构是指:相互之间存在着一种或多种关系的数据元素的集合和该集合中数据元素之间的关系组成. 举个列子来理解这个数据结构: 数据可以比作是书本, 数据结构相当于书架,书存放在书架上, ...
- [0x00 用Python讲解数据结构与算法] 概览
自从工作后就没什么时间更新博客了,最近抽空学了点Python,觉得Python真的是很强大呀.想来在大学中没有学好数据结构和算法,自己的意志力一直不够坚定,这次想好好看一本书,认真把基本的数据结构和算 ...
- 《用Python解决数据结构与算法问题》在线阅读
源于经典 数据结构作为计算机从业人员的必备基础,Java, c 之类的语言有很多这方面的书籍,Python 相对较少, 其中比较著名的一本 problem-solving-with-algorithm ...
- (python数据分析)第03章 Python的数据结构、函数和文件
本章讨论Python的内置功能,这些功能本书会用到很多.虽然扩展库,比如pandas和Numpy,使处理大数据集很方便,但它们是和Python的内置数据处理工具一同使用的. 我们会从Python最基础 ...
- Python :数据结构
LearnPython :数据结构 .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .labe ...
- python的类基础
python类的基础: 1,面向对象的基本概念 类(Class): 用来描述具有相同的属性和方法的对象的集合.它定义了该集合中每个对象所共有的属性和方法.对象是类的实例. 类变量:类变量在整个实例化的 ...
- [转]python与numpy基础
来源于:https://github.com/HanXiaoyang/python-and-numpy-tutorial/blob/master/python-numpy-tutorial.ipynb ...
- Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice)
Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Py ...
- Python入门篇-基础语法
Python入门篇-基础语法 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.编程基础 1>.程序 一组能让计算机识别和执行的指令. 程序 >.算法+ 数据结构= 程 ...
随机推荐
- 前端基于react,后端基于.net core2.0的开发之路(番外篇) 后端使用T4模板,生成某些类
1.介绍 因为开发过程中,有部分类是你加一个模型,就需要去改动的,每次加非常的烦,或者有些类,你只用到了他基类的方法,但是你还必须建一个文件才能调用他基类的方法,也很烦. 这个时候,T4就非常有用了. ...
- Effective Java 第三版——22. 接口仅用来定义类型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Angular02 通过angular-cli来搭建web前端项目
利用angular-cli的常见命令: npm i --save 包名 -> 软件依赖 npm i --save-dev 包名 -> 开发依赖 ng new 项 ...
- Mac 安装 Gradle
首先下载 Gradle 通过官网进行下载 https://gradle.org 下载的文件名可能是 gradle-3.3-bin.zip 解压 将此文件解压到任意位置,如解压到 /usr/local ...
- python子域名收集器
今天心血来潮做了一个子域名收集器.过程是蛋疼啊!这里先感谢一下qpython群的咸鱼大佬,在换页的时候出了点毛病,讲到后面我们就知道了. 思路: 代码开始: 我们要用到的模块是 Requests Bs ...
- Educational Codeforces Round 21(A.暴力,B.前缀和,C.贪心)
A. Lucky Year time limit per test:1 second memory limit per test:256 megabytes input:standard input ...
- React Native学习(四)—— 写一个公用组件(头部)
本文基于React Native 0.52 Demo上传到Git了,有需要可以看看,写了新内容会上传的.Git地址 https://github.com/gingerJY/React-Native-D ...
- JqGrid 多行表头设置
1.我想要统计的效果是这样的 2.只要在初始化表格中加上如下代码就可以了: jQuery("#tbAbroadStatisticByUnit").jqGrid('setGroupH ...
- java finally深入探究
When---什么时候需要finally: 在jdk1.7之前,所有涉及到I/O的相关操作,我们都会用到finally,以保证流在最后的正常关闭.jdk1.7之后,虽然所有实现Closable接口的流 ...
- es6语法部分浏览器支持引发的坑
es2015部分浏览器支持踩的坑 自从es2015出现以来,以其更丰富的api和简介的语法,使得js功能越来越丰富写起来也更便捷.比较早先的时候,浏览器是完全不支持的,我们使用的时候,必须要使用bab ...