2016-02-03 26 views
1

我想寫一個腳本,配對男性和女性的祕密聖誕老人類型的事件。所以我有兩個男孩和女孩的名單,並且想要進行2路匹配,但目前我似乎只能弄清楚如何做1路匹配。祕密聖誕老人遊戲的雙向匹配

此外,我遇到的問題是這個...在下面的例子中,如果Kedrick得到Annabel,那麼Annabel不能得到Kedrick。 Kedrick必須從名單中找到其他人。

我目前的實施情況如下,如何擴展其功能以滿足上述要求?

boys = ['Kedrick','Jonathan','Tim','Philip','John','Quincy']; 
girls = ['Annabel','Janet','Jocelyn','Pamela','Priscilla','Viviana']; 

matches = [] 

for i in boys: 
    rand - randint(0, len(girls-1) 
    fullname = "{} matched with {}".format(i, girls(rand) 
    del girls(rand) 
    matches.append(fullname) 

print matches 
+4

一個小技巧只是[ 'shuffle']( https://docs.python.org/3/library/random.html#random.shuffle)列表之一併按索引映射。它更容易 –

+0

Kedrick和Tim如何連接?還是隻是錯字? – Lafexlos

+0

@Lafexlos他們之間沒有任何聯繫 – methuselah

回答

2

這可能可以用更少的循環和更少的代碼完成,但這裏是我的解決方案!創建了2個字典來存儲名稱和目標(字典可以同時組合或完成,以減少內存問題,但對於這個大小的程序,我認爲您不會遇到這個問題!

boys = ['Kedrick','Jonathan','Tim','Philip','John','Quincy']; 
girls = ['Annabel','Janet','Jocelyn','Pamela','Priscilla','Viviana']; 

matchesBoys = {i:{'to':''} for i in boys} 
matchesGirls = {i:{'to':''} for i in girls} 

for name in boys: 
    giveTo = girls[random.randint(0, len(girls)-1)] 
    girls.remove(giveTo) 
    matchesBoys[name]['to']=giveTo 

for name in matchesGirls: 
    giveTo = boys[random.randint(0, len(boys)-1)] 
    boys.remove(giveTo) 
    matchesGirls[name]['to']=giveTo 

del boys, girls 
for i in matchesBoys: 
    print "%s matched with %s"%(i, matchesBoys[i]['to']) 
for i in matchesGirls: 
    print '%s matched with %s'%(i, matchesGirls[i]['to']) 
1

將這兩個列表隨機洗並放入一個環中,每個其他元素來自第一個或第二個列表。每個人都會向右邊的人贈送禮物。類似於這樣的列表的東西:

[Girl, Boy, Girl, Boy, ..., Boy] 

最後一個元素給第一個禮物。

它的工作原理是這兩個表中的元素數量相同,並且總共至少有四個元素,否則問題無法解決。

這給出了一個解決方案,可以滿足您的約束條件。該問題的一般解決方案是在每個頂點恰好具有兩個邊緣,一個入口和一個出口的集合之間找到定向bipartite graph。也許這個問題的解決方案也總是會產生一個響鈴?

+0

我幾乎可以肯定,我的最後一句話是真實的,但我把它作爲一個練習給讀者:-) –

0

這是創建具有替代男孩和女孩一圓實現見@Emil Vickstom的回答爲理念的解釋

from random import shuffle 
boys = ['Kedrick','Jonathan','Tim','Philip','John','Quincy']; 
girls = ['Annabel','Janet','Jocelyn','Pamela','Priscilla','Viviana']; 

shuffle(boys) 
shuffle(girls) 
circle = [person for pair in zip(boys, girls) for person in pair] 
print(' -> '.join(circle + circle[:1])) 

輸出:。

Tim -> Priscilla -> Quincy -> Annabel -> John -> Janet -> Kedrick -> Jocelyn -> Philip -> Pamela -> Jonathan -> Viviana -> Tim