Jan 29, 2023

파이썬으로 구현한 1차 저역필터 (Low pass filter in Python)


# First order LPF
import numpy as np
import matplotlib.pyplot as plt

def first_order_low_pass_filer(data, alpha):
    filtered_data = np.zeros_like(data)
    filtered_data[0] = data[0]
    for i in range(1, len(data)):
        filtered_data[i] = alpha * data[i] + (1 - alpha) * filtered_data[i-1]
    return filtered_data

low_alpha = 0.4  # filter weight
high_alpha = 0.8 # filter weight

# np.linspace(start, stop, num, ...)
time = np.linspace(0, 5, 200)

data = np.sin(2 * np.pi * 50 * time) + np.sin(2 * np.pi * 250 * time) * 2  

low_alpha_data = first_order_low_pass_filer(data, low_alpha)
high_alpha_data = first_order_low_pass_filer(data, high_alpha)

plt.figure(figsize=(25, 7))
plt.plot(time, data, label='real Data', color = 'lawngreen')
plt.plot(time, low_alpha_data, label = 'low 1-st LPF', color = 'black', linestyle = '--')
plt.plot(time, high_alpha_data, label = 'high 1-st LPF', color = 'red', linestyle = '-.')

plt.xlabel('time (sec.)')
plt.ylabel('amplitude')
plt.title('First Order Low Pass Filter')
plt.legend()
plt.show()

Output



Jan 20, 2023

파이썬-text 파일 쓰기, 읽기, 추가하기 (.txt writing, reading, and adding in Python)

■ .txt 파일 생성 후 쓰기

※ 한글 사용 시, utf-8로 encoding을 지정해 준다.

f = open("text_file.txt", "w", encoding="utf-8")
for i in range(1, 5):
    text_line = "{0}번째 줄입니다. \n" .format(i)
    f.write(text_line)

f.close()

Output in "text_file.txt"
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 출력하기

- readline() 함수 사용, while 문으로 한 줄 한 줄, 읽은 것을 출력

f = open("text_file.txt", "r", encoding="utf-8")

while True:
    line = f.readline()
    if not line:    
        break

    print(line)

f.close()

Output
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 출력하기 II

- readlines() 함수 사용, 전체 읽어서 한 줄, 한줄 for문으로 출력

f = open("text_file.txt", "r", encoding="utf-8")

lines = f.readlines()
for line in lines:
    print(line)

f.close()

Output
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 출력하기 III

- read() 함수 사용, 전체 읽어서 전체 출력

f = open("text_file.txt", "r", encoding="utf-8")
print(f.read())

Output
1번째 줄입니다. 2번째 줄입니다. 3번째 줄입니다. 4번째 줄입니다.

■ .txt 읽고 추가하기


Jan 15, 2023

Python 함수 만들기 (functions)

 ■ No argument, No retrun (인자가 없고, 리턴이 없는 경우)

def hello_function():
    print("Hello, world!")

hello_function()

Output
Hello, world!

 ■ Yes argument, No retrun (인자가 있고, 리턴이 없는 경우)

def hello_function(name):
    print("Hello, it's me. {0}!" .format(name))

hello_function("Swan")

Output
Hello, it's me. Swan!

 ■ Yes argument, Yes retrun (인자가 있고, 리턴이 있는 경우)

def multiply_five(number):
    return number*5

multiply_five(5)

Output
25

Jan 14, 2023

파이썬을 활용한 로또 번호 추출 (Extraction of 'Lotto number' in Python)

 ■ Code & Output

- random module을 활용한 예제

import random

print("몇 장의 로또를 구매하실 건가요?")
print("숫자를 입력하세요.")
num_set =int(input("숫자를 입력하세요: "))
print("{0}장을 구매했습니다." .format(num_set))

for i in range(1, num_set+1):
    lotto_numbers = random.sample(range(1, 46), 6)
    lotto_numbers.sort()

    print("{0}장, {1}" .format(i, lotto_numbers))

print("1등을 기원합니다.")

Output
몇 장의 로또를 구매하실 건가요? 숫자를 입력하세요. 3장을 구매했습니다. 1장, [1, 9, 25, 27, 36, 45] 2장, [12, 18, 22, 27, 29, 39] 3장, [11, 17, 19, 36, 37, 41] 1등을 기원합니다.

파이썬을 활용한 오늘 메뉴 선택 프로그램 (Choosing a today's memu in Python)

import random
options = ["치킨", "김밥", "국밥", "돈가스", "제육덮밥", "김치찌개", "떡국"]

def today_menu():
    menu = random.choice(options)
    return menu

today_choice_menu = today_menu()
print("오늘 점식 메뉴는 {0} 입니다." .format(today_choice_menu))

Output
오늘 점식 메뉴는 떡국 입니다.

Jan 2, 2023

파이썬으로 2중 반복문을 활용한 구구단 및 문자열 formatting 종류 (Multiplication table using a double for-loop in Python)

print("구구단 2단부터 9단까지 시작!")

for i in range(2, 10, 1):
    for j in range(1, 10, 1):
        print(i, "x", j, "=", i*j)                   # case1
        print("%d x %d = %d"  % (i, j, i*j))         # case2
        print(f'{i} x {j} = {i*j}')                  # case3
        print("{0} x {1} = {2}".format(i, j, i*j))   # case4

Output exceeds the size limit. Open the full output data in a text editor
구구단 2단부터 9단까지 시작! 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27

Jan 1, 2023

Design a GA-based PID Controller for a Pressure Control of a Process Chamber using a Time-domain System Identification

1. Status: 2022 22nd International Conference on Control, Automation and Systems (ICCAS) (published).

2. Author: Seungwan Ryu; Sungsoon Yim; Seokmin Wi; Seungyun Jung; Sanghoon Kim; Byeonghee Kim

3. Abstract: in URL.

List Comprehension example in Python

 ■ Before comprehension

words = ["apple", "bus", "camera", "dog", "eye", "five", "game"]

new_list = []

for x in words:
    if "e" in x:
        new_list.append(x)

print(new_list)

Output
['apple', 'camera', 'eye', 'five', 'game']

 ■ After comprehension

words = ["apple", "bus", "camera", "dog", "eye", "five", "game"]
new_list = [x for x in words if "e" in x]

print(new_list)

['apple', 'camera', 'eye', 'five', 'game']

파이썬 반복문 (for문), range(..., ..., ...,) example

■ 문자로 for문

for x in "abcdef":
    print(x)

Output
a b c d e f

■ List로 for문

words = ["apple", "bus", "camera", "dog", "eye", "five", "game"]

for x in words:
    print(x)

Output
apple bus camera dog eye five game

■ for문 range 활용 I

for i in range(6):
    print(i)

Output
0 1 2 3 4 5

■ for문 range 활용 II

for i in range(1, 6):
    print(i)

Output
1 2 3 4 5

■ for문 range 활용 III

for i in range(0, 8, 2):
    print(i)

Output
0 2 4 6

■ for문 range 활용 IV

for i in range(100, 50, -10):
    print(i)

Output
100 90 80 70 60