Python實現常用的數據結構


Python中的數據結構

 

#巧用Python列表特性實現特定數據結構

#棧實現
stack = []
stack.push(x)
stack.pop()
stack[-1]

 

#隊列實現
from collections import deque
queue = deque()
#單向隊列
queue.append(x)
queue.popleft()
#雙向隊列
queue.append(x)
queue.popleft()
queue.appendleft(x)
queue.pop()

 

#環形隊列
#初始
dqueue = []
rear = 0
front = 0
#添加一個數據
front = (front + 1 ) % MaxSize
#一個數據出隊
rear = (rear + 1 ) % MaxSize
#空隊條件
rear == front
#滿隊條件
(rear + 1 ) % MaxSize == front

 

#巧用Python類特性實現特定數據結構

#鏈表實現
class Node(object):
def __init__(self,item=None):
  self.item = item
  self.next = None

def main():
  head = Node(1)
  b = Node(2)
  head.next = b

head -> b -> None

#head為鏈表首部,有無數據都可以
#遍歷鏈表
def traversal(head):
  currNode = head
  while currNode is not None:
    print(currNode.item)
    currNode = currNode.next
#鏈表的插入、刪除
#插入
#p.next = currNode.next
#currNode.next = p
#刪除
#currNode.next = p
#currNode.next = currNode.next.next
#del p

 

#雙向鏈表
class Node(object):
def __init__(self,item=None):
  self.item = itme
  self.next = None
  self.prev = None
#插入
#p.next = currNode.next
#currNode.next.prev = p
#p.prev = currNode
#currNode.next = p
#刪除
#p = currNode.next
#currNode.next = p.next
#p.next.prev = currNode
#del p

 

#鏈表和列表的效率分析
#按元素查找時間復雜度都為O(n)
#按下標查找鏈表時間復雜度為O(n),列表為O(1)
#在某元素后插入數據鏈表時間復雜度為O(1),列表的時間復雜度為O(n)
#刪除某元素鏈表時間復雜度為O(n),列表時間復雜度為O(1)

 


#散列表(Hash表)實現
#它是一種線性存儲的表結構
#首先根據關鍵字k,進過某Hash函數,獲得一個索引值
#然后將該關鍵字存儲到索引值所在的位置

#這也是集合的存儲原理

#對於字典也是類似的
#字典是對每一個key求索引值,索引值對應的位置存放相應的value

#問題一:
#索引值重復
#解決一:線性表每個位置采用鏈表存儲,相同索引值得關鍵字,依次鏈接起來(拉鏈法
#解決二:通過哈希沖突函數得到新的地址(開放地址法)

 


#利用棧解決迷宮問題

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,1,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 mpath(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
        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]] = -1  # 標記為已經走過,防止死循環
                break
        else:#四個方向都沒找到
            maze[curNode[0]][curNode[1]] = -1  # 死路一條,下次別走了
            stack.pop() #回溯
    print("沒有路")
    return False

mpath(1,1,8,8)
View Code


#利用隊列解決迷宮問題

from collections import  deque

mg = [
    [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,1,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 print_p(path):
    curNode = path[-1]
    realpath = []
    print('迷宮路徑為:')
    while curNode[2] != -1:
        realpath.append(curNode[0:2])
        curNode = path[curNode[2]]
    realpath.append(curNode[0:2])
    realpath.reverse()
    print(realpath)

def mgpath(x1, y1, x2, y2):
    queue = deque()
    path = []
    queue.append((x1, y1, -1))
    while len(queue) > 0:
        curNode = queue.popleft()
        path.append(curNode)
        if curNode[0] == x2 and curNode[1] == y2:
            #到達終點
            print_p(path)
            return True
        for dir in dirs:
            nextNode = dir(curNode[0], curNode[1])
            if mg[nextNode[0]][nextNode[1]] == 0:  # 找到下一個方塊
                queue.append((*nextNode, len(path) - 1))
                mg[nextNode[0]][nextNode[1]] = -1  # 標記為已經走過
    return False


mgpath(1,1,8,8)
View Code


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM