2014-05-01 129 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