Prepare > Python > Built-Ins > ginortS
ginortS | HackerRank
An uneasy sort.
www.hackerrank.com
문제
you are given a string S.
S contains alphanumeric characters only.
- All sorted lowercase letters are ahead of uppercase letters.
- All sorted uppercase letters are ahead of digits.
- All sorted odd digits are ahead of sorted even digits.
Input Format
A single line of input contains the string S.
Output Format
Output the sorted string S.
=> S에 대해 소문자, 대문자, 홀수, 짝수 순으로 각각 정렬해 출력하라
코드
from collections import defaultdict
S = input()
d = defaultdict(list)
for i in S:
if i.islower():
d['lower'].append(i)
d['lower'].sort()
elif i.isupper():
d['upper'].append(i)
d['upper'].sort()
elif int(i) % 2 != 0:
d['odd'].append(i)
d['odd'].sort()
else:
d['even'].append(i)
d['even'].sort()
print(
''.join(d['lower']) + ''.join(d['upper']) + ''.join(d['odd']) + ''.join(d['even'])
)
노트
문자열을 하나하나 뜯어서 4가지 유형중 어떤건지 판별하고, 정렬해서 합치는 코드...
sorted()로 하고싶은데...어렵다
sorted()의 key 이용
s = input()
print(
"".join(sorted(s,key = lambda x : ( x.isdigit() and not int(x) % 2, x.isdigit() and int(x) % 2, ord(x) in range(65,91) , x)))
)
번외
sort_order = list('abcdefghijklamnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468')
print(
''.join(
sorted(input(), key=lambda x: sort_order.index(x))
)
)
구글 바드의 답변기반 코드
S = input()
S = sorted(S)
def key(x):
if x.islower():
return 0
elif x.isupper():
return 1
elif x.isdigit() and int(x) % 2:
return 2
else:
return 3
print("".join(sorted(S, key=key)))
- sorted()의 key에는 함수를 써야하는데 꼭 lambda 함수를 쓸 필요는 없잖아...?
참조
Prepare > Python > Collections > DefaultDict Tutorial
DefaultDict Tutorial | HackerRank Create dictionary value fields with predefined data types. www.hackerrank.com 문제 Input Format The first line contains integers, n and m separated by a space. The next n lines contains the words belonging to group A. Th
my-little-diary.tistory.com
Sorting HOW TO
Author, Andrew Dalke and Raymond Hettinger,, Release, 0.1,. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a...
docs.python.org