我对我的第四个函数LongestRun
有疑问。我想根据用户输入的翻转次数(n)输出最长的头部和最长的尾部。我尝试了很多不同的东西,它似乎没有用。你能帮助我吗?:
def LongestRun(n):
H = 0
T = 1
myList = []
for i in range(n):
random.randint(0,1)
if random.randint(0,1) == H:
myList.append('H')
else:
myList.append('T')
我希望下一篇文章输出两件事。
"最长的头是:"然后无论运行时间最长 头是。
"最长的尾巴是:"无论最长的运行时间 尾巴是。
请帮帮我!感谢你们!
答案 0 :(得分:4)
from itertools import groupby
my_list = [1,1,0,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,1]
max(len(list(v)) for k,v in groupby(my_list) if k==1)
是一种有趣的方法,可以对连续值进行分组,然后计算最长的1,如果您要使用" H / T"而只是改变最后的if条件
答案 1 :(得分:0)
跟踪最长的序列,在比较当前与最长序列后重置每个序列:
def LongestRun(n):
my_t, my_h = 0, 0
long_h, long_t = 0, 0
for i in range(n):
if not random.randint(0, 1):
my_h += 1
# if we have heads, check current len of tails seq and reset
if my_t > long_t:
long_t = my_t
my_t = 0
else:
# else we have tails, check current len of heads seq and reset
my_t += 1
if my_h > long_h:
long_h = my_h
my_h = 0
print("Longest run of heads was {}\nLongest run of tails was {}".format(long_h, long_t))
输出:
In [4]: LongestRun(1000)
Longest run of heads was 11
Longest run of tails was 13
In [5]: LongestRun(1000)
Longest run of heads was 7
Longest run of tails was 10
In [6]: LongestRun(1000)
Longest run of heads was 13
Longest run of tails was 8
答案 2 :(得分:0)
我想有一种方法比我的解决方案具有更高的性能,但它可以满足您的需求:
您还可以使用列表而不是np.arrays执行以下操作:
import numpy as np
n = 100
choices = ['H', 'T']
HT_array = np.random.choice(choices, n) # creates a n dimensional array with random entries of H and T
max_h = 0
max_t = 0
count_h = 0
count_t = 0
for item in HT_array:
if item == 'H':
count_h += 1
count_t = 0
if count_h > max_h:
max_h = count_h
elif item == 'T':
count_t += 1
count_h = 0
if count_t > max_t:
max_t = count_t
打印(max_t) 打印(max_h)
答案 3 :(得分:0)
我没有那么优化的版本:
def LongestRun(myList, lookFor='H'):
current_longest = 0
max_longest = 0
for x in myList:
if x == lookFor:
current_longest+=1
if current_longest > max_longest:
max_longest = current_longest
else:
current_longest=0
return max_longest
myList = 'H H H H H T H T H T T H T T T T T T H H H H H H H H H H H H H T'.split()
print LongestRun(myList)
print LongestRun(myList, 'T')
答案 4 :(得分:0)
正如@khuderm建议的那样,一个解决方案是有一个计数器来跟踪当前的头部或尾部运行,以及两个跟踪每个运行的最大运行的变量。
以下是流程应该是什么样的:
counter
,max_H
和max_T
初始化为零,'H'
或'T'
时,将counter
增加1 counter
后,如果相应的最大值小于counter
,则将max更新为counter
的值。 'H'
,现在是'T'
或反面,请将counter
重置为零。