레이블이 python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 python인 게시물을 표시합니다. 모든 게시물 표시

2018/07/16

[python] binary search tree

오름차순으로 정렬된 리스트에서 특정한 값의 위치를 찾는 알고리즘이다. 처음 중간의 값을 임의의 값으로 선택하여, 그 값과 찾고자 하는 값의 크고 작음을 비교하는 방식을 채택하고 있다. 처음 선택한 중앙값이 만약 찾는 값보다 크면 그 값은 새로운 최댓값이 되며, 작으면 그 값은 새로운 최솟값이 된다. 검색 원리상 정렬된 리스트에만 사용할 수 있다는 단점이 있지만, 검색이 반복될 때마다 목표값을 찾을 확률은 두 배가 되므로 속도가 빠르다는 장점이 있다.
def bsearch(items, key):
    # recursive function을 독립 시키기 위한 adapter function
    return bs_helper(items, key, -1, len(items))

def bs_helper(items, key, lower, upper):
    # Base condition : 값을 못 찾았을 경우
    if lower + 1 == upper:
        return None
    mid = (lower + upper) // 2
    # 값을 찾았을 경우 return
    if key == items[mid]:
        return mid
    # 아래 쪽에 위치할 경우 lower range 를 검색
    if key < items[mid]:
        return bs_helper(items, key, lower, mid)
    else:
        return bs_helper(items, key, mid, upper)


a = [1, 2, 4, 5, 7, 9, 10, 34, 45, 89, 345]
print(bsearch(a, 5))

[python] check parenthesis matching

import queue

class PaMatch():
    def __init__(self):
        super(PaMatch, self).__init__()
        self.lst = queue.LifoQueue()
        self.check = 0
    
    def push(self, a):
        self.lst.put(a)
        
    def pop(self):
        return self.lst.get()
    
    def checkMatch(self, string):
        for i in range(len(string)):
            if string[i] == "(":
                self.push(i)
            elif string[i] == ")":
                if self.lst.qsize() >= 1:
                    # 첫번째 출력이 아닐 경우 "," 추
                    if self.check > 0:
                        print(",", end="")
                    print("({},{})".format(self.pop(),i), end="")
                    self.check += 1
                # parenthsis가 맞지 않을 경우 남은 자리를 보여주고 종료
                else:
                    print("\nNot matched : {}".format(i), end="")
        # parenthsis가 맞지 않을 경우 남은 자리를 보여주고 종료
        for i in range(self.lst.qsize()):
            print("\nNot matched : {}".format(self.lst.get()), end="")

        print("")
   
#  Good Matching Case
string = "((((A+B)-C)*D)/S*A)"
A = PaMatch()
A.checkMatch(string)

# Not Good Matching Case 1
string2 = "(((((((A+B)-C)*D)/S*A"
B = PaMatch()
B.checkMatch(string2)

# Not Good Matching Case 2
string3 = "((((A+B)-C)*D)))/S*A))))"
C = PaMatch()
C.checkMatch(string3)

(3,7),(2,10),(1,13),(0,18)
(6,10),(5,13),(4,16)
Not matched : 3
Not matched : 2
Not matched : 1
Not matched : 0
(3,7),(2,10),(1,13),(0,14)
Not matched : 15
Not matched : 20
Not matched : 21
Not matched : 22
Not matched : 23

2018/07/14

[python] 공공 Data를 이용한 동네 예보 처리

공공 Data 활용을 위한 service_key 신청은 Link를 참조.

# -*- coding: utf-8 -*-
import datetime as dt
import requests as req
from bs4 import BeautifulSoup

w_items = {"POP":["강수확률", "%"], "PTY":["강수형태", ""], "R06":["6시간 강수량", "mm"], "REH":["습도", "%"], "S06":["6시간 신적설", "cm"], 
           "SKY":["하늘상태", ""], "T3H":["3시간 기온", "°C"], "TMN":["아침 최저 기온", "°C"], "TMX":["낮 최고 기온", "°C"], 
           "UUU":["풍속(동서성분)","m/s"], "VVV":["풍속(남북성분)","m/s"], "WAV":["파고", "m"], "VEC":["풍향", ""], "WSD":["풍속", "m/s"]}
wind_dict = {0:"N",1:"NNE",2:"NE",3:"ENE",4:"E",5:"ESE",6:"SE",7:"SSE",8:"S",9:"SSW",10:"SW",11:"WSW",12:"W",13:"WNW",14:"NW",15:"NNW",16:"N"}
rain_dict = {0:"없음", 1:"비", 2:"진눈깨비", 3:"눈"}

# 가장 최근의 기상청 예보 시간(02:10 이후 3시간 단위) get
def get_rpt_time():
    base_time = dt.datetime.now() - dt.timedelta(hours=2) - dt.timedelta(minutes=10)
    hour = int(base_time.strftime("%H"))
    rehour = str(hour//3*3 + 2).zfill(2)
    return [base_time.strftime("%Y%m%d"), rehour + "00"]

# 풍향 계산용
def get_wind_type(i):
    return wind_dict[(i + 22.5 * 0.5)//22.5]

def get_sky_status(i):
    if i >= 0 and i <= 2: return "맑음"
    elif i >= 3 and i <= 5: return "구름조금"
    elif i >= 6 and i <= 8: return "구름많음"
    elif i >= 9 and i <= 10: return "흐림"

def get_real_value(c, s):
    if c.string == "VEC":
        return get_wind_type(int(s.string))
    elif c.string == "SKY":
        return get_sky_status(int(s.string))
    elif c.string == "PTY":
        return rain_dict[int(s.string)]
    return s.string

# have to change with your service_key
service_key = "MJqwsP2VlmHlaRh0BMwMAtDvhfFu6k59h%2B1Svp2A%......."
nx = 60    # 서울 기준
ny = 127   # 서울 기준

date = get_rpt_time()

base_url = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastSpaceData?ServiceKey={}&base_date={}&base_time={}&nx={}&ny={}"
url = base_url.format(service_key, date[0], date[1], nx, ny)

contents = req.get(url)
weather = BeautifulSoup(contents.content, 'lxml-xml')

print("\t **************************************")
print("\t Report Time :", date[0], date[1])
print("\t **************************************")
for item in weather.find_all("item"):
    print("\t", w_items[item.category.string][0], " : ", get_real_value(item.category, item.fcstValue), end = "")
    if w_items[item.category.string][1] != "":
        print(w_items[item.category.string][1])
    else:
        print()
<결과>
         **************************************
         Report Time : 20180715 1100
         **************************************
         강수확률  :  10%
         강수형태  :  없음
         습도  :  50%
         하늘상태  :  맑음
         3시간 기온  :  31°C
         낮 최고 기온  :  33.0°C
         풍속(동서성분)  :  3.1m/s
         풍향  :  WSW
         풍속(남북성분)  :  1.3m/s
         풍속  :  3.4m/s

[python] get current datetime

from datetime import datetime
datetime.today()                # get current date
datetime.today().year        # get current year
datetime.today().month    # get current month
datetime.today().day         # get current day
datetime.today().hour        # get current hour
datetime.today().strftime("%Y/%m/%d %H:%M:%S")  # get current date with format yyyy/mm/dd hh24:mm:ss

[python] all markers in matplotlib.pypolot.scatter

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

markers = {'.': 'point', ',': 'pixel', 'o': 'circle', 'v': 'triangle_down', '^': 'triangle_up', '<': 'triangle_left', '>': 'triangle_right', 
                    '1': 'tri_down', '2': 'tri_up', '3': 'tri_left', '4': 'tri_right', '8': 'octagon', 's': 'square', 'p': 'pentagon', '*': 'star', 
                    'h': 'hexagon1', 'H': 'hexagon2', '+': 'plus', 'x': 'x', 'D': 'diamond', 'd': 'thin_diamond', '|': 'vline', '_': 'hline', 
                    'P': 'plus_filled', 'X': 'x_filled', 0: 'tickleft', 1: 'tickright', 2: 'tickup', 3: 'tickdown', 4: 'caretleft', 5: 'caretright', 
                    6: 'caretup', 7: 'caretdown', 8: 'caretleftbase', 9: 'caretrightbase', 10: 'caretupbase', 11: 'caretdownbase', 
                    'None': 'nothing', None: 'nothing', ' ': 'nothing', '': 'nothing'}

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = (30 * np.random.rand(N))**2 

for key, value in markers.items():
    plt.scatter(x, y, s=area, c="g", alpha=0.5, marker=key, label=value)
    plt.legend(loc=1)
    plt.show()







































2018/07/13

useful links


Visual Studio Code - python
https://code.visualstudio.com/docs/python/python-tutorial


운영체제 - 경성대학교 양희재 교수

컴퓨터 구조 - 숭실대학교 김병기 교수

소프트웨어 공학 - 동국대학교 최은만 교수

알고리즘 - 명지대학교 이충기 교수

데이터베이스 - 이화여자대학교 용환승 교수

수리 통계학 - 국민대학교 강주성 교수

선형 대수 - 국민대학교 이옥연 교수

선형 대수 -  한양대학교 이상화 교수

확률 및 통계 - 한양대학교 이상화 교수

Deep Learning 정리 Blog

DataScience School

Python 연습 Site

Python Data Science Handbook

수학 관련 정리

Thinker with a Neutal Network

2018/06/11

[python] json

import json

# Json String to variable
sample = {
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

# string to Json encoding with formatting
sample_json = json.dumps(sample, indent = 4)
print(sample_json)
print('')

# Decoding Json String to Python type
sample_structured_json = json.loads(sample_json)
print(sample_structured_json)
print('')

print(sample_structured_json['glossary']['title'])
print('')

for i in sample_structured_json['glossary']['GlossDiv']['GlossList']['GlossEntry']:
    print(i)

2018/06/08

[python] binary data write to file

# binary data generation
bdata = bytes(range(0, 256))

# check length and data
print('size :', len(bdata), '\ndata : ', bdata)

# set offset and chunk size, get data size
offset = 0
chunk = 10
size = len(bdata)

# write to file and get size
with open('bfile.bin', 'wb') as bf:
    while offset <= size:
        bf.write(bdata[offset:offset+chunk])
        offset += chunk

# check file
! cat bfile.bin