본문 바로가기

강의/Udacity ML

4.11 공통책 찾기 실습

SMALL
#Optimizing Code: Common Books"
#Here's the code your coworker wrote to find the common book ids in `books_published_last_two_years.txt` and `all_coding_books.txt` to obtain a list of recent coding books."

import time
import pandas as pd
import numpy as np

with open ('books_published_last_two_years.txt') as f:
    recent_books = f.read().split('\\n')
    
with open('all_coding_books.txt') as f:
    coding_books = f.read().split('\\n')

start = time.time()
recent_coding_books = []

for book in recent_books:
    if book in coding_books:
        recent_coding_books.append(book)

print(len(recent_coding_books))
print('Duration: {} seconds'.format(time.time() - start))

### Tip #1: Use vector operations over loops when possible

start = time.time()
recent_coding_books =  np.intersect1d(recent_books, coding_books) # compute intersection of lists
print(len(recent_coding_books))
print('Duration: {} seconds'.format(time.time() - start))


### Tip #2: Know your data structures and which methods are faster",

start = time.time()
recent_coding_books =  set(recent_books).intersection(coding_books) # compute intersection of lists
print(len(recent_coding_books))
print('Duration: {} seconds'.format(time.time() - start))

#Tip 1. 루프에 벡터 연산 사용

numpy의 intersect1d를 활용하여 공통점을 찾는다. 이 모듈로 연산을 더 빠르게 할 수 있다.

 

#Tip 2. 데이터 구조를 확인하고 더 빠른 방법 찾기

이 데이터의 경우 고유한 요소 그룹을 저장하고 빠르게 계산할 수 있는 Set 데이터 구조가 있다. 

https://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists

 


intersect1d

https://numpy.org/doc/stable/reference/generated/numpy.intersect1d.html

 

numpy.intersect1d — NumPy v1.21 Manual

numpy.intersect1d numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)[source] Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ar1, ar2array_likeInput arrays. Will be

numpy.org

Parameter로 받은 두 배열의 공통배열을 정렬하여 return 한다.

parmeter option에 따라 다른 return값을 받을 수 있다.

 

intersection

https://www.w3schools.com/python/ref_set_intersection.asp

 

Python Set intersection() Method

Python Set intersection() Method ❮ Set Methods Example Return a set that contains the items that exist in both set x, and set y: x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print(z) Try it Yourself » Defi

www.w3schools.com

2개 이상의 Set 구조에 사용할 수 있는 모듈이다.

Parameter로 전달된 Set의 공통부분을 Set으로 반환한다. 

SMALL

'강의 > Udacity ML' 카테고리의 다른 글

4.15 문서화  (0) 2021.07.29
4.14 실습 : 선물 코스트 정리하기  (0) 2021.07.27
4.6 모듈화된 코드 작성  (0) 2021.07.22
4.4 클린 코드 작성  (0) 2021.07.22
4.3 코드 리팩토링  (0) 2021.07.22