用类快排的方法找寻"第n小"的数,方法找寻,[Python]代码Py
用类快排的方法找寻"第n小"的数,方法找寻,[Python]代码Py
[Python]代码
Python语言: 用类快排的方法找寻"第n小"的数#coding=utf-8## from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269554# 代码描述:# O(n) quicksort style algorithm for looking up data based on rank order.# Useful for finding medians, percentiles, quartiles, and deciles.# Equivalent to data[n] when the data is already sorted.import randomdef select(data, n): "Find the nth rank ordered element (the least value has rank 0)." data = list(data) if not 0 <= n < len(data): raise ValueError('not enough elements for the given rank') while True: pivot = random.choice(data) pcount = 0 under, over = [], [] uappend, oappend = under.append, over.append for elem in data: if elem < pivot: uappend(elem) elif elem > pivot: oappend(elem) else: pcount += 1 if n < len(under): data = under elif n < len(under) + pcount: return pivot else: data = over n -= len(under) + pcount
相关内容
- 计算n*n网格生成树的数目,网格,[Python]代码Py
- python实现统计word的小程序,pythonword小程序,[Python]代码
- HTML颜色和RGB颜色互转,html颜色rgb,[Python]代码Py
- 常见的Python字符串操作和一下小技巧,python字符串,[P
- python中获取按键(跨平台),python获取按键,[Python]代码P
- Python将内容中的Url地址转换成Tinyurl地址,pythontinyurl,
- 计算今天是一年中的第几周,计算一年第几周,[Python]代
- 多线程下载地址检测url_download,多线程url_download,#!/us
- 求素数的快速算法,素数算法,[Python]代码Py
- 组合生成与数量计算(Combinaton generator and counter),,[Pyt
评论关闭