210217 Python TIL (작성중...)

Python

네트워크

Web scraping 실습하기

  • 환경설정

    1. requests, beautifulsoup4, lxml, jupyter 설치하기
    1
    2
    3
    4
    $ poetry add requests
    $ poetry add beautifulsoup4
    $ poetry add lxml
    $ poetry add —dev jupiter
    1. jupyter notebook 환경에서 requests를 사용해서 Web Scrapping하기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import requests

    url = 'https://api.kurly.com/v2/categories?ver=1'
    response = requests.get(url)
    response
    # response data를 json 형태로 변환하기
    response.json()

    """
    {'data': {'categories': [{'no': '907',
    'name': '채소',
    'show_all_flag': True,
    'pc_icon_url': 'https://img-cf.kurly.com/shop/data/category/icon_veggies_inactive_pc@2x.1586324570.png',
    'icon_url': 'https://img-cf.kurly.com/shop/data/category/icon_veggies_inactive@3x.1586324413.png',
    'pc_icon_active_url': 'https://img-cf.kurly.com/shop/data/
    ...(생략)...
    """
Read more

210215 Python TIL 2/2 - Function, Closure, Decorator

Python

Function = First-class function

  • 파이썬에서는 함수를 일급 시민(first class citizen)으로 취급한다.
    아래의 예시코드를 보면, 함수에서 또 다른 함수를 반환할 수 있으며, 함수에서 반환하는 lambda 함수의 경우 본래 heap에 저장이 되지만, 함수에서 반환된 lambda함수를 변수에 넣음으로써 data 영역에 저장된다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    def make_difference(operator):
    if operator == '+':
    return lambda x,y:x+y
    if operator == '-':
    return lambda x,y:x-y

    plus = make_difference('+')
    # lambda는 기본적으로 heap에 저장이 되지만, 변수로 다시 넣기 때문에 데이터의 영역으로 저장이 된다.
    print(plus(1,2)) #3
Read more

210215 Python TIL 1/2 - Module & Package, Library & Framework, Poetry, Virtualenv

Python

Module, Package


  • Module?

    • Python 코드로 이루어진 파일로, 본체에 대한 하위 단위로 정의한다.
  • Package?

    • 관련 여러 모듈들을 하나의 폴더로 묶은 것을 말한다.

    (Module, Package관련 실습내용)
    (1) fibo.py와 main.py 파일을 만들어서 실습을 진행한다.
    fibo에 정의되어있는 text변수의 값을 main.py에서 출력한다.

    1
    2
    3
    from fibo import text

    print(text)
Read more

210214 Python HackerRank Assignment

HackerRank

설날 과제로 강사님이 내주신 HackerRank의 과제에 대해서 정리한다.

문제 1

Problem1 Link(HackerRank)

이 문제는 주어진 클래스의 상속관계를 완성하고, 주어진 조건으로 내부에 method를 완성시키면 되는 간단한 문제이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Student(Person):

# Class Constructor
#
# Parameters:
# firstName - A string denoting the Person's first name.
# lastName - A string denoting the Person's last name.
# id - An integer denoting the Person's ID number.
# scores - An array of integers denoting the Person's test scores.
#
# Write your constructor here
def __init__(self, _firstName, _lastName, _id, _scores):
Person.__init__(self, _firstName, _lastName, _id)
self.scores = _scores
# Function Name: calculate
# Return: A character denoting the grade.
#
# Write your function here
def calculate(self):
average = sum(self.scores) / len(self.scores)
if 90 <= average <= 100:
grade = "O"
elif 80 <= average < 90:
grade = "E"
elif 70 <= average < 80:
grade = "A"
elif 55 <= average < 70:
grade = "P"
elif 40 <= average < 55:
grade = "D"
else:
grade = "T"
return grade
Read more

210210 Python TIL 2/2 - class method, instance method, static method, Polymorphism, Abstract class

Python

오늘 배운 내용은 전반적으로 객체지향 프로그래밍 언어로써 Python을 잘 활용하기 위해 중요한 내용이기 때문에 포스팅을 두 개로 나눠서 작성해보았다.

오늘 배운내용

Class, instance, static method

  • Class method: @classmethod decorator를 사용하며, cls를 인자로 사용

    • cls 인자를 받는다.
    • class variable과 연관된 일을 할때 사용이 된다.
  • Instance method: self를 인자로 사용

    -객체의 고유 속성값을 사용한다.
  • Static method: 아무 인자 없이 사용

    • 일반 함수와 같은 역할을 한다.
    • class와 관련있는 함수로써, class내부에서 정의하고자 할 때 사용된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Wallet:
def __init__(self, account):
self.account = account
balance = 0
name = 'Your wallet'

@classmethod
def set_default(cls, amount):
while amount < 1:
print("Err: You should set default value over 1. Try again!")
amount = int(input("Set default value: "))
cls.balance = amount
print('Set default balance to {}'.format(amount))
#instance method
def add_to_account(self, amount):
self.account += amount
print('Your total balance is {}'.format(self.account + Wallet.balance))

@staticmethod
def see_static_name():
print(Wallet.name)

def get_class_name(cls):
print(cls.name)
class MyWallet(Wallet):
name = 'My wallet'
Read more

210209 Python Assignment

Python

과제1) 성수역 지하철 열차 시스템

210209_train

지하철 노선 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 2호선 내부순환선 (총 43개 역) 시청역 <->시청역 (내부순환)
# 성수지선 (총 5개 역) 성수역 <-> 신설동
# 신정지선 (총 38개 역) 성수역 <->까치산
# class instance를 만들때 각 노선의 최대 정착역의 수를 구한다.
class SubwayLine:
def __init__(self, num_of_stn):
# 지하철역의 수 만큼 [0]리스트를 만들어서
# 역별로 정차하고 있는 지하철의 수를 관리
self.num_of_stop_train_list = [0]*num_of_stn

# 해당 index위치의 count값을 1증가 시켜준다.
def increaseNumOfStopTrain(self, idx):
if self.num_of_stop_train_list[idx] == 0:
self.num_of_stop_train_list[idx] += 1
else:
# 위험 알람 method를 호출해서 False값을 반환하도록 한다.
self.setDangerAlert()

def decreaseNumOfStopTrain(self, idx):
if self.num_of_stop_train_list[idx] == 1:
self.num_of_stop_train_list[idx] -= 1

# 해당 index위치에 정차되어있는 지하철의 수를 반환한다.
def getNumOfStopTrain(self, idx):
return self.num_of_stop_train_list[idx]
# 해당 역 위치에 지하철이 정차되어있는 경우, False값을 반환해서 출발할 수 없도록 한다.

def setDangerAlert(self):
return False
Read more

210205 Book recommendation


개발 관련 책 추천

오늘은 평소에 내가 관심이 많이 있었던 Clean code, TypeScript 등 개발과 관련해서 강사님이 수업도중에 여러 책들을 추천해주셨다.

Clean code는 이전부터 관심이 있던 내용이고, TypeScript는 최근에 공부를 시작해서 관심이 있던 내용이라 추천해주셨을때 너무 좋았다. 요즘 무슨 책을 읽어볼까 고민하던 참이었는데, 온라인 북으로 구매해서 아이패드에 넣고 통학시간이나 주말, 머리식힐때 읽어봐야겠다.

읽은 내용에서 유익한 내용이 있으면, 블로그에 포스팅해봐야겠다.

추천해주신 책은 아래와 같다. 일단 내가 최근에 공부를 시작한 TypeScript와 Clean code 책을 구매해서 읽어 볼 생각이다. 생각에서 끝나지 않기 위해서 내일 오전에 공부 시작할때 당장 구매해서 읽어봐야 겠다.

Code 코드 파이썬을 이용한 클린 코드를 위한 테스트 주도 개발
TypeScript Programming Two Scoops of Django
Two Scoops of Django책에서 다루고 있는 장고의 버전이 낮기 때문에 google에서 Two Scoops of Django를 검색해서 two scoops-of-django-3.x github의 코드파일을 참고하는 것을 추천한다.

https://github.com/feldroy/two-scoops-of-django-3.x

Read more

210205 Python TIL - filter, reduce, isinstance, OOP, scope, class

Python

오늘 배운내용

  • Section1) filter, reduce
  • Section2) OOP, Class

filter, reduce

filter

filter의 기본 사용 format : filter([function], [iterable object])

1부터 10까지의 수 중에 짝수인 수로 구성된 리스트 만들기

1
2
3
4
5
6
7
8
9
def even_selector(x):
if x % 2 == 0:
return True
else:
return False
# 선언한 function을 인자로 넣기
list(filter(even_selector, range(1, 10+1)))
# lambda function로 별도의 함수 선언없이 함수처리
list(filter(lambda a:a%2==0, range(1, 10+1)))
Read more

210204 Python Regular Expression Assignment

HackerRank

원래 HackerRank 문제의 경우, 별도로 풀이를 정리하지는 않지만, 이번에 정규표현식의 경우, 헷갈리는 부분과 새롭게 공부하게 된 내용이 있어서 별도로 정리를 해본다.

문제 1

Problem1 Link(HackerRank)

이 문제는 앞 뒤로는 자음만 위치하고, 가운데에는 2개 이상의 모음으로만 구성되어 있는 문자를 정규표현식을 통해 출력하는 문제이다.

Task You are given a string . It consists of alphanumeric characters, spaces and symbols(+, -). Your task is to find all the substrings of that contains or more vowels. Also, these substrings must lie in between consonants and should contain vowels only.

우선 문제를 풀이하기에 앞서 다음 긍정/부정예측(positive/negative lookahead assertion), 긍정 후 읽기에 대한 개념에 대해서 알아보자.

긍정적인 예측

x?=y : 이 패턴은 직후에 y가 존재하는 문자열 x에 match한다.

1
2
foo(?=bar)
# 직후에 bar가 있는 foo에 일치한다.

부정적인 예측

x?!y : 이 패턴은 직후에 y가 없는 문자열 x에 match한다.

1
2
foo(?!bar)
# 직후에 bar가 없는 foo에 일치한다.
Read more