1

재귀함수

(a)

1
2
3
4
5
6
7
def mult(i,j):
    print(i,"*",j,"=",i*j)
def right(i,j,n):
    if j < n:
        mult(i,j)
        right(i,j+1,n)
right(2,1,10)

2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18


(b)

1
2
3
4
5
6
7
8
9
10
11
def mult(i,j):
    print(i,"*",j,"=",i*j)
def right(i,j,n):
    if j < n:
        mult(i,j)
        right(i,j+1,n)
def left(i,m,n):
    if i < m:
        right(i,1,n)
        left(i+1,m,n)
left(2,5,3)

2 * 1 = 2 2 * 2 = 4 3 * 1 = 3 3 * 2 = 6 4 * 1 = 4 4 * 2 = 8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
left(2,5,3) -> rigth(2,1,3) -> mult(2,1)
    |               |
    |          right(2,2,3) -> mult(2,2)
    |               |
    |          right(2,3,3)
    |
left(3,5,3) -> rigth(3,1,3) -> mult(3,1)
    |               |
    |          right(3,2,3) -> mult(3,2)
    |               |
    |          right(3,3,3)
    |
left(4,5,3) -> rigth(4,1,3) -> mult(4,1)
    |               |
    |          right(4,2,3) -> mult(4,2)
    |               |
    |          right(4,3,3)
    |
left(5,5,3)

nested for loop (for 두개)로 만들 수 있음

2

문자열과 리스트의 관계 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
s = 'This is right justified'
def mysplit(s):
    lst = []
    tmp = ''
    for c in s:
        if c != ' ':
            tmp = tmp + c
        else:
            lst.append(tmp)
            tmp = ''
    if tmp != '':
        lst.append(tmp)
        tmp = ''
    return lst
print(mysplit(s))

[‘This’, ‘is’, ‘right’, ‘justified’]


3

파이썬의 기본 함수들 예제

(a)

1
2
3
4
x = [1,2,3]
print(len(x))
x.append(4)
print(len(x))

3 4


(b)

1
print('hello'.upper())

HELLO


(c)

1
print('{0}'.format(3 + 4))

7


(d)

1
print('{x}'.format(x=3+4))

7


4

파이썬으로 Vector 클래스를 정의한 예제

1
2
3
4
5
6
7
8
9
class Vector:
    def __init__(self,lst):
        self.vec = lst
    def __repr__(self):
        return "Vector({0})".format(self.vec)
    def __add__(self,other):
        return Vector([self.vec[i] + other.vec[i] for i in range(len(self.vec))])
x = Vector([1,2,3])
print(x + x)

Vector([2, 4, 6])

init은 Vector가 실행될때 가장 먼저 실행되는것