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>.程序 一组能让计算机识别和执行的指令. 程序 >.算法+ 数据结构= 程 ...
随机推荐
- Oracle触发bug(cursor: mutex S),造成数据库服务器CPU接近100%
问题现象: 项目反馈系统反应非常缓慢,数据库服务器CPU接近100%! INSERT INTO GSPAudit1712(ID,TypeID,CategoryID,DateTime,UserID,Us ...
- 【ASP.NET Core】在Win 10 的 Linux 子系统中安装 .NET Core
在上一篇文章中,老周扯了一下在 Windows 10 中开启 Linux 子系统,并且进行了一些简单的设置.本篇咱们就往上面安装 .net core . 老周假设你从来没有用过 Linux,所以,接着 ...
- CountDownLatch源码解析
一.CountDownLatch介绍 CountDownLatch是在jdk1.5被引入的,它主要是通过一个计数器来实现的,当在初始化该类的构造函数时,会事先传入一个状态值,之后在执行await方法后 ...
- Codeforces Beta Round #2 A,B,C
A. Winner time limit per test:1 second memory limit per test:64 megabytes input:standard input outpu ...
- 51Nod 1182 完美字符串(字符串处理 贪心 Facebook Hacker Cup选拔)
1182 完美字符串 题目来源: Facebook Hacker Cup选拔 基准时间限制:1 秒 空间限制:1 ...
- POJ 3624 Charm Bracelet(01背包裸题)
Charm Bracelet Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 38909 Accepted: 16862 ...
- 2017ecjtu-summer training #4 UESTC 1584
此题链接 http://acm.uestc.edu.cn/#/problem/show/1584 此题和hdu1541几乎完全一样,我们要先对坐标排序,再进行操作. hdu1541题解 http:// ...
- c++(线性堆栈)
前面我们讲到了队列,今天我们接着讨论另外一种数据结构:堆栈.堆栈几乎是程序设计的命脉,没有堆栈就没有函数调用,当然也就没有软件设计.那么堆栈有什么特殊的属性呢?其实,堆栈的属性主要表现在下面两个方面: ...
- Proxy 那点事儿
---恢复内容开始--- 尊重原创:https://my.oschina.net/huangyong/blog/159788 Proxy,也就是"代理"了.意思就是,你不用去做,别 ...
- 在tomcat中布置项目的介绍(一)
一:为什么要在tomcat中单独布置项目 因为上线到服务器上需要项目的功能之间彼此独立,这个以后我会细说. 二:简单的步骤一个都不能少 conf文件里的配置文件需要配置好:logback.xml文件会 ...