Back-End/Python

[프로그래머스 강의] 파이썬을 파이썬답게

uni2237 2021. 7. 11.
728x90
728x90

파트1. Python 꿀팁

 

def solution(mylist):
    answer = [len(i) for i in mylist]
    return answer

def solution(mylist):
	return list(map(len, mylist))

파트2. 정수 다루기 

 

1. 몫과 나머지 - divmod

divmod를 사용하면 한번에 구할수 있음! ( 작은 숫자 다룰때는 divmod가 느림, 큰수는 빠름!)

print(*divmod(a, b))
# print(a//b, a%b) 랑 같음

 

2. n진법 string -> 10진법 숫자 - int()

int(x, base=10) 함수 사용!

num = '1234'
base = 5
answer = int(num, base)

파트3. Str 다루기 

 

1. 문자열 정렬하기 - ljust, center, rjust (좌측/가운데/우측)

s = '가나다라'
n = 7

s.ljust(n) # 좌측 정렬    '가나다라               '
s.center(n) # 가운데 정렬 '       가나다라        '
s.rjust(n) # 우측 정렬    '               가나다라'

 

2. 알파벳 출력하기 - string 모듈

import string 

string.ascii_lowercase # 소문자 abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase # 대문자 ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_letters # 대소문자 모두 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits # 숫자 0123456789알파벳 출력하기 - string 모듈

파트4. Iterable 다루기 

Iterable : 자신의 멤버를 한번에 리턴할 수 있는 객체 ex) list, str, tuple, dictionary 등

 

1. 원본을 유지한채, 정렬된 리스트 구하기 - sorted

list1 = [3, 2, 1]
list2 = sorted(list1)
# 유지안하고 정렬-> sort(list1)

 

2. 2차원 리스트 뒤집기 - ⭐️zip⭐️

mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = [[], [], []]

for i in range(len(mylist)):
    for j in range(len(mylist[i])):
        new_list[i].append(mylist[j][i])
# new_list : [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

파이썬의 zip과 unpacking -> 리스트를 뒤집을 수 있음

mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = list(map(list, zip(*mylist)))

+) zip ??

zip(*iterables)는 각 iterables 의 요소들을 모으는 이터레이터를 만든다.
튜플의 이터레이터를 돌려주는데, i 번째 튜플은 각 인자로 전달된 시퀀스나 이터러블의 i 번째 요소를 포함

1) 두 리스트를 각 인덱스별로 묶어줌.

mylist = [1, 2, 3]
new_list = [40, 50, 60]
for i in zip(mylist, new_list):
    print (i)

(1, 40)
(2, 50)
(3, 60)

2) 여러개의 Iterable 동시에 가능

list1 = [1, 2, 3, 4]
list2 = [100, 120, 30, 300]
list3 = [392, 2, 33, 1]
answer = []
for number1, number2, number3 in zip(list1, list2, list3):
   print(number1 + number2 + number3)

3) 두개의 리스트를 각각 key, value로 하여 딕셔너리 생성 가능

animals = ['cat', 'dog', 'lion']
sounds = ['meow', 'woof', 'roar']
answer = dict(zip(animals, sounds)) # {'cat': 'meow', 'dog': 'woof', 'lion': 'roar'}

 

 

3. i번째 원소와 i+1번째 원소 - zip

⭐ zip 함수에 서로 길이가 다른 리스트가 인자로 들어오면 길이가 짧은 쪽 까지만 이터레이션이 이루어짐

def solution(mylist):
    answer = []
    for number1, number2 in zip(mylist, mylist[1:]):
        answer.append(abs(number1 - number2)) # i번째와 i+1번째 원소의 차
    return answer

if __name__ == '__main__':
    mylist = [83, 48, 13, 4, 71, 11]    
    print(solution(mylist)) # [35, 35, 9, 67, 60]

 

4. 모든 멤버의 type 변환하기 - map

map -> for 문을 사용하지 않고도 멤버의 타입을 일괄 변환 가능

list1 = ['1', '100', '33']
list2 = list(map(int, list1))

파트5. Sequence Types 다루기 

Sequence Type :  int 타입 인덱스를 통해, 원소를 접근할 수 있는 iterable  ex) list, str, tuple

 

1. sequence 멤버를 하나로 이어붙이기 - join

 str.join(iterable) 사용 !! 

my_list = ['1', '100', '33']
answer = ''.join(my_list)

 

2. 삼각형 별찍기 - sequence type의 * 연산

곱셈 연산 *를 통해 문자열,리스트 반복

n = 5
answer = 'abc' * n
#  'abcabcabcabc ...' 

n = 어쩌고
answer= [123, 456] * n 
# [123, 456, 123, 456, 123 ...]

파트6. Itertools / Collections 모듈

더 많은 팁 : https://realpython.com/python-itertools/ 

 

 

1. 곱집합(Cartesian product) 구하기 - product

import itertools

iterable1 = 'ABCD'
iterable2 = 'xy'
iterable3 = '1234'
print(list(itertools.product(iterable1, iterable2, iterable3)))

# [('A', 'x', '1'), ('A', 'x', '2'), ('A', 'x', '3'), ('A', 'x', '4'), ('A', 'y', '1'), ('A', 'y', '2'), ('A', 'y', '3'), ('A', 'y', '4'), 
# ('B', 'x', '1'), ('B', 'x', '2'), ('B', 'x', '3'), ('B', 'x', '4'), ('B', 'y', '1'), ('B', 'y', '2'), ('B', 'y', '3'), ('B', 'y', '4'), 
# ('C', 'x', '1'), ('C', 'x', '2'), ('C', 'x', '3'), ('C', 'x', '4'), ('C', 'y', '1'), ('C', 'y', '2'), ('C', 'y', '3'), ('C', 'y', '4'), 
# ('D', 'x', '1'), ('D', 'x', '2'), ('D', 'x', '3'), ('D', 'x', '4'), ('D', 'y', '1'), ('D', 'y', '2'), ('D', 'y', '3'), ('D', 'y', '4')]

 

 

2. 2차원 리스트를 1차원 리스트로 만들기 - from_iterable

 

my_list = [[1, 2], [3, 4], [5, 6]]

# 방법 1 - sum 함수
answer = sum(my_list, [])

# 방법 2 - itertools.chain
import itertools
list(itertools.chain.from_iterable(my_list))

# 방법 3 - itertools와 unpacking
import itertools
list(itertools.chain(*my_list))

# 방법 4 - list comprehension 이용
[element for array in my_list for element in array]

# 방법 5 - reduce 함수 이용 1
from functools import reduce
list(reduce(lambda x, y: x+y, my_list))

# 방법 6 - reduce 함수 이용 2
from functools import reduce

# 제한적 사용 - 각 원소 길이 동일할 경우!
# 방법 7 - numpy 라이브러리의 flatten 이용
import numpy as np
np.array(my_list).flatten().tolist()
import operator
list(reduce(operator.add, my_list))

 

 

3. 순열과 조합 - combinations, permutations

순열 : itertools.permutations

조합 : itertools.combinations

import itertools

pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.permutations(pool)))) # 3개의 원소로 수열 만들기
print(list(map(''.join, itertools.permutations(pool, 2)))) # 2개의 원소로 수열 만들기

print(list(map(''.join, itertools.combinations(pool)))) # 3개의 원소로 조합 만들기
print(list(map(''.join, itertools.combinations(pool, 2)))) # 2개의 원소로 조합 만들기

 

4. 가장 많이 등장하는 알파벳 찾기 - Counter

collections.Counter  : 어떤 원소 x가 주어진 시퀀스타입에 몇 번이나 등장하는지 세야 할 때!

import collections
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0]
answer = collections.Counter(my_list)

print(answer[1]) # = 4
print(answer[3])  # = 3
print(answer[100]) # = 0

 


 

파트7. 기타 

 

1. for 문과 if문을 한번에 - List comprehension의 if 문

mylist = [3, 2, 6, 7]
answer = [number**2 for number in mylist if number % 2 == 0]

 

2. flag 대신 for-else 사용하기

flag변수 사용하지 않고 for-else문으로 짧은 코드 + 알아보기 쉬움 !

import math

if __name__ == '__main__':
    numbers = [int(input()) for _ in range(5)]
    multiplied = 1
    flag = True # flag 변수
    for number in numbers:
        multiplied *= number
        if math.sqrt(multiplied) == int(math.sqrt(multiplied)):
            flag = False
            print('found')
            break

    if flag: # flag 변수
        print('not found')

import math

if __name__ == '__main__':
    numbers = [int(input()) for _ in range(5)]
    multiplied = 1
    for number in numbers:
        multiplied *= number
        if math.sqrt(multiplied) == int(math.sqrt(multiplied)):
            print('found')
            break
    else:
        print('not found')

 

3. 두 변수의 값 바꾸기 - swap

a = 3
b = 'abc'

a, b = b, a

 

4. 이진 탐색하기 - binary search

Python의 이진 탐색 모듈, bisect 사용 -> 이진탐색 코드 직접 안짜도 됨!

import bisect
mylist = [1, 2, 3, 7, 9, 11, 33]
print(bisect.bisect(mylist, 3))

 

5. 클래스 인스턴스 출력하기 - class의 자동 string casting

__str__ 메소드를 사용해 class 내부에서 출력 format을 지정할 수 있습니다.

class Coord(object):
    def __init__ (self, x, y):
        self.x, self.y = x, y
    def __str__ (self):
        return '({}, {})'.format(self.x, self.y)

point = Coord(1, 2)
print(point) # (1, 2)

 

6. 가장 큰 수, inf

 inf는 어떤 숫자와 비교해도 무조건 크다고 판정됨

min_val = float('inf')
min_val > 10000000000

# 음수 기호 붙이는 것도 가능
max_val = float('-inf')

 

7. 파일 입출력 간단하게 하기

f = open('myfile.txt', 'r')
while True: # EOF 만날때까지 파일읽기 반복
    line = f.readline()
    if not line: 
        break
    raw = line.split()
    print(raw)
f.close()

with - as 구문을 이용

with open('myfile.txt') as file:
    for line in file.readlines():
        print(line.strip().split('\t'))
1. 파일을 close 하지 않아도 됨 - with - as 블록이 종료되면 파일이 자동으로 close 됨
2. readlines가 EOF까지만 읽으므로, while 문 안에서 EOF를 체크할 필요가 x

 

728x90

댓글