我正在研究一个程序,它将模拟一个为秘密圣诞老人准备的分类帽。我试图让程序有一个错误陷阱,以防止人们得到自己的名字,但是我不能让程序选择一个新的名字,如果有人得到自己的名字。我遇到的另一个问题是程序过早地退出。
这是我的代码:

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)

最佳答案

虽然这可能不是你想要的组织程序的方式,但是这个例子提供了一个防止个人给自己送礼的方法。它使用类似于某些其他语言中可用的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()

关于python - secret 圣诞老人分拣帽,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35369085/

10-11 07:10