-
holdtom
没脾气,for循环一遍跑不了了.
s = [-175, -842, -187, -66, -1, -1, -148, -17, -32, -35, 35, -1, -1, -1, -278, 278, -432, -92, -25,
549, -666, -45, -547, -38, -7, -101, -28, -43, -31, -4, 1510, -1958, -40, -25, -7, -1, -1, -1, -1, -15]
Max = 0 # 已知最大连续出现次数初始为0
cur_repeat_time = 1 # 记录当前元素是第几次连续出现
pre_element = None # 记录上一个元素是什么
for i in s:
if i == pre_element: # 如果当前元素和上一个元素相同,连续出现次数+1,并更新最大值
cur_repeat_time += 1
Max = max((cur_repeat_time, Max))
else: # 不同则刷新计数器,配置pre
pre_element = i
cur_repeat_time = 1
print(Max)
没审题,原来是要-1出现的次数,那就要在if那里判断是不是等于-1了,计数器初始值也得是0,else也不需要重置pre,直接重置计数器就可以了.
s = [-175, -842, -187, -66, -1, -1, -148, -17, -32, -35, 35, -1, -1, -1, -278, 278, -432, -92, -25,
549, -666, -45, -547, -38, -7, -101, -28, -43, -31, -4, 1510, -1958, -40, -25, -7, -1, -1, -1, -1, -15]
Max = 1 if s else 0 # 已知最大连续出现次数,列表为空则为0
cur_repeat_time = 0 # 记录当前元素是第几次连续出现
for i in s:
if i == -1: # 如果当前元素和上一个元素相同,连续出现次数+1,并更新最大值
cur_repeat_time += 1
Max = max((cur_repeat_time, Max))
else: # 不同则刷新计数器,配置pre
cur_repeat_time = 0
print(Max)
-
千巷猫影
import itertoolss = [-175, -842, -187, -66, -1, -1, -148, -17, -32, -35, 35, -1, -1, -1, -278, 278, -432,-92, -25, 549, -666, -45, -547, -38, -7, -101,-28, -43, -31, -4, 1510, -1958, -40, -25, -7, -1, -1, -1, -1, -15]a=[len(list(v)) for k,v in itertools.groupby(s) if k==-1]print('-1连续出现的最大次数为:%d'%max(a))
-
慕哥6287543
import itertools
s = [-175, -842, -187, -66, -1, -1, -148, -17, -32, -35, 35, -1, -1, -1, -278, 278, -432, -92, -25,
549, -666, -45, -547, -38, -7, -101, -28, -43, -31, -4, 1510, -1958, -40, -25, -7, -1, -1, -1, -1, -15]
print(max([len(list(v)) for k,v in itertools.groupby(s)]))
4
-
达令说
Python实用技法第11篇:找出序列中出现次数最多的元素
-
犯罪嫌疑人X
from collections import Counter
s = [-175, -842, -187, -66, -1, -1, -148, -17, -32, -35, 35, -1, -1, -1, -278, 278, -432, -92, -25,
549, -666, -45, -547, -38, -7, -101, -28, -43, -31, -4, 1510, -1958, -40, -25, -7, -1, -1, -1, -1, -15]
c = Counter(s)
most = c.most_common(1)[0]
print(most[1])