找出数组中出现频率超过一半的数,数组超过一半,有一个乱序的数组,其中有
找出数组中出现频率超过一半的数,数组超过一半,有一个乱序的数组,其中有
有一个乱序的数组,其中有一个数占了一半以上,找出这个数
三种方法: 1.一次遍历,筛掉两个不同的数,其剩余数组中,频率超过一半的数还是超过一半...
2.排序, 选取中间的那个数,即是
3.放到MAP中,选取频率最高的那个数
import randomspecified = 4;# generate standard sampledef f(x): if x%2 == 0 or x%7 == 0:return specified return random.randint(1,100)array = map(f, xrange(0,100))#random.shuffle(array)#print array.count(specified)# findout the value , Tree method to solve the question:def findoutSpecifiedByIterOnce(array): temp = array[0] count = 1 for i in xrange(1, len(array)): if count == 0: temp = array[i] count += 1 continue if temp == array[i]: count += 1 else: count -= 1 #print "show ", temp return tempdef findoutSpecifiedBySort(array): array.sort() return array[len(array)/2]def findoutSpecifiedByMap(array): arrayCountMap = {x : array.count(x) for x in set(array)} return sorted(arrayCountMap.items(), key=lambda arrayCountMap:arrayCountMap[1], reverse=True)[0][0]print findoutSpecifiedByIterOnce(array) == specifiedprint findoutSpecifiedByMap(array) == specifiedprint findoutSpecifiedBySort(array) == specified#该片段来自于http://byrx.net
相关内容
- 3行Python代码解简单的一元一次方程,3行python,solve("
- python直接通过邮件服务器端口发送邮件,python邮件服务
- Python从ftp服务器下载文件的代码,,#coding=utf-
- python操作sqlite的CRUD,pythonsqlitecrud,import sqlit
- Ubuntu,按下ctrl,查询选定的单词,ubuntuctrl,双击或拖选
- Python从URL地址提取文件名,,import osurl
- python从mymailbox.msg获取邮件信息,,import rfc82
- python中访问类的docstring注释的方法,pythondocstring,class
- python一句代码实现全排列,python一句代码,from itertoo
- PyQt界面中用twisted建立server,pyqttwistedserver,这两天在看
评论关闭