显示连续出现次数最多的数字

时间:2018-05-29 11:02:54

标签: python python-3.x algorithm list

如何编写程序,向我显示最常显示并排的项目?

示例:

6 1 6 4 4 4 6 6

我想要四个,而不是六个,因为只有两个六个一起。

这是我尝试的(来自评论):

c = int(input())
h = [] 
for c in range(c):
    h.append(int(input()))
final = []
n = 0    
for x in range(c-1):
    c = x
    if h[x] == h[x+1]:
        n+=1
        while h[x] != h[c]:
            n+=1
        final.append([h[c],n])
print(final)        

2 个答案:

答案 0 :(得分:2)

取决于您想要输入的内容,例如

lst = [1, 1, 1, 2, 2, 2, 2, 1, 1, 1]

如果您认为最常见的四个2,因为它是相同项目中最长的不间断延伸,那么您可以groupby相同的值并选择max的值} len

max((len(list(g)), k) for k, g in itertools.groupby(lst))
# (4, 2)  # meaning 2 appeared 4 times

如果您对自身旁边最常出现的元素感兴趣,可以zip列表获取相邻项目对,过滤那些相同的项目,通过Counter传递它们,并获得most_common

collections.Counter((x,y) for (x,y) in zip(lst, lst[1:]) if x == y).most_common(1)
# [((1, 1), 4)]  # meaning (1,1) appeared 4 times

对于6 1 6 4 4 4 6 6的示例,两者都将返回4

答案 1 :(得分:0)

 maxcount=0; //store maximum number item side by side
num=-1; //store element with max count 
 for i=0 to n //loop through your array
        count=0; 
        in=i;
        while(arr[in++]==arr[i]){//count number of side by side same element
           count++;
        }
        maxcount=max(maxcount,count);
        num= maxcount==count? arr[i]:num;
        i=in-1;
endfor;