2016-02-12 60 views
3

我正在研究一個程序,將模擬祕密聖誕老人的排序帽子。我試圖讓程序有一個錯誤陷阱來阻止人們獲取自己的名字,但是我無法讓程序在某人獲得自己的名字時選擇一個新名字。我遇到的另一個問題是該程序過早退出。祕密聖誕老人排序帽子

這裏是我的代碼:

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) 

回答

1

詢問用戶名,然後再使用while循環,以保持獲取隨機的名字,而隨機名稱等於輸入名稱。

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()