【问题标题】:Secret Santa Sorting Hat秘密圣诞老人分院帽
【发布时间】:2016-05-23 23:39:01
【问题描述】:

我正在开发一个程序,该程序将模拟秘密圣诞老人的分类帽。我试图让程序有一个错误陷阱,以防止人们获得自己的名字,但是如果有人获得自己的名字,我无法让程序选择一个新名字。我遇到的另一个问题是程序一直过早退出。

这是我的代码:

import random
print "Testing Arrays"
Names=[0,1,2,3,4]
#0 - Travis 
#1 - Eric 
#2 - Bob 
#3 - Tim 
#4 - Dhyan
x = 1
z = True
def pick(x):
    while (z == True):
        #test=input("Is your Name Travis?")
        choice = random.choice(Names) #Picks a random choice from Names Array
        if (choice == 0): #If it's Travis
            test=input("Is your Name Travis?") #Asking user if they're Rabbit
            if(test == "Yes"):
                return "Pick Again"
            elif(test== "No"):
                return "You got Travis"
                Names.remove(1)
                break
        elif (choice == 1):
            test=input("Is your Name Eric?")
            if(test=="Yes"):
                return "Pick Again"
            elif(test=="No"):
                Names.remove(2)
                return "You got Eric"
                break

print pick(1)

【问题讨论】:

    标签: python arrays function loops random


    【解决方案1】:

    虽然这可能不是您想要组织程序的确切方式,但该示例提供了一个示例,说明了一种防止个人向自己赠送礼物的方法。它使用类似于某些其他语言中可用的 do/while 循环的东西来确保 targets 满足要求。

    #! /usr/bin/env python3
    import random
    
    
    def main():
        names = 'Travis', 'Eric', 'Bob', 'Rose', 'Jessica', 'Anabel'
        while True:
            targets = random.sample(names, len(names))
            if not any(a == b for a, b in zip(targets, names)):
                break
        # If Python supported do/while loops, you might have written this:
        # do:
        #     targets = random.sample(names, len(names)
        # while any(a == b for a, b in zip(targets, names))
        for source, target in zip(names, targets):
            print('{} will give to {}.'.format(source, target))
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      【解决方案2】:

      先询问用户名,然后使用 while 循环继续获取随机名称,而随机名称等于输入名称。

      【讨论】:

        猜你喜欢
        • 2010-09-21
        • 2013-11-10
        • 2022-01-12
        • 2022-01-15
        • 1970-01-01
        • 2012-01-26
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多