我得到了这个DICE拼图来解决,我的思绪被困在一个场景中。
在试验中发生了多少次,恰好两个6
相继滚动?例如,在序列56611166626634416
它发生了两次,恰好两个6
相互抛出。
问题是:如何避免让计数器计算那些666。
注意:我尝试了多个跟踪器(密钥),但后来又遇到了另一个问题:
IndexError:列表索引超出范围
Throws=[6,6,2,6,6,6,3,6,6,3,6,6,6]
Counter_6 = 0
X=0
for i in range (0,len(Throws)):
if i==len(Throws) or i+1>len(Throws) or i+2>len(Throws):
key1= Throws[i]
key2=0
key3=0
elif i+2>=len(Throws):
key1 = Throws[i]
key2 = Throws[i + 1]
key3 = 0
else:
key1=Throws[i]
key2 = Throws[i + 1]
key3 = Throws[i + 2]
print("key 1 is", key1)
print("key 2 is", key2)
print("key 3 is", key3)
if key1==6 and key2==6 and key3!=6 and X==0:
Counter_6 = Counter_6 + 1
X=1
elif key1!=6 and key2 ==6 and key3==6 and X==0:
Counter_6 = Counter_6 + 1
X=1
elif key1==6 and key2==6 and key3==6:
Counter_6 = Counter_6
X=0
print("number of double 6 are: ",Counter_6)
计数器应该等于2
itertools.groupby()
将为您提供更多或更少的连续数字:
from itertools import groupby
throws = [6,6,2,6,6,6,3,6,6,3,6,6,6]
[tuple(v) for k,v in groupby(throws)]
>> [(6, 6), (2,), (6, 6, 6), (3,), (6, 6), (3,), (6, 6, 6)]
你可以将它与collections.Counter
结合起来得到(6,6)
元组的计数:
from itertools import groupby
from collections import Counter
throws = [6,6,2,6,6,6,3,6,6,3,6,6,6]
c = Counter(tuple(v) for k,v in groupby(throws))
c[(6,6)]
>> 2
我能想到的一个更简单的方法是用连续3个六分中的第3个六分,用掷骰子不能出现的整数来标记。例如-1
throws=[6,6,2,6,6,6,3,6,6,3,6,6,6]
counter = 0
for i in range (0, len(throws)-2):
if throws[i] == 6 and throws[i+1] == 6:
if throws[i+2] == 6:
throws[i+2] = -1
print(throws)
#[6, 6, 2, 6, 6, -1, 3, 6, 6, 3, 6, 6, -1]
在此之后,您可以遍历列表,并在遇到两个连续的6并且第三个元素不是-1时增加计数器
for i in range (0, len(throws)-2):
if throws[i] == 6 and throws[i+1] == 6 and throws[i+2] != -1:
counter+=1
print(counter)
#2
这种方法可以肯定。
一种可能的方法是使用正则表达式。通过这种方式,您可以指定精确模式并简单计算它们出现的次数,并且还可以为具有字母或符号的系统的结果提供额外的好处。
import re
throws = [6, 6, 2, 6, 6, 6, 3, 6, 6, 3, 6, 6, 6]
throws_string = "".join(str(x) for x in throws) # Make the list into a string to be able to apply regex to it.
match = re.findall(r"(?:[^6]|\A)(6{2})(?:[^6]|\Z)", throws_string)
assert len(match) == 2
中间(6{2})
中的捕获组匹配我们需要的,并且它周围的非捕获组确保我们不匹配任何3个或更多六个簇。 \A
和\Z
需要匹配字符串的开头和结尾,否则“不是六个”[^6]
将寻找不同的角色并找不到。
请注意,Python中的变量名应该使用snake_case
,而且至关重要的是,第一个字母应该是小写,以区分变量和类名。