[英]Proper use of lists and sets in python
我嘗試在python中編寫先驗算法,當算法必須檢查k維項目集時遇到問題。 到目前為止,我已經編寫了以下代碼:
def A_Priori_Algorithm_Next_Passes(file, freqk, k, s):
input_file = open(file, 'r')
csv_reader = csv.reader(input_file, delimiter=',')
baskets = []
for row in csv_reader:
unique_row_items = set([field.strip().lower() for field in row])
baskets.append(unique_row_items)
input_file.close()
all_items = []
counts = {}
freq = {}
length = len(baskets)
i = 0
while(i < length):
items = GetUniqueItems(baskets[i])
items_list = list(items)
length_1 = len(items_list)
itemset_pairs = GetPairs(freqk)
u = 0
while(u < len(itemset_pairs)):
all_items.append(tuple(itemset_pairs[u]))
u = u + 1
candidates = []
q = 0
while(q < len(itemset_pairs)):
a1 = itemset_pairs[q][0]
a2 = itemset_pairs[q][1]
#print(a1)
#print(a2)
#candidate_sum = a1 + ',' + a2
candidate_set = set(a1).union(set(a2))
candidate = []
candidate.append(candidate_set)
if(tuple(candidate) not in candidates):
candidates.append(tuple(candidate))
if((len(candidate) == (k + 1)) and ((candidate < items) == True)):
#print(candidate)
if(tuple(candidate) not in counts):
counts[tuple(candidate)] = 1
else:
counts[tuple(candidate)] = counts[tuple(candidate)] + 1
q = q + 1
i = i + 1
i = 0
while(i < len(all_items)):
if(all_items[i] in counts):
if(counts[tuple(all_items[i])] >= s):
freq[all_items[i]] = counts[all_items[i]]
i = i + 1
return freq
我的問題是我無法識別何時使用列表以及何時使用集合。 在此if語句中,“ if((len(candidate)==(k + 1))and((candidate <items)== True)):”該程序永遠不會進入。您對我所沒有的了解嗎?不明白嗎? 該算法的偽代碼為:
Algorithm: A-Priori algorithm (k + 1) pass.
Input: F, a file containing baskets
Input: freqk, a table containg the frequencies of itemsets of size k in baskets above the threshold s
Input: k, the size of the itemsets in freqk
Input: s, the support
Output: freq, a table containg the frequencies of itemsets of size k + 1 with threshold s
1 counts ← ∅
2 freq ← ∅
3 foreach basket in F do
4 items ← GetUniqueItems(basket)
5 itemset_pairs = GetPairs(freqk)
6 candidates ← ∅
7 foreach pair in itemset_pairs do
8 (fp,sp) ← pair
9 candidate ← fp ∪ sp
10 if not candidate in candidates then
11 Add(candidates, candidate)
12 if |candidate| = k + 1 and candidate ⊆ items then
13 counts[candidate] ← counts[candidate] + 1
14 foreach itemset, count in counts do
15 if count ≥ s then
16 freq[itemset] = count
17 return freq
提前致謝!
集合對於測試成員資格(如果x在集合中)優越,並且一個集合必須包含可散列的數據,並且不能/將不包含重復項(請嘗試set([1, 1, 3, 4])
1,1,3,4 set([1, 1, 3, 4])
)。 集使許多集理論功能可用,例如交集。 它們添加成員的速度較慢,沒有順序,如果您沒有充分的理由使用set(),通常最好使用list()。 我鼓勵您閱讀set()上的官方python文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.