python實現睡眠排序(sleep sort)
阿新 • • 發佈:2018-11-30
本文主要介紹使用python實現睡眠排序(Sleep Sort)。
import _thread from time import sleep import numpy as np items = [2, 4, 10, 2, 1, 7] # 求平均值 m = np.mean(items) # 求數字位數 length = len(str(m).split('.')[0]) # 計算等待時間的比例 p = np.power(0.1, length -1) # 睡眠排序演算法 def sleep_sort(i): sleep(i * p) print(i) # 測試:方案1 [_thread.start_new_thread(sleep_sort, (i,)) for i in items] import threading # 測試:方案2 [threading.Thread(target=sleep_sort, args=(i,)).start() for i in items]
結果:
[17216, 15444, 15640, 15580, 13060, 16288]
1
2
2
4
7
[None, None, None, None, None, None]
1
2
2
4
7
10