2017-01-27 23 views
-1

我使用隨機數生成器從隨機列表中選擇一個問題,如果問題已經被回答,它應該跳過並重新滾動,直到它得到一個數字還沒有給出。RNG應該忽略已經給出的分子[Python]

它的工作原理,直到選項變得太有限。它會滾動~4次。如果它還沒有一個以前沒有給出的數字,它會給出一個「索引超出範圍」的錯誤。

樣品:

from random import randint 
counter = 0 # Max value, count the amount of questions in the list 
done = [] # Already been rolled, ignore these values 
list = open('questions.txt').readlines() 

for l in list: 
    counter +=1 

try: 
    # While there are less values in <done> than <counter>, roll and add to list 
    while len(done) < counter: 
     question = randint(1,counter) 
     while question in done: 
      print('Skipped [%i]' % question) # Check if ignored 
      question = randint(1,counter) # Reroll 
     else: 
      # Add to list so it knows the question has already been asked 
      done.append(question) # Add to list with given values 
    else: 
     print('Finished!\n') 
except Exception as e: 
    print(e) # Show error if any 

我不知道我做錯了,請幫助。

謝謝:)

+0

順便說一下,你應該使用'random.sample'。 – TigerhawkT3

+1

您正在尋找的術語是「洗牌」。使用'random.shuffle',然後關閉項目。 – jamesdlin

+1

'random.randint()'包含兩個端點。所以有時你會得到最後一點:超出範圍。使用'randrange()',或者,更好地檢查上面的註釋是否真的pythonic。 –

回答

1

解決方案可能更簡單,你實際上不需要你的櫃檯。

比方說,你有問題的列表:

import random 
questions = ['how are you ?', 'happy now ?', 'Another question ?'] 

然後,你將打印的那些問題之一:

question = random.choice(foo) 
print question 

然後,只需從列表中刪除:

# del questions[questions.index(question)] 
questions.remove(question) 

在這裏,你去! ;)

+1

使用shuffle比刪除列表內的項目更有效,因爲當您刪除除最後一個項目之外的任何項目時,必須將所有後續項目向下移動。當然,這個操作速度很快,因爲它發生在C速度,但如果你不需要它,這樣做仍然是浪費。此外,執行'questions.index(問題)'必須執行列表的線性掃描才能找到該項目。 –

+2

'del questions [questions.index(question)]'是'questions.remove(question)'。 – TigerhawkT3

+0

@ PM2Ring我不明白爲什麼使用shuffle會更好?實際上,我們需要選擇一個不需要再次提問的問題。所以即使使用'shuffle',我們也必須選擇一個問題,然後從原始列表中刪除它。 – iFlo