⚙️ Python
📌 재귀 함수
def rec_fn(n):
print(n)
if not n:
return
rec_fn(n-1)
📌 := 연산자
- 표현식의 결과를 변수에 할당하고, 동시에 반환해주는 연산자다.
a = 'hellooooooooo'
if (n := len(a)) > 10:
print(f'too long {n} elements')
📌 Scope
- 호출하려는 함수/ 변수 탐색 과정
- Local 위치에서 탐색 시작
- 부모 위치에서 탐색
- Global 위치에서 탐색
- Built in 위치에서 탐색
- 전역 변수
total = 0
def summation(n):
global total
total += n
for i in range(5):
summation(i)
print(total)
def outer():
x = 'local'
print('before calling inner function:', x)
def inner():
nonlocal x
x = 'nonlocal'
print(x)
inner()
print('after calling inner function:', x)
outer()
📌 클래스와 상속
class Myclass(object):
def __init__(self):
self.word = 'hello world'
def hello(self):
print(self.word)
object = Myclass()
object.hello()
⚙️ Exercise
📝 가변인자를 입력받는 함수 만들기
입력을 가변인자로 받아서 원하는 출력을 생성해주는 함수를 만들자
def func1(*args):
result = []
for item in args:
k = len(str(item[0]))
t = []
for i in range(0,len(item),1):
t.append(k*(10**i))
result.append(t)
return(result)
print(func1([1,2,3], [10,20,30], [100,200,300]))
📝 재귀 함수 만들기
양의 정수 n을 입력하면 0에서 n까지의 합을 출력하는 함수를 만들자
def recfunc(n):
if n == 1:
return 1
return n + recfunc(n-1)
📝 재귀 함수 만들기 2
양의 정수 n, m을 입력하면 n x m 부터 n x 1까지 구구단을 출력해주는 함수를 만들자
def gugudan(n, m):
if not m:
return 0
print("%d X %d = %d" %(n,m,n*m))
gugudan(n, m-1)
📝 재귀 함수 만들기 3
피보나치 수열에서 입력된 정수 n번째 항을 출력해주는 함수를 만들자
def func(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return func(n-2) + func(n-1)
📝 재귀 함수 만들기 4
주어진 리스트 두개의 각 요소를 하나씩 꺼내어 새로운 리스트를 만들어주는 함수를 만들자
def rec_zip(xs, ys):
if len(xs) == 0 | len(ys) == 0:
return []
xhead, *xtail = xs
yhead, *ytail = ys
return [[xhead, yhead]] + rec_zip(xtail, ytail)
📝 전역 변수 사용
두 개의 함수를 이용해 수들의 평균을 출력 하도록 해보자
final_average = 0
stack = 0
def accumulator(n):
global final_average
global stack
final_average += n
stack += 1
def result():
return final_average / stack
for i in range(10):
accumulator(i+1)
print(result())
📝 클래스 만들기
입력된 숫자들의 합을 구해주는 메서드와 그 합의 평균을 return 해주는 메서드,
그리고 현재까지의 합을 초기화해주는 메서드를 가지는 클래스를 만들어보자
class accumulator(object):
def __init__(self):
self.total_val = 0
self.count_val = 0
def add(self, num):
self.total_val += num
self.count_val += 1
def result(self):
return self.total_val / self.count_val
def reset(self):
self.total_val = 0
self.count_val = 0
📝 클래스 만들기 2
set()과 get()을 통해 값을 자유롭게 변경할 수 있는 클래스를 만들어보자
class Person(object):
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
def set(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
def get(self):
return self.name, self.age, self.height, self.weight