数据结构是指相互之间存在着一种或多种关系的数据元素的集合和该集合中数据元素之间的关系组成。
简而言之,数据结构就是设计数据以何种方式组织并存储在计算机中。
比如: 列表、集合与字典都是一种数据结构
# -*- coding: utf-8 -*-
class Stack:
def __init__(self):
self.stack = []
def push(self,element):
self.stack.append(element)
def pop(self):
return self.stack.pop()
#
def get_top(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack) == 0
# stack = Stack()
# stack.push(1)
# stack.push(2)
# stack.push(3)
# print(stack.pop) # 证明后进先出问题
def brace_match(s):
match = {"}":"{", "]":"[", ")":"("}
stack = Stack()
for ch in s:
if ch in {"(", "[", "{"}:
stack.push(ch)
else: # ch in {"}", "]", ")"}
if stack.is_empty(): # 判断栈是不是空
return False
elif stack.get_top() == match[ch]: # 栈顶的元素是否和要找的元素匹配
stack.pop()
else: # stack.get_top() != match[ch] # 如果栈顶位置和其不匹配
return False
# 栈空了
if stack.is_empty():
return True
else: # 栈还有值
return False
print(brace_match(("[{()}(){()}[]({}){}]")))
print(brace_match("[{]"))
# -*- coding: utf-8 -*-
class Queue:
def __init__(self, size):
self.queue = [0 for _ in range(size)] # 创建好一个大小为100的队列
self.size = size
self.rear = 0 # 队尾指针
self.front = 0 # 队首指针
def push(self, element): # 进栈
if not self.is_filled():
self.rear = (self.rear+1) % self.size
self.queue[self.rear] = element
else:
raise IndexError("Queue is filled")
def pop(self): # 出栈
if not self.is_empty():
self.front = (self.front + 1) % self.size
return self.queue[self.front]
else:
raise IndexError("Queue is empty.")
# 判断队空
def is_empty(self):
return self.rear == self.front
# 判断队满
def is_filled(self):
return (self.rear + 1) % self.size == self.front
# 测试
q = Queue(5)
for i in range(4):
q.push(i)
print(q.pop())
q.push(4)
# -*- coding: utf-8 -*-
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-1, y),
lambda x,y: (x, y-1),
lambda x,y: (x, y+1)
]
def maze_path(x1,y1,x2,y2):
stack = []
stack.append((x1,y1))
while(len(stack)>0):
curNode = stack[-1] # 当前的节点
if curNode[0] == x2 and curNode[1] == y2:
#走到终点
for p in stack:
print(p)
return True
# x,y 四个方向 x-1,y; x+1,y; x,y-1; x,y-1; x,y+1
for dir in dirs:
nextNode = dir(curNode[0], curNode[1])
# 如果下一个节点能走
if maze[nextNode[0]][nextNode[1]] == 0:
stack.append(nextNode)
maze[nextNode[0]][nextNode[1]] = 2 # 2 表示为已经走过
break
else:
maze[nextNode[0]][nextNode[1]] = 2
stack.pop()
else:
print("没有路")
return False
maze_path(1, 1, 8, 8)
# -*- coding: utf-8 -*-
class Node:
def __init__(self, item):
self.item = item
self.next = None
# 简单创建链表
# a = Node(1)
# b = Node(2)
# c = Node(3)
# a.next = b
# b.next = c
#
# print(a.next.item)
def create_linklist_head(li):
head = Node(li[0])
for element in li[1:]:
node = Node(element)
node.next = head
head = node
return head
def creat_linklist_tail(li):
head = Node(li[0])
tail = head
for element in li[1:]:
node = Node(element)
tail.next = node
tail = node
return head
def print_linklist(lk):
while lk:
print(lk.item, end=",")
lk = lk.next
lk = create_linklist_head([1, 2, 3])
print_linklist(lk)
lk = creat_linklist_tail([1, 2, 3, 6, 8])
print_linklist(lk)
goods = [(60, 10),(100, 20),(120, 30)] # 每个商品元组表示(价格, 重量)
goods.sort(key=lambda x: x[0]/x[1], reverse=True)
def fractional_backpack(goods, w):
m = [0 for _ in range(len(goods))]
total_v = 0
for i, (prize, weight) in enumerate(goods):
if w >= weight:
total_v += prize
w -= weight
else:
m[i] = w / weight
total_v += m[i] * prize
w = 0
break
return total_v, m
print(fractional_backpack(goods, 50))
(240.0, [0, 0, 0.6666666666666666])
from functools import cmp_to_key
li = [32, 94, 128, 1286, 6, 71]
def xy_cmp(x, y):
if x+y < y+x:
return 1
elif x+y > y+x:
return -1
else:
return 0
def number_join(li):
li = list(map(str, li))
li.sort(key=cmp_to_key(xy_cmp))
return "".join(li)
print(number_join(li))
94716321286128