Algorithm/프로그래머스

[프로그래머스/python3] 문자열 내림차순으로 배치하기

구씨언니 2021. 2. 3. 01:01
반응형

문제

문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요.
s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다.

 

제한 사항

  • str은 길이 1 이상인 문자열입니다.

 

입출력 예

 

s return
Zbcdefg gfedcbZ

풀이

def solution(s):
    answer = ''
    answer = answer.join(sorted(list(s),reverse=True))
    
    return answer

사용 메서드

 

1. python join() 메서드

: iterable 한 모든 아이템을 한 개의 string 으로 바꿔줍니다. seperator 역할을 하는 string이 필요합니다.

seperator_string.join(iterable)

 

예제)

myTuple = ("John", "Peter", "Vicky")

# 튜플을 한 개의 string으로 바꿔준 것을 x에 대입함
x = "#".join(myTuple) 

print(x)


"""
실행 결과:
John#Peter#Vicky
"""

 

www.w3schools.com/python/ref_string_join.asp

 

Python String join() Method

Python String join() Method ❮ String Methods Example Join all items in a tuple into a string, using a hash character as separator: myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x) Try it Yourself » Definition and Usage The join() meth

www.w3schools.com

 

2. python sorted() 함수

 

www.w3schools.com/python/ref_func_sorted.asp

 

Python sorted() Function

Python sorted() Function ❮ Built-in Functions Example Sort a tuple: a = ("b", "g", "a", "d", "f", "c", "h", "e") x = sorted(a) print(x) Try it Yourself » Definition and Usage The sorted() function returns a sorted list of the specified iterable object.

www.w3schools.com

 

반응형