題目
本題是對一個給定的序列進(jìn)行排序袜硫,排序的方式為:
- 對序列中出現(xiàn)的元素贰镣,按照頻率從高到低的順序排練
- 對于頻率相同的元素鼎文,其先后順序保持和原序列中一致
- 如下例子中Frequency_sort為需要編寫的函數(shù)
frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]) == [4, 4, 4, 4, 6, 6, 2, 2]
frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob']) == ['bob', 'bob', 'bob', 'carl', 'alex']
代碼思路
- 先對序列中的元素出現(xiàn)的頻率進(jìn)行統(tǒng)計(jì)槽棍,考慮到collections模塊中的Counter函數(shù)可以進(jìn)行相關(guān)的統(tǒng)計(jì)冀自,返回的一個Counter對象,如下例子
In [1]: from collections import Counter
In [2]:Counter([1,2,3,4,4,4,3,6,6,6,6,9,0])
Out[2]:Counter({1: 1, 2: 1, 3: 2, 4: 3, 6: 4, 9: 1, 0: 1})
- 然后厨相,利用Counter對象的most_common方法可以實(shí)現(xiàn)按照頻率進(jìn)行排序
In [3]: Counter([1,2,3,4,4,4,3,6,6,6,6,9,0]).most_common()
Out[3]: [(6, 4), (4, 3), (3, 2), (1, 1), (2, 1), (9, 1), (0, 1)]
- 最后對這個Couter對象進(jìn)行處理
我的代碼
from collections import Counter
def frequency_sort(items):
a = []
b = Counter(items).most_common()
for i in b:
a += [i[0]]*i[1]
return a
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]
assert list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex']
assert list(frequency_sort([17, 99, 42])) == [17, 99, 42]
assert list(frequency_sort([])) == []
assert list(frequency_sort([1])) == [1]
print("Coding complete? Click 'Check' to earn cool rewards!")
其他人的代碼
代碼1:
from collections import OrderedDict
def frequency_sort(items):
return [i[0] for i in sorted(OrderedDict({i: items.count(i) for i in items}).items(), key=lambda x: x[1], reverse=True) for n in range(i[1])]
代碼2:
def frequency_sort(items):
from collections import Counter
return [i for x, c in Counter(items).most_common() for i in [x] * c]
代碼3:
def frequency_sort(items):
return sorted(sorted(items, key=lambda x: items.index(x)), key=items.count, reverse=True)