-
파이썬을 파이썬답게 (1)개발노트 2019. 9. 2. 22:40
프로그래머스 파이썬을 파이썬답게 강의를 듣고 정리한 글입니다.
1. 몫과 나머지
-몫과 나머지를 공백으로 구분해서 출력합니다.
작성한 코드, 답
a, b = map(int, input().strip().split(' ')) print(a//b, a%b) #5 3 입력 #1 2 출력
물론 위 코드도 정답
파이썬에서는 divmod()를 사용해서 몫과 나머지를 한번에 구합니다.
a = 7 b = 5 print( *divmod(a, b) ) #1 2 출력
*TIP
무조건 divmod를 사용하는 게 좋은 방법은 아닙니다.
가독성이나, 팀의 코드 스타일에 따라서, a//b, a%b와 같이 쓸 때가 더 좋을 수도 있습니다.
또한, divmod는 작은 숫자를 다룰 때는 a//b, a%b 보다 느립니다. 대신, 큰 숫자를 다룰 때는 전자가 후자보다 더 빠르지요.
2. 진법 변환
-base 진법으로 표기된 숫자를 10진법 숫자 출력해보세요.
int(num, base) 형식으로 작성합니다. 10진법이니 base = 10이고 num은 str형식으로 넣어줍니다.
num, base = map(int, input().strip().split(' ')) print(int(str(num), base)) #12 3 입력 #5 출력
3. 문자열 정렬
-문자열 s와 자연수 n이 입력으로 주어집니다. 문자열 s를 좌측 / 가운데 / 우측 정렬한 길이 n인 문자열을 한 줄씩 프린트해보세요.
파이썬에서는 ljust, center, rjust와 같은 string의 메소드를 사용해 코드를 획기적으로 줄일 수 있습니다.
s = 'abc' n = 7 print(s.ljust(n)) # 좌측 정렬 print(s.center(n)) # 가운데 정렬 print(s.rjust(n)) # 우측 정렬 #출력 abc abc abc
4. 알파벳 출력하기
-입력으로 0이 주어지면 영문 소문자 알파벳을, 입력으로 1이 주어지면 영문 대문자 알파벳을 사전 순으로 출력하는 코드를 짜세요.
num = int(input().strip()) import string if num is 0: print(string.ascii_lowercase)# 소문자 abcdefghijklmnopqrstuvwxyz if num is 1: print(string.ascii_uppercase) # 대문자 ABCDEFGHIJKLMNOPQRSTUVWXYZ #string.ascii_letters #대소문자 모두 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #string.digits # 숫자 0123456789
5. 원본을 유지한채, 정렬된 리스트 구하기
파이썬에서는 sorted를 사용해서 list를 자동 정렬 합니다.
>>> list1 = [3, 2, 1] >>> list2 = sorted(list1) >>> list2 [1, 2, 3]