반응형
https://www.hackerrank.com/challenges/big-sorting/problem
Big Sorting | HackerRank
Sort an array of very long numeric strings.
www.hackerrank.com


난해한 문제는 아니었지만, Python sorting의 특징을 하나 알 수 있었던 문제. 해당 문제 forum을 들어가보면 더 자세히 알 수 있다.
Python에서 int -> str, str -> int 형변환은 연산량이 비싼 편이다. 특히 이 문제처럼 숫자값이 클 경우 연산량이 매우 비싸게 작용한다.
따라서 일반적으로 생각하는 문제해결방법인 '문자열을 숫자로 변환 -> 대소비교 -> 정렬' 식의 연산은 time limit에 걸린다.
대안으로 key = lambda x: (len(x), x)를 사용할 수 있는데, int 형변환보다 훨씬 빠른 연산속도를 보여준다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
import math | |
import os | |
import random | |
import re | |
import sys | |
# Complete the bigSorting function below. | |
def bigSorting(unsorted): | |
return sorted(unsorted,key=lambda x: (len(x), x)) | |
# temp = list(map(str, temp)) | |
if __name__ == '__main__': | |
fptr = open(os.environ['OUTPUT_PATH'], 'w') | |
n = int(input()) | |
unsorted = [] | |
for _ in range(n): | |
unsorted_item = input() | |
unsorted.append(unsorted_item) | |
result = bigSorting(unsorted) | |
fptr.write('\n'.join(result)) | |
fptr.write('\n') | |
fptr.close() |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] Hackerrank. Climbing the Leaderboard (Medium) (0) | 2020.03.12 |
---|---|
[Python] Hackerrank. Sherlock and the Valid String (Medium) (0) | 2020.03.11 |
[Python] Hackerrank. Find the Nearest Clone (Medium) (0) | 2020.03.09 |
[Python] 프로그래머스. 2018 카카오 recruit - 프렌즈4블록 (Level 2) (0) | 2020.03.07 |
[Python] 백준 1890. 점프 (0) | 2020.03.05 |