2014-05-01 126 views
3

我有兩個變量:「分數」和「獎金」,都初始化爲0.每次分數增加5時,我都希望獎勵增加1.我嘗試過使用itertools 。重複,但我無法使它工作。基於另一個變量增加一個變量

最初的想法:如果分數是5的倍數,並且至少是5,然後按1

if score>=5 and score%5==0: 
    bonus += 1 

增加獎金不幸的是,這是行不通的,因爲我們不斷遞增永遠的獎金。換句話說,當分數是5時,獎勵變爲1。 。 。然後2。 。 。等等,沒有限制。

想法:記錄分數;如果得分是5的倍數,並且至少是5,那麼檢查我們是否已經看過5的倍數。如果我們之前沒有看到過這個5的倍數,那麼將獎勵增加1。現在我們可以避免重複計數。

if score>=5 and score%5==0:

for x in range(5,score+1,5): 
     score_array_mults_of_5 = [] 
     score_array_mults_of_5.append(x) 
     for i in score_array_mults_of_5: 
      if (i in range(5,score-5,5))==False: 
       for _ in itertools.repeat(None, i): 
        bonus += 1 

。 。 。除了這個實現也是雙重計數並且不起作用。

我已閱讀StackExchange,Python文檔,現在我已經嘗試了兩個小時的自己的解決方案。請幫忙。

編輯:謝謝大家。所有有用的答案。

對於那些詢問還有什麼會影響獎金的人:如果用戶按下鍵盤按鈕,則獎金減1。我沒有提及那部分,因爲它似乎不相關。

+0

除了分數還有什麼影響獎金?這種關係不僅僅是「獎金=分數// 5」嗎? – kojiro

+0

工作。非常感謝 - 有沒有一些「接受答案」按鈕?我已閱讀過關於此的內容,但我沒有看到它。 – Comedyguy

+0

單擊答案旁邊的複選框 – aruisdante

回答

0

你可以只讓bonusscore/5

>>> score = bonus = 0 
>>> score+=5 
>>> bonus = score/5 
>>> bonus 
1 
>>> score+=5 
>>> score+=5 
>>> score+=5 
>>> score+=5 
>>> score 
25 
>>> bonus = score/5 
>>> bonus 
5 
>>> 

這是證明的一種方式:

>>> while True: 
...  try: 
...    print 'Hit ^C to add 5 to score, and print score, bonus' 
...    time.sleep(1) 
...  except KeyboardInterrupt: 
...    score+=5 
...    bonus = score/5 
...    print score, bonus 
... 
Hit ^C to add 5 to score, and print score, bonus 
Hit ^C to add 5 to score, and print score, bonus 
^C5 1 
Hit ^C to add 5 to score, and print score, bonus 
Hit ^C to add 5 to score, and print score, bonus 
^C10 2 
Hit ^C to add 5 to score, and print score, bonus 
^C15 3 
Hit ^C to add 5 to score, and print score, bonus 
^C20 4 
Hit ^C to add 5 to score, and print score, bonus 
^C25 5 
Hit ^C to add 5 to score, and print score, bonus 
^C30 6 
Hit ^C to add 5 to score, and print score, bonus 
^C35 7 
Hit ^C to add 5 to score, and print score, bonus 
Hit ^C to add 5 to score, and print score, bonus 
... 

爲了把這個在你的代碼,你只要把bonus = int(score/5)以後每次score已被添加到。

+0

謝謝,如果我先看過這個,我會選擇這個。非常有幫助,非常感謝。 – Comedyguy

+0

你可以通過再次點擊綠色的檢查來改變接受,但沒有壓力:) –

1

嗯,你總是可以簡單地做

bonus = int(score/5). 

這也將保證獎金下降,如果分數確實(如果可能的話,你想要的行爲)

但你也可以用你的第一隻要你只做更新的比分,而不是每個比賽週期都執行檢查。

+1

'int()'在這裏是不必要的,除非'score'將會是一個十進制(不太可能),因爲python會自動舍入。 –

+0

@ aj8uppal *顯式優於隱式*。更好的是'int(score // 5)'。 – kojiro

+0

確實。如果''score''不知何故變成了''float'',而沒有轉換爲''int''就會中斷。 – aruisdante