秘密圣诞节计划

时间:2013-10-31 00:49:54

标签: python list random

我们需要创建一个可用于“秘密圣诞老人”游戏的程序:

from random import *
people=[]
while True:
    person=input("Enter a person participating.(end to exit):\n")
    if person=="end": break
    people.append(person)


shuffle(people)
for i in range(len(people)//2):
    print(people[0],"buys for",people[1])

这是我开发的程序。截至目前,如果我输入3个人(例如Bob,Ben,Bill) 它将返回“Ben购买比尔”,没有人买Ben或Bob。我目前正试图让它输出“Bob买Ben,Ben Buys买Bill,Bill买Bob”,但到目前为止还没有成功。如果有人能给我一个暗示/基础来设置它,将不胜感激。另外,如果我的代码中有任何不允许我完成此操作的错误,您能告诉我吗?感谢。

6 个答案:

答案 0 :(得分:6)

首先提示,在i循环中使用0和1之类的常量而不是for是没有意义的。

for i in range(len(people)):
    print(people[i],"buys for",people[(i+1)%(len(people))])

但是,这种实施方式不会为您提供秘密圣诞老人提供的所有可能性。

让我们假设您输入“Alice”,“Bob”,“Claire”,“David”,您永远不会遇到以下情况:

  • Alice购买Bob
  • 鲍勃买爱丽丝
  • Claire为David购买
  • 大卫购买克莱尔

你只能获得circular permutations,即:

  • Alice购买Bob
  • Bob购买Claire
  • Claire为David购买
  • 大卫买爱丽丝

等。

你需要一些额外的工作来制作一个完美的秘密圣诞老人:)

答案 1 :(得分:2)

您正在索引0和1,因此它始终是第一个和第二个人正在打印。你真正想要的是:

shuffle(people)
offset = [people[-1]] + people[:-1]
for santa, receiver in zip(people, offset):
     print(santa, "buys for", receiver)

答案 2 :(得分:0)

假设你有三个人:['Bob', 'Ben', 'Bill']

In [1]: people = ['Bob', 'Ben', 'Bill']

现在,当你得到这个列表的长度时,你的分区为2.这导致:

In [2]: len(people) // 2
Out[2]: 1

这就是为什么你只得到一行输出。

你怎么能得到你想要的秘密圣诞老人结果?以下是一些简单实现方法的提示:

  • 你需要某种方法来确保两个人不被分配到同一个人,而且一个人没有被分配给他或她自己。
  • 这可能意味着可能的买家列表和可能的收件人列表 - 逐个删除它们并找到匹配项,检查人员是否被分配给自己。

答案 3 :(得分:0)

from random import *

prompt = "Enter a person participating.(end to exit):\n"
people = list(iter(lambda:input(prompt), "end"))

shuffle(people)
people.append(people[0])
for i in range(len(people) - 1):
    print(people[i],"buys for", people[i + 1])

示例运行

Enter a person participating.(end to exit):
A
Enter a person participating.(end to exit):
B
Enter a person participating.(end to exit):
C
Enter a person participating.(end to exit):
end
A buys for B
B buys for C
C buys for A

您可以替换

people=[]
while True:
    person=input("Enter a person participating.(end to exit):\n")
    if person=="end": break
    people.append(person)

prompt = "Enter a person participating.(end to exit):\n"
people = list(iter(lambda:input(prompt), "end"))

他们俩都在做同样的事情。 iter函数将继续执行我们传递的函数作为第一个参数,直到第二个值匹配。

然后,你这样做

people.append(people[0])

这是一个圆形的东西,最后一个人必须为第一个人买。 append将在最后插入。

for i in range(len(people) - 1):

我们len(people) - 1,因为如果有n人,则会有n次购买。在这种情况下,我们在最后添加了第一个人,因此我们减去一个人。最后

print(people[i],"buys for", people[i + 1])

每个人都必须为列表中的下一个人购买。因此,people[i]购买people[i + 1]

答案 4 :(得分:0)

我意识到我的回答有点迟了,这是我自己的secret santa project我过去几年一直在使用,我的回答可能有所帮助。我从我的剧本中删除了重要的部分。

def pick_recipient(group,recipients,single_flag):
        for person in group:
                gift = random.choice(recipients)
                if single_flag == 0:
                        while gift in group:
                                gift = random.choice(recipients)
                else:
                        while gift in person:
                                gift = random.choice(recipients)
                mail_list.append( '%s=%s' %(person,gift))
                recipients.remove(gift)
        return recipients

if __name__ == "__main__":
        global mail_list
        mail_list = []

        #create lists of people, group couples at beginning or end of list and the singles opposite
        all_recipients = ['name_1-CoupleA: name_1-CoupleA@gmail.com','name_2-CoupleA: name_2-CoupleA@gmail.com',
                'name_3-CoupleB: name_3-CoupleB@hotmail.com','name_4: name_4CoupleB@hotmail.com',
                'name_5-Single: name_5-Single@gmail.com','name_6-Single: name_6-Single@gmail.com']

        #create couples and lists of singles to make sure couples don't get their other half
        #modify the groups to match the list of people from above
        coupleA = all_recipients [0:2]
        coupleB = all_recipients [2:4]
        single = all_recipients [4:]

        #keep initial list in tact      
        possible_recipients = all_recipients

        #modify the groups to match what the input list is
        possible_recipients = pick_recipient(coupleA,possible_recipients,single_flag=0)
        possible_recipients = pick_recipient(coupleB,possible_recipients,single_flag=0)
        possible_recipients = pick_recipient(single,possible_recipients,single_flag=1)

        print mail_list

答案 5 :(得分:0)

秘密圣诞老人取景器内

https://github.com/savitojs/secret-santa-finder-script

要使用此脚本, 你需要在secret_santa.py文件中添加你正在玩的候选人的名字。 _from和_to列表应相同,以获得更好的结果。

更改_from_to列表

跑步
$ ./secret_santa.py
Hi.. What is your nick name? [ENTER] savsingh
Hey savsingh!, Hold on!! Searching...
Any guess... ?

Your secret santa is: bar
Clear the screen [ENTER]:

所以......

脚本:

#!/usr/bin/python
#===============================================================================
#
#          FILE:  secret_santa.py
# 
#         USAGE:  ./secret_santa.py
# 
#   DESCRIPTION:  It can help you to find your secret santa, add participants name in _from and _to list
# 
#  REQUIREMENTS:  python 2.6+, _from list and _to list should be same to work perfectly.
#        AUTHOR:  Savitoj Singh (savitojs@gmail.com)
#       VERSION:  1.1
#       CREATED:  12/21/2016 05:13:38 AM IST
#      REVISION:  * Initial release
#                 * Fixed minor bugs
#=============================================================================== import random import os import time import sys '''Add participants to list'''
_from = ['bob','foo','bar','savsingh','tom','jack','mac','hex'] '''Add participants to list'''
_to = ['bob','foo','bar','savsingh','tom','jack','mac','hex']


class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

for i in range(len(_from)):
    try:
        user_name = raw_input('Hi.. What is your nick name? [ENTER] ')
        if user_name not in _from and user_name not in _to:
            try:
              print("")
              print(bcolors.FAIL + bcolors.BOLD + "Nick name doesn't seem to be in `_from` or `_to` list" + bcolors.ENDC)
              print(bcolors.HEADER + "\nDo you expect me to look in galaxy ? It may take many x'mas to retrive results :P" + bcolors.ENDC)
              break
            except:
              pass
        else:
            print('Hey ' + bcolors.OKBLUE + bcolors.BOLD + str(user_name) + bcolors.ENDC + '!, Hold on!! Searching...')
            random.shuffle(_from)
            _from.remove(user_name)
            print(bcolors.WARNING + 'Any guess... ?' + bcolors.ENDC)
            print('')
            time.sleep(1)
            a = random.choice(_to)
            while str(a) == str(user_name):
                a = random.choice(_to)
            _to.remove(a)
            print(bcolors.BOLD + 'Your secret santa is: ' + bcolors.ENDC + bcolors.OKGREEN + bcolors.BOLD + str(a) + bcolors.ENDC)
            raw_input('Clear the screen [ENTER]: ')
            os.system('reset')
    except:
        print(bcolors.FAIL + bcolors.BOLD + "\n\nOops!!, Something went wrong..." + bcolors.ENDC)
        sys.exit(1)