2021藍橋杯(Python)騙分指南

專注的阿熊發表於2021-04-19

Ascii 值轉換

AA=ord('a')      # crd() 函式就是用來返回單個字元的 ascii 值( 0-255

BB=chr(65)       # chr() 函式是輸入一個整數 [0 255] 返回其對應的 ascii 符號

>>>print(AA)

97

>>>print(BB)

'A'

BFS 基本例題

graph={'A':['B','C'],

       'B':['A','C'],

       'C':['B','A'],

       'D':['B','C','E'],

       'E':['D','C','B'],

       'F':['D']}

def BFS(graph,s):

    queue=[]

    queue.append(s)

    seen=[]

    seen.append(s)

    while len(queue)>0:

        vertex=queue.pop(0)

        nodes=graph[vertex]

        for i in nodes:

            if i not in seen:

                queue.append(i)

                seen.append(i)

        print(vertex)

BFS(graph,'E')

>>>

E

D

C

B

A

DFS 基本例題

graph={'A':['B','C'],

       'B':['A','C','D'],

       'C':['B','A','D','E'],

       'D':['B','C','E','F'],

       'E':['D','C'],

       'F':['D']}

def DFS(graph,s):

    stack=[]

    stack.append(s)

    seen=[]

    seen.append(s)

    while len(stack)>0:

        vertex=stack.pop()

        nodes=graph[vertex]

        for i in nodes:

            if i not in seen:

                stack.append(i)

                seen.append(i)

        print(vertex)

DFS(graph,'E')

>>>

E

C

A

B

D

F

BFS 最短路徑問題

graph={'A':['B','C'],

       'B':['A','C','D'],

       'C':['B','A','D'],

       'D':['B','C','E','F'],

       'E':['D','C'],

       'F':['D']}

def BFS(graph,s):

    queue=[]

    queue.append(s)

    seen=[]

    seen.append(s)

    parent={s:None}  

    while len(queue)>0:

        vertex=queue.pop(0)

        nodes=graph[vertex]

        for w in nodes:

            if w not in seen:

                queue.append(w)

                seen.append(w)

                parent[w]=vertex

        #print(vertex)

    return parent    

parent=BFS(graph,'E')          #  E   終點

''' #外匯跟單gendan5.com 輸出從 B E 的最短路徑

v='B'

while v!=None:

    print(v)

    v=parent[v]    

'''

v='B'             #  B     起點

way=[]

while v!=None:

    way.append(v)

    v=parent[v]

print(way,len(way))


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2768781/,如需轉載,請註明出處,否則將追究法律責任。