노력과 삽질 퇴적물

코딩도장 문제풀이 본문

프로그래밍note/CS 기초

코딩도장 문제풀이

MTG 2015. 3. 10. 19:10

사용언어: 파이썬 2.7






1. 난이도, Lv 1


1) 피보나치 수열

문제: http://codingdojang.com/scode/461

1
2
3
4
5
6
7
8
9
10
11
12
13
input = 10
cnt = 0
a = 0
b = 1
 
for index in range(0, input):
    if index %2 == 0:
        print a
        print b
    cnt = a+b
    a = b
    b = cnt
    pass
cs





2) Multiples of 3 and 5 

문제: http://codingdojang.com/scode/350

1
2
3
4
5
6
7
8
9
10
11
12
13
14
max = 1000
result = 0
 
for index in range(1, max):
    if index % 3 == 0:
        result += index
        print index
    elif index % 5 == 0:
        result += index
        print index
    pass
 
 
print result
cs

1000에서는 233168





3) 구글 입사문제

문제: http://codingdojang.com/scode/393

1
2
3
4
5
6
7
8
9
10
11
12
13
max = 10000
cnt = 0
 
for index in range(1, max):
    tmp = index
    while tmp > 0:
        if tmp % 10 == 8:
            cnt += 1
        tmp /= 10
    pass    #END. while tmp > 0:
pass    #END. for index in range(1, max):
 
print cnt
cs





4) 삽입정렬

문제: http://codingdojang.com/scode/443

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
g_list = [524613]
listLeng = len(g_list)
 
for index in range(1, listLeng):
    tmp = g_list[index]
    leftIdx = index - 1
 
    while ( leftIdx >= 0 and g_list[leftIdx] > tmp):
        g_list[leftIdx + 1] = g_list[leftIdx]
        g_list[leftIdx] = tmp
        print "loop. index=" + str(index) + ", leftIdx=" + str(leftIdx) + ", "  + str(g_list)
        leftIdx -= 1
        # END. while
    pass    # END. for index in range(1, listLeng):
 
print str(g_list)
cs


이미지출처: http://effectiveprogramming.tistory.com/19




2. 난이도, Lv 2


1) 아마존 면접문제

문제: http://codingdojang.com/scode/416

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
g_list = [102030405060708090112131415161718191]
limit = len(g_list) / 2
aList = []
bList = []
print "START. " + str(g_list)
 
for index in range(0, limit):
    aList.append( g_list[index] )
    bList.append( g_list[index + limit] )
    """
    해당 반복문은 아래의 2줄로도 가능하긴 함.
    aList = g_list[0:limit]
    bList = g_list[limit:len(g_list)]
    """
    pass
print "aList =" + str(aList)
print "bList =" + str(bList)
 
g_list = []
for index in range(0, limit):
    g_list.append( aList[index] )
    g_list.append( bList[index] )
    pass
print "FINAL. " + str(g_list)
cs




2) 문자열 압축하기

문제: http://codingdojang.com/scode/465

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
msg = "aaabbcccccca"
resultMsg = ""
msgLeng = len(msg) - 1
cnt = 1
index = 0
 
for index in range(0, msgLeng):
    if ( msg[index] == msg[index + 1] ):
        cnt += 1
        pass
    else:
        resultMsg += ( msg[index] + str(cnt) )
        cnt = 1
        if( index+1 == msgLeng ):
            resultMsg += ( msg[index+1] + str(1) )
            pass
        pass
    pass
 
print resultMsg
cs





3) 구글 전화면접

문제: http://codingdojang.com/scode/414

1
2
3
4
5
6
7
8
9
10
11
12
13
14
g_list = [-113, -22]
leftList = []
rightList = []
 
for index in range ( 0len(g_list) ):
    tmp = g_list[index]
 
    if( tmp < 0 ):
        leftList.append(tmp)
    else:
        rightList.append(tmp)
    pass
 
print leftList + rightList
cs





4) 10진수 변환

문제: http://codingdojang.com/scode/458

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def binaryNum(res, divN, result = ""):
    if( divN < 2 and 16 < divN):
        return
 
    if(res < 1 ):
        print result + "[" + str(divN) + "]"
        return
    else:
        tmp = res % divN
        if tmp > 10:
            result = chr( 65 + (tmp-10) ) + result
            pass
        else:
            result = str(tmp) + result
            pass
        tmpInt = res/ divN
        binaryNum( tmpInt, divN, result )
    pass
 
binaryNum(23316"")  #입력
cs





5) 비슷한 단어 찾아내기

문제: http://codingdojang.com/scode/445

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def oneEditApart(arg0Str, arg1Str):
    cntF = 0
    block = 0
    tmp = len(arg0Str) - len(arg1Str)
 
    if( tmp > 0 ):
        for index in range (0len(arg0Str)-1):
            if( arg0Str[index:index+1] == arg1Str[0:1] ):
                block = index
                break
            pass
        arg1Str = ('_' * block) + arg1Str
        pass    #END. if( tmp > 0 ):
    elif( tmp < 0 ):
        for index in range (0len(arg1Str)-1):
            if( arg1Str[index:index+1] == arg0Str[0:1] ):
                block = index
                break
            pass
        arg0Str = ('_' * block) + arg0Str
        pass    #END. elif( tmp < 0 ):
 
    for index in range (0len(arg0Str) ):
        if ( arg0Str[index]==arg1Str[index] ):
            cntF += 1/( float(len(arg0Str)) )
            pass
        pass
 
    if( cntF > 0.5 ):
        print "TRUE\t" + arg0Str + "/" + arg1Str
    else:
        print "FALSE\t" + arg0Str + "/" + arg1Str
    pass    #END. def oneEditApart(arg0Str, arg1Str):
 
oneEditApart("cat""dog")
oneEditApart("cat""cats")
oneEditApart("cat""cut")
oneEditApart("cat""cast")
oneEditApart("cat""at")
oneEditApart("cat""acts")
cs





3. 난이도, Lv 3


1) Spiral Array

문제: http://codingdojang.com/scode/266

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def spiralArray(rowLeng, colLeng):
    spiralMetrix = [[0 for col in range(colLeng)] for row in range(rowLeng)]
 
    direction = 1
    mx = 0
    index = 0
    while (index < colLeng * rowLeng):
        idx = 0
        if(direction == 1):   #RIGHT
            for idx in range (mx, colLeng - mx):
                spiralMetrix[mx][idx] = index
                index += 1
                pass
            direction = direction << 1
            pass
        elif(direction == 2):   #DOWN
            for idx in range (mx+1, rowLeng - mx):
                spiralMetrix[idx][colLeng - (mx+1)] = index
                index += 1
                pass
            direction = direction << 1
            pass
        elif(direction == 4):   #LEFT
            for idx in range (colLeng - (mx+2) , mx-1, -1):
                spiralMetrix[rowLeng - (mx+1)][idx] = index
                index += 1
                pass
            direction = direction << 1
            pass
        elif(direction == 8):   #UP
            for idx in range (rowLeng - (mx+2), mx, -1):
                spiralMetrix[idx][mx] = index
                index += 1
                pass
            mx += 1
            direction = direction >> 3
            pass
 
        #   REULT
        print "\n\tloop. " + str(index) + ", " + str(direction)
        for i in spiralMetrix:
            print i
            pass
    pass
 
spiralArray(66);
cs






2) 그 시간 사무실에 몇 명이 있었나?(아마존 면접)

문제: http://codingdojang.com/scode/418

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
log = """09:12:23 11:14:35
09:04:00 12:00:00
11:06:00 12:00:45
10:34:01 13:23:40
09:04:00 11:00:00
10:34:31 11:20:10"""
 
def howMany(logStr, time):
    personCheck = log.splitlines()
    personNum = len(personCheck)
    cnt = 0
    hour = int(time[0:2])
    minute = int(time[3:5])
    second = int(time[6:8])
 
    for index in range(0, personNum):
        tmp = personCheck[index].split(' ')
        inTime = tmp[0]
        outTime = tmp[1]
 
        if( hour == int(inTime[0:2]) ):
            if( minute > int(inTime[3:5]) ):
                cnt += 1
                pass
            elif( minute == int(inTime[3:5]) and second >= int(inTime[6:8]) ):
                cnt += 1
                pass
            pass
        elifint(inTime[0:2]) < hour < int(outTime[0:2]) ):
            cnt += 1
            pass
        elif( hour == int(outTime[0:2]) ):
            if( minute < int(outTime[3:5]) ):
                cnt += 1
                pass
            elif( minute == int(outTime[3:5]) and second <= int(outTime[6:8]) ):
                cnt += 1
                pass
            pass
        pass    #END. for index in range(0, personNum):
 
    print time + ", " + str(cnt) + "person(s)."
    pass    #END. def howMany(logStr, time):
 
howMany(log, "09:30:00")
howMany(log, "11:05:20")
cs




3) Ugly Numbers

문제: 

처음에 시도한 아래의 코드는 사실 계산상 문제는 없지만 저조한 퍼포먼스.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import time;
 
def uglyNumber(nthNum):
    _t = time.time();
    resultFt = 0.0;
    listCnt = 1;
    idxFt = 1.0;
 
    while (listCnt < nthNum):
        if( degradedNum(idxFt) ):
            print "[" + str(listCnt+1+ "] " + str(idxFt);
            listCnt += 1;
            resultFt = idxFt;
            pass
        idxFt += 1.0;
        pass
 
    print str(resultFt) + ',   %.02f seconds' % (time.time() - _t);
    pass    # END. def uglyNumber(nthNum):
 
def degradedNum(input):
    tmp = input;
    if(tmp%2 == 0):
        while (tmp%2 == 0):
            tmp /= 2;
            if (tmp == 1):
                return True;
            pass
        pass
    if(tmp%3 == 0):
        while (tmp%3 == 0):
            tmp /= 3;
            if (tmp == 1):
                return True;
            pass
        pass
    if(tmp%5 == 0):
        while (tmp%5 == 0):
            tmp /= 5;
            if (tmp == 1):
                return True;
            pass
        pass
    return False;
    pass    # END. def degradedNum(isEven, input):
 
uglyNumber(1550)
cs






4) 숫자에 콤마 삽입

문제: http://codingdojang.com/scode/398

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def setComma(arg):
    mark = "";
    if (arg< 0):
        mark = "-";
        arg *= -1;
        pass
 
    #    소수점 이하 분리.
    pointFt = float(arg - int(arg));
    tmpPtStr = str(pointFt);
    arg -= pointFt;
    arg = int(arg);
    
    tmpStr = str(arg);
    msgStr = "";
    idx = 0;    #콤마 표기용 idx값
    for index in range (len(tmpStr)-1-1-1):
        if(idx % 3 == 0 and idx > 1):
            msgStr = "," + msgStr;
            pass
        idx += 1;
        msgStr = tmpStr[index] + msgStr;
        pass
 
    print mark + msgStr + tmpPtStr[1:len(tmpPtStr)];
    pass
 
setComma(1000);
setComma(20000000);
setComma(-3245.24);
cs






5) 앞뒤가 같은 수

문제: http://codingdojang.com/scode/401


1안. 재귀함수 사용시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import time;
 
def getPairNum(arg):
    cntInt = 0;
    result = -1;
    _t = time.time();
 
    if(arg == 0):
        print "pairNum[" + str(arg) + "]=1";
        return;
 
    while (cntInt < arg):
        result += 1;
        tmpStr = str(result);
        strLeng = len(tmpStr);
        if( result < 10 ):
            cntInt += 1;
            pass
        elif( result < 100 ):
            if( tmpStr[0== tmpStr[1] ):
                cntInt += 1;
            pass
        elif( result < 1000 ):
            if(tmpStr[0== tmpStr[2]):
                cntInt += 1;
            pass
        elif(tmpStr[0== tmpStr[strLeng-1and tmpStr[1== tmpStr[strLeng-2]):
            if( result < 10000 ):
                cntInt += 1;
            elif( checkPair(tmpStr, 0, strLeng) ):
                cntInt += 1;
        pass;    # while (cntInt < arg):
 
    print "pairNum[" + str(arg) + "]=" + str(result) + ',   %.04f seconds' % (time.time() - _t);
    pass;    # def getPair(arg):
 
def checkPair(msg, token, gap):
    #print str(gap) + ", msg=" + str(msg);
    if(len(msg)%2==0 and gap<1):
        return True;
        pass
    elif(len(msg)%2!=0 and gap<2):
        return True;
        pass
    elif(msg[token] == msg[gap-1]):
        token += 1;
        gap -= 2;
        checkPair(msg, token, gap)
        pass
    else:
        return False;
    pass    # def checkPair(msg, msgLeng):
 
getPairNum(1);
getPairNum(4);
getPairNum(20);
getPairNum(21);
getPairNum(30);
getPairNum(100);
getPairNum(1000);
getPairNum(1001);
getPairNum(30000);
getPairNum(1000000);
cs



2안.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import time;
 
def getPairNum(arg):
    cntInt = 0;
    result = -1;
    _t = time.time();
 
    if(arg == 0):
        print "pairNum[" + str(arg) + "]=1";
        return;
 
    while (cntInt < arg):
        result += 1;
        tmpStr = str(result);
        strLeng = len(tmpStr);
        if( result < 10 ):
            cntInt += 1;
            pass
        elif( result < 100 ):
            if( tmpStr[0== tmpStr[1] ):
                cntInt += 1;
            pass
        elif( result < 1000 ):
            if(tmpStr[0== tmpStr[2]):
                cntInt += 1;
            pass
        elif(tmpStr[0== tmpStr[strLeng-1and tmpStr[1== tmpStr[strLeng-2]):
            if( result < 10000 ):
                cntInt += 1;
            elif( checkPair(tmpStr, strLeng) ):
                cntInt += 1;
        pass;    # while (cntInt < arg):
 
    print "pairNum[" + str(arg) + "]=" + str(result) + ',   %.04f seconds' % (time.time() - _t);
    pass;    # def getPair(arg):
 
def checkPair(msg, msgLeng):
    rangeEnd = int(msgLeng/2);
    head = -1;
 
    for head in range(0, rangeEnd):
        rear = msgLeng - 2*head - 1;
        if(rear < 3):
            return True;
            pass;
        elif(msg[head] != msg[rear]):
            return False;
        pass;
 
    pass    # def checkPair(msg, msgLeng):
 
getPairNum(1);
getPairNum(4);
getPairNum(20);
getPairNum(21);
getPairNum(30);
getPairNum(100);
getPairNum(1000);
getPairNum(1001);
getPairNum(30000);
getPairNum(1000000);
cs





6) 넥슨 입사문제, 셀프 넘버

문제: http://codingdojang.com/scode/365


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def selfNumAcc(start, end):
    resultInt = 0;
    generateList = [];
    tmpToken = [];
 
    for index in range(start, end):
        generateList.append( getGenerator(index) );
        pass;
    #print str(generateList);
 
    for index in range(start, end):
        if( index not in generateList):
            resultInt += index;# print str(index) + ", " + str(resultInt);
            pass
        pass;
    print str(start) + "~" + str(end) + " self num sum = " + str(resultInt);
 
    pass;    # def selfNumAcc(start, end):
 
def getGenerator(arg):
    tmpSum = arg;
    while(arg > 0):
        tmpSum += (arg%10);
        arg //= 10# quotient
        pass;
    return tmpSum;
    pass;
 
selfNumAcc(15000);
cs


답: 1227365







기타. 변경이력


일자

변경이력

2015-03-10

 초안.