2017-08-09 37 views
2

我的代碼大部分工作完美,唯一我無法弄清楚是三種。如果出現三個相同的數字,則它們會相加得到分數。這是我現在擁有的那部分代碼。我必須在Python中製作一個Yahtzee遊戲。其他的工作,但我不能得到三種工作

def threeOfOne(dicelst): 
    total = 0 
    for die in dicelst: 
     if dicelst[0] == dicelst[1:3]: 
      total += die 
     elif dicelst[1] == dicelst[2:5]: 
      total += die 
     else: 
      total = 0 
     return total 

我覺得我缺少一些非常簡單的東西,但我不能得到它的工作它總是顯示零。

+0

您正在比較單個值與列表! – ti7

+0

https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical – Lafexlos

回答

0

在你的函數中,你正在檢查單個值是否等於一個列表!

>>> dicelst = [1,3,5,4,2] 
>>> dicelst[0] 
1 
>>> dicelst[1:3] 
[3, 5] 

嘗試檢查每個count列表

def threeOfOne(dicelst): 
    for die in dicelst: 
     if dicelst.count(die) >= 3: # only if there are at least three matches 
      return die * dicelst.count(die) 
    return 0 

這裏死了,是我相信的表情解決您的問題

def threeOfOne(dicelst): 
    return sum(x for x in dicelst if dicelst.count(x) >= 3) 

由此,在dicelst其中出現的所有值至少三次

  • (x for x in y)它迭代Ÿ
  • dicelst.count(x)數乘以x的數字出現在dicelst
  • sum(iterable)發電機表達式添加在包含列表一切(或其他可迭代)

如果您需要整整三的種類,只需檢查計數== 3

相關問題