본문 바로가기
프로그래밍 문제/[Python] CheckIO

[CheckIO] sort array by element frequency

by Physics 2020. 12. 30.
728x90

Problems: py.checkio.org/en/mission/sort-array-by-element-frequency/

My Solution:

def frequency_sort(items):
    # your code here
    count_value = dict.fromkeys(items)
    count_list = [items.count(x) for x in count_value]
    dict_list = dict(zip(count_value, count_list))
    sort_list = dict(sorted(dict_list.items(), key = (lambda x: x[1]), reverse=True))
    
    new_list = []
    for x in sort_list:
         new_list.extend([x for _ in range(sort_list[x])])
         
    return new_list


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!")

 

A good solution that I see

def frequency_sort(items):
    return sorted(items, key=lambda x: (-items.count(x), items.index(x)))
728x90

'프로그래밍 문제 > [Python] CheckIO' 카테고리의 다른 글

[CheckIO] Sun angle  (0) 2021.01.03
[CheckIO] pawn-brotherhood  (0) 2021.01.02
[CheckIO] Second Index  (0) 2020.12.24
[CheckIO] Popular words  (0) 2020.12.23
[CheckIO] non unique elements  (0) 2020.12.22

댓글