我正在尝试自学Python,我正在修改代码,这些代码目前在许多翻转中计算头尾数。我想要它计算连续头数。这是我到目前为止的代码。
def coinFlips(numberOfTosses):
Heads = 0
tossNum = 0
while tossNumber < numberOfTosses:
value = random.randint(1,2)
if value == 1:
numHeads = Heads + 1
tossNum = tossNum + 1
return (Heads, numTosses-Heads)
我觉得答案是盯着我的脸,但我无法理解我的生活!
答案 0 :(得分:0)
听起来你想要groupby
个连续的正面和尾部,然后只为头部max
找到len
次投掷的list
1
):
import itertools as it
def coinFlips(numberOfTosses):
flips = (random.randint(1,2) for _ in range(numberOfTosses))
return max(len(list(tosses)) for coin, tosses in it.groupby(flips) if coin == 1)
^ ^ ^^ ^^ ^^ ^^
max len list tosses groupby consecutive only heads