강의/Udacity ML

4.14 실습 : 선물 코스트 정리하기

3. 2021. 7. 27. 21:40
SMALL

특정 값 이상의 품목에 대해 과세하는 프로그램

 

import time
import numpy as np

with open('gift_costs.txt') as f:
    gift_costs = f.read().split('\n')

gift_costs = np.array(gift_costs).astype(int)  # convert string to int

start = time.time()

total_price = 0
for cost in gift_costs:
    if cost < 25:
        total_price += cost * 1.08  # add cost after tax

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

## Refactor Code

start = time.time()

total_price = (gift_costs[gift_costs < 25]).sum() * 1.08
print(total_price)

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

numpy 모듈의 특성

배열 인덱스에 조건식을 주어 계산 가능하다. 

SMALL