面试时的一道笔试题,内容如题,使用本身熟悉的语言便可。面试
博主在拿到笔试题的生活想到了好几种实现方式,可是没怎么复习,有些实现方式的细节没记清,最后使用了最绕的冒泡排序的方式完成的,因此写这篇博客记录一下,提醒本身。数组
定义一个数组:函数
a = [1, 2, 3, 4, 2, 1, 4, 1, 1]
from collections import Counter print(Counter(a))
首先转换为字典,转换为“元素-出现次数”对:spa
b = {}
for i in a: b[i] = a.count(i)
m = sorted(b.items(),key=lambda x:x[1],reverse=True)
print m
c = b.items() # b为方法二中的字典,转换为列表 for j in range(len(b)): for i in range(len(b)-j-1): if c[i][1] < c[i+1][1]: c[i] ,c[i+1] = c[i+1],c[i] print c
定义一个数组3d
array=(1 2 4 3 5 3 5)
取出数组全部元素:code
而后将元素间空格转换为换行符:blog
而后先使用sort进行排序(uniq -c 只能对相邻的数据进行统计):排序
再使用uniq进行统计:博客
最后对统计后的数据进行排序:it
echo ${array[*]}|tr " " "\n"|sort|uniq -c|sort -r #-r表示逆序
最终效果以下: