[英]python basics - I am trying to write a function which takes a string(a month) as an input and returns the amount of days in the month
[英]Write an algorithm in Python which takes a prufer code as input and returns the edge set of the tree
在 Python 中編寫一個算法,該算法將 prufer 代碼作為輸入並返回樹的邊緣集。 輸入:一個名為“p”的列表(精簡代碼,零索引)示例:
p = [3,1,0,0,3,2,9,9,2,3]
(可以在代碼塊中定義 prufer 代碼。您不需要編寫接受用戶輸入的 function) Output:名為“edges”的列表(邊緣集_示例:
打印(邊緣)
[[3, 4], [1, 5], [0, 1], [0, 6], [3, 0], [2, 7], [9, 8], [9, 10], [ 2, 9], [3, 2], [3,11]]
我遇到了麻煩。 我怎樣才能獲得“p”的值,以便在“edges”中打印 output?
將序列(剩余部分)中的第一個頂點連接到序列中未出現(剩余部分)的最低頂點。 刪除序列中的第一個頂點並重復。 連接剩下的兩個頂點。
def decode(p):
p = list(p)
vertices = set(range(len(p) + 2))
while p:
v = min(vertices - set(p))
vertices.remove(v)
yield p.pop(0), v
yield min(vertices), max(vertices)
print(list(decode([3, 1, 0, 0, 3, 2, 9, 9, 2, 3])))
David Eisenstat 的出色算法。 一些挑剔:
.pop(0)
在列表上是線性的:我希望通過用for... enumerate
替換while
來使列表遍歷更加明確;.difference()
不需要將第二個操作數轉換為集合;min()
和max()
有點矯枉過正,因為我們知道剩下的集合正好有兩個元素。def decode(p):
p = list(p)
vertices = set(range(len(p) + 2))
for (i, u) in enumerate(p):
v = min(vertices.difference(p[i:]))
vertices.remove(v)
yield u, v
yield tuple(vertices)
print(list(decode([3, 1, 0, 0, 3, 2, 9, 9, 2, 3])))
給定相應的長度為 n-2 的 Prufer 序列,可以使用以下算法(參考this )在 n 個標記的頂點上構造生成樹:
下一個代碼片段實現了上述算法,以在給定 Prufer 序列的情況下生成標記樹(通過計算邊)(還請注意,我們在python
中有從零開始的索引):
def get_tree(S):
n = len(S)
L = set(range(n+2))
tree_edges = []
for i in range(n):
u, v = S[0], min(L - set(S))
S.pop(0)
L.remove(v)
tree_edges.append((u,v))
tree_edges.append((L.pop(), L.pop()))
return tree_edges
在輸入的 Prufer 序列上調用上述 function 將生成以下樹,如下面的 animation 所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.