본문 바로가기

Thinking/Study

[study] python 기본 문법

728x90

dictionary 사용

# dictionary = {
#     "a1" : "A1",
#     "b1" : "B1"
# }

dictionary = [
    {"key" : "A1", "value" : 10}, 
    {"key" : "B1", "value" : 20}
]

for d in dictionary:
    # print(d)
    #print("{}".format(d))
    print("{}:{}".format(d["key"], d["value"]))

# print(dictionary.get("a2"))

# del dictionary["a1"]
# if "a1" in dictionary:
#     print(dictionary.get("a1"))
# else:
#     print("not exist key")

list, list comprehension

# 1~100 에서 2진수로 0 이 하나면 포함된 숫자의 합
output = 0
for i in range(1, 100 + 1):
	if "{:b}".format(i).count("0") == 1:
		print("{} : {:b}".format(i, i))
		output += i
print("합계 :{}".format(output))

# List Comprehension 으로 변경
output = [i for i in range(1, 100+1) if "{:b}".format(i).count("0") == 1]
for i in output:
	print("{} : {}".format(i, "{:b}").format(i))
print("합계:{}".format(sum(output)))

function 정의, variable parameter, default value parameter, 

def print_n_time(value, n=5):
	for i in range(n):
		print(value)

print_n_time("First Hi")
print_n_time("Second Hi", 2)

def function(value, *var, n=5):
	for i in range(n):
		print(value)

function("First Hi2")
function("Second Hi2", "variable", n=1)
function("Third Hi3", "variable", 3, n=1)

재귀함수, 메모리제이션

# 피보나치 수열
counter = 0
def pivonacci(num):
	global counter
	counter += 1
	if num == 0 or num == 1 or num == 2:
		return 1
	return (pivonacci(num - 1) + pivonacci(num - 2))

print(pivonacci(1))
print(pivonacci(2))
print(pivonacci(3))	
print(pivonacci(4))
print(pivonacci(30))
print(counter)

# memorization
memo = {1 : 1, 2 : 1}
def f(n):
	if n in memo:
		return memo[n]
	else:
		output = f(n-1) + f(n-2)
		memo[n] = output
		return output
print(f(30))

 

list -> flatten

# example 의 list 를 flatten
def flatten(data):
    output = []
    for item in data:
        if type(item) == list:
            output += flatten(item)
        else:
            #output.append(item)
            output += [item] 
    return output

example = [[1, 2, 3], [4, [5,6]], 7, [8, 9]]
print("original: ", example)
print("conversion: ", flatten(example))

tuple

(a, b) = (10, 20)
#a, b = 10, 20
print(a, b)

# swap
a, b = b, a
print(a, b)

# divmod
a, b = 87, 40
print(divmod(a,b))

# tuple type
print(273, )
print(type(273,))
print((273, ))
print(type((273,)))

# tuple value
data = {
    (0,0): 10,
    (0,1): 20,
    (1,0): 30,
    (1,1): 40
}
print(data[(0,0)])
print(data[0,0])

lamda

def call_5_times(func):
    for i in range(5):
        func(i)

def print_hello(number):
    print("Hello", number)

#call_5_times(print_hello)
call_5_times(lambda number: print("Hello", number))

# print => 1::2::3::4::5::6
numbers = [1,2,3,4,5,6]
print("::".join(map(str, numbers)))

numbers2 = ['1','2','3','4','5','6']
print("::".join(numbers2))

text file handling

with open("test.txt", "a") as file:
    file.write("Hello.")

file = open("test.txt", "a")
file.write("Hello.")
file.close()

file = open("test.txt", "r")
print(file.read())
file.close()

with open("test.txt", "r") as file:
    print(file.read())

generator

#1 yield, next 사용
def func():
    print("Hello A")
    yield 100
    print("Hello B")
    yield 200
    print("Hello C")
    yield 300
    print("Hello D")
    yield 400

gene = func()
value = next(gene)
value = next(gene)
value = next(gene)
value = next(gene)

for i in gene:
    print(i)

#2 reverse function
def reverse_func(list_a):
    for i in range(len(list_a)):
        yield list_a[-i - 1]

generator = reverse_func([1,2,3,4,5])
for i in generator:
    print(i)

try, except

try:
    a = [1, 2, 3, 4, 5]
    number = int(input("input (0~4)> "))
    print(a[number])
except ValueError as exception:
    print("Value error : ", exception)
except IndexError as exception:
    print("Index error : ", exception)
except Exception as exception:
    print("Unknown error : ", exception)

class

class Student:
    def __init__(self, name, korean, math, english, science):
        self.name = name
        self.korean = korean
        self.math = math
        self.english = english
        self.science = science
    def total(self):
        return self.korean + self.math + self.english + self.science
    def average(self):
        return self.total() / 4
    def print(self):
        print(self.name, self.total(), self.average(), sep="\t")


students = [
    Student("alice", 87, 80, 91, 89),
    Student("betty", 90, 88, 89, 78),
    Student("Catherine", 93, 95, 89, 86)
]

for student in students:
    student.print()

class getter, setter

# getter, setter
class Rect:
    def __init__(self, width, height):
        if width <= 0 or height <= 0:
            raise Exception("Width/Height must not 0 or negative")
        self.__width = width
        self.__height = height
    def get_width(self):
        return self.__width
    def set_width(self, width):
        if width <= 0:
            raise Exception("Width must not 0 or negative")
        self.__width = width
    def get_height(self):
        return self.__height
    def set_height(self, height):
        if height <= 0:
            raise Exception("Height must not 0 or negative")
        self.__height = height
    def get_area(self):
        return self.__width * self.__height

rect = Rect(10, 10)
rect.set_width(rect.get_width() * 10)
print(rect.get_area())

# property
class Rect:
    def __init__(self, width, height):
        if width <= 0 or height <= 0:
            raise Exception("Width/Height must not 0 or negative")
        self.__width = width
        self.__height = height
    @property
    def width(self):
        return self.__width
    @width.setter
    def width(self, width):
        if width <= 0:
            raise Exception("Width must not 0 or negative")
        self.__width = width
    @property
    def height(self):
        return self.__height
    @height.setter
    def height(self, height):
        if height <= 0:
            raise Exception("Height must not 0 or negative")
        self.__height = height
    def get_area(self):
        return self.__width * self.__height

rect = Rect(10, 10)
rect.width -= 5
print(rect.get_area())

module

import math
impoort math as suhak
from math import pi, sin
from math import *

데코레이터(decorator)

def decorator(func):
    print("pre process")
    return func

@decorator
def test_func():
    print("hello")

# @decorator 사용하기전 
# test_func = decorator(test_func)
test_func()

def exdecorator(number):
    def decorator(func):
        print("pre process", number)
        return func
    return decorator

@exdecorator(number=100)
def test_func():
    print("hello")

test_func()

출처 :

혼자 공부하는 파이썬 - 윤인성

https://www.youtube.com/playlist?list=PLBXuLgInP-5nbu5s5TuNbD6-4qh3Mgoor

'Thinking > Study' 카테고리의 다른 글

[내용 정리] 토비의 봄 TV 5회  (0) 2017.11.22
[내용 정리] 토비의 봄 TV 1회 Double dispatch example  (0) 2017.11.17
JAVA 8 에서 추가된 forEach 문 사용 예제  (0) 2017.11.15
Apache ZooKeeper  (0) 2017.03.22
패턴 정리  (0) 2015.08.24