Python 确定骰子卷是否包含某些组合?
我正在用Python编写一个骰子游戏模拟器。我使用一个包含1-6个整数的列表来表示一个滚动。所以我可能会有这样一卷:Python 确定骰子卷是否包含某些组合?,python,algorithm,list,dictionary,dice,Python,Algorithm,List,Dictionary,Dice,我正在用Python编写一个骰子游戏模拟器。我使用一个包含1-6个整数的列表来表示一个滚动。所以我可能会有这样一卷: [1,2,1,4,5,1] 我需要确定一个掷骰是否包含得分组合,例如3个一类、4个一类、2组3个和直道 有没有一种简单的蟒蛇式的方法?我尝试过几种方法,但结果都很混乱。重新组织成一个dict,使用值:count并测试是否存在各种模式。有两种方法: def getCounts(L): d = {} for i in range(1, 7): d[i
[1,2,1,4,5,1]
我需要确定一个掷骰是否包含得分组合,例如3个一类、4个一类、2组3个和直道
有没有一种简单的蟒蛇式的方法?我尝试过几种方法,但结果都很混乱。重新组织成一个dict,使用
值:count
并测试是否存在各种模式。有两种方法:
def getCounts(L):
d = {}
for i in range(1, 7):
d[i] = L.count(i)
return d # d is the dictionary which contains the occurrences of all possible dice values
# and has a 0 if it doesn't occur in th roll
这一款的灵感来自伊格纳西奥·巴斯克斯·艾布拉姆斯和德卡明斯
def getCounts(L):
d = {}
for i in set(L):
d[i] = L.count(i)
return d # d is the dictionary which contains the occurrences of
# all and only the values in the roll
我以前也写过类似的代码(但使用扑克牌)。一定数量的代码蔓延是不可避免的编码游戏的所有规则。例如,查找n-of-a-kind的代码将与查找直线的代码完全不同 首先让我们考虑一下“同类”。正如其他人所建议的,创建一个包含每个元素计数的
dict
。然后:
counts = sorted(d.values())
if counts[-1] == 4:
return four_of_a_kind
if counts[-1] and counts[-2] == 3:
return two_sets_of_three
# etc.
检查直线需要不同的方法。当检查n-of-a-kind时,需要获取计数并忽略值。现在我们需要检查值并忽略计数:
ranks = set(rolls)
if len(ranks) == 6: # all six values are present
return long_straight
# etc.
通常,您应该能够识别具有类似风格的规则,抽象出有助于处理这些规则的代码,然后为每个规则编写几行代码。某些规则可能是完全唯一的,无法与其他规则共享代码。这正是饼干破碎的方式。聪明。在python 2.7(或3.1)中,collections模块中有一个计数器类,它可以为您实现这一点<代码>集合。计数器([1,2,1,4,5,1])的行为类似于
value:count
dictionary。