정보처리기사 실기 코딩 공부

by 민갤

Back End /

공부 도서: 2021 이기적 정보처리기사 실기
공부 사이트: 수제비 IT 커뮤니티 네이버 공식 카페, 구글링

1. 정렬

거품 정렬 (Bubble Sort)

인접한 두 데이터를 비교하여 기준을 만족하면 서로의 위치를 바꾼다.
한 회전이 끝날 때마다 뒤에서부터 정렬이 완료된다.

#include <stdio.h>

int main(void) {
    int i, j;
    int temp;
    int a[5] = {14, 22, 53, 45, 1};
    
    for(i=0; i<4; i++)
    {
        for(j=0; j<4-i; j++)
        {
            if(a[j] > a[j + 1])
            {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
    
    for(i=0; i<5; i++)
    {
        printf("%d\n", a[i]);
    }
    return 0;
}
1
14
22
45
53

선택 정렬(Selection Sort)

처리되지 않은 데이터 중에서 가장 작은 데이터를 선택해 맨 앞에 있는 데이터와 바꾸는 것을 반복

list = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]

for i in range(len(list)):
    min_idx = i    # 가장 작은 데이터의 인덱스
    for j in range(i + 1, len(list)):
        if list[min_idx] > list[j]:
            min_idx = j
    list[i], list[min_idx] = list[min_idx], list[i]

print(list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

삽입 정렬(insertion sort)

처리되지 않은 데이터를 하나씩 골라 적절한 위치에 삽입
첫 번째 데이터는 그 자체로 정렬되어 있다고 판단하고, 두 번째 데이터부터 앞에 정렬된 데이터와 비교하여 삽입할 위치를 판단한다.
처음 KEY 값은 두 번째 자료부터 시작한다.

array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]

for i in range(1, len(array)):
    # 뒤에서부터 정렬
    for j in range(i, 0, -1):
        if array[j] < array[j - 1]:
            array[j], array[j - 1] = array[j - 1], array[j]
        else:
            break

print(array)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#include <stdio.h>

int main(void) {
    int i, j, min_key;
    int list[5] = {14, 22, 53, 45, 1};
    
    for(i=1; i<5; i++)
    {
        min_key = list[i];
    
        for(j=i-1; j>=0 && list[j]>min_key; j--)
        {
            list[j+1] = list[j];
        }
        list[j+1] = min_key;
    }
    
    for(i=0; i<5; i++)
    {
        printf("%d\n", list[i]);
    }
    return 0;
}
1
14
22
45
53

2. C

C++ 생성자와 소멸자

#include <iostream>
class A {
    public:
        A() {
            std::cout << "A ";
        }
        ~A() {
            std::cout << "~A ";
        }
};
class B : public A {
    public:
        B() {
            std::cout << "B ";
        }
        ~B() {
            std::cout << "~B ";
        }
};

void main() {
    A* a = new B();
    delete a;
    std::cout << std::endl;
    B* b = new B();
    delete b;
}
A B ~A 
A B ~B ~A 

비트 연산자

  • & : 비트 AND 연산자는 같이 자리수가 둘 다 1이면 1
  • | : 비트 OR 연산자는 같은 자리수가 하나라도 1이면 1
  • ^ : 비트 XOR 연산자는 같은 자리수가 둘 다 1이거나 0이면 0
#include <stdio.h>
void main()
{
    int a = 7;
    int b = 4;
    int x = a & b;
    int y = a | b;
    int z = a ^ b;
    printf("결과 x : %d\n", x);
    printf("결과 y : %d\n", y);
    printf("결과 z : %d\n", z);
}
4
7
3

문자열 상수와 포인터

  • 문자열은 문자들의 집합으로, 연속된 주소에 한 문자씩 저장되며 문자열의 끝을 의미하는 널 문자(\0)가 마지막 주소에 위치한다.
  • printf 함수의 포맷 %s : 주소의 내용을 '\0'(NULL)전까지 출력한다.
  • char *p : 문자열 상수의 시작 주소를 가진다.
#include <stdio.h>
 
int main(void) {
    char str[] = "KOREA";
    printf("%s\n", str);
    printf("%s\n", str + 3);
    printf("%c\n", str[0]);
    printf("%p\n", str);
    printf("%p\n", &str);
 
    char *p = "KOREA";
    printf("%s\n", p);
    printf("%s\n", p + 3);
    printf("%c\n", *p);
    printf("%c\n", *(p + 3));
    printf("%c\n", *p + 3);
    printf("%p\n", p);
    printf("%p\n", &p);
    return 0;
}
KOREA
EA
K
0x7ffda8806762
0x7ffda8806762

KOREA
EA
K
E
N
0x55e14ac42010
0x7ffeda2b30a8
  • printf("%s\n", p); : p 주소부터 '\0'전까지 내용 출력
  • printf("%s\n", p + 3); : p 위치로부터 3칸 떨어진 거리에 있는 주소부터 '\0'전까지 내용 출력
  • printf("%c\n", *p); : *는 포인트 연산자. 주소의 내용 출력한다. p는 K의 주소를 가지고 있으므로 K 출력
  • printf("%c\n", *(p + 3)); : P 위치로부터 3칸 떨어진 거리에 있는 주소의 내용을 출력
  • printf("%c\n", *p + 3); : p의 주소 내용(문자열 상수 시작주소 = K) + 3
문자열 상수 "KOREA"
주소100101102103104105
데이터KOREA\0

3. JAVA

2진수 구하기

import java.util.*;
import java.lang.*;
import java.io.*;

class Test
{
    public static void main (String[] args)
    {
        int[] arr = new int[8];
        
        int n = 11;
        int i = arr.length - 1;
        
        while(n != 0)
        {
            arr[i] = n % 2;
            n /= 2;
            i--;
        }
        
        for(int j=0; j<arr.length; j++)
        {
            System.out.printf("%d", arr[j]);
        }
    }
}
00001011

상속

생성 객체가 부모, 자식 순으로 실행된다.
매개변수가 있는 생성자로 초기화할 경우, 부모의 기본 생성자를 실행하고, 자식은 매개변수 생성자를 실행한다.

class Super
{
    public Super()
    {
        System.out.print("Super ");
    }

    public Super(int a)
    {
        System.out.print("PSuper "+a+" ");
    }
}

class Sub extends Super
{
    public Sub()
    {
        System.out.print("Sub ");
    }

    public Sub(int a)
    {
        System.out.print("PSub "+a+" ");
    }
}

public class Test {
    public static void main(String[] args) {
        Super a = new Sub();
        Sub b = new Sub();

        System.out.println("");

        Super c = new Sub(10);
        Sub d = new Sub(20);
    }
}
Super Sub Super Sub 
Super PSub 10 Super PSub 20 

static 활용

class Test
{
    public static void main (String[] args)
    {
        Number n1 = new Number();
        Number n2 = new Number();
 
        n1.increment();
        n2.increment();
        n2.increment();
        n1.decrement();
        n1.printNumber();
        n2.printNumber();
    }
}
 
class Number
{
    static public int num1 = 0;
    public int num2 = 0;
    public void increment()
    {
        num1++;
        num2++;
    }
    public void decrement()
    {
        num1--;
        num2--;
    }
    public void printNumber()
    {
        System.out.println("num1 : " + num1);
        System.out.println("num2 : " + num2);
    }
}
num1 : 2
num2 : 0
num1 : 2
num2 : 2

2차원 배열

public class Test
{
    public static void main(String[] args)
    {
        double score[][] = { {80, 90}, {70, 80}, {60, 100} };
        double sum = 0;
        for(int i=0; i<score.length; i++)
        {
            for(int j=0; j<score[i].length; j++)
            {
                sum+= score[i][j];
            }
        }

        int row = score.length;
        int col = score[0].length;
        System.out.println(sum / (row*col));
    }
}
80.0

반복문과 문자열에서 문자 추출 함수

class Test
{
    public static void main (String[] args)
    {
        String text = "Love is a variety of different feelings , states, and"
        + "attitudes that ranges from interpersonal affection to pleasure.";

        int cnt = 0;
        for(int i=0; i<text.length(); i++)
            if(text.charAt(i) == 'a') cnt++;

        System.out.println("a문자: " + cnt);
    }
}
a문자: 10
class Test
{
    public static void main (String[] args)
    {
        int[] arr = {1, 2, 3, 4, 5};
        int sum = 0;

        for(int i : arr)
        {
            sum+= i;
            if(i != arr.length)
                System.out.print(i + "+");
            else
                System.out.print(i + "=");
        }
        System.out.println(sum);
    }
}
1+2+3+4+5=15

4. Python

문자열 연산

strings = "If you come at 4 o’clock"
print(strings)
print(len(strings)) # string length

# indexing
print(strings[0])
print(strings[3])
print(strings[12])
print(strings[-1])

# slicing
print(strings[0:3])
print(strings[1:3])
print(strings[:])
print(strings[:-1])

str1 = 'If you come at 4 o’clock'
str2 = ', I will be happy from 3 o’clock.'
str3 = str1 + str2 # concatenation
print(str3)
str4 = str3 * 2 # repetition
print(str4)

# member check
print(',' in str3)
print('!' in str3)
If you come at 4 o’clock
24
I
y
a
k
If 
f 
If you come at 4 o’clock
If you come at 4 o’cloc
If you come at 4 o’clock, I will be happy from 3 o’clock.
If you come at 4 o’clock, I will be happy from 3 o’clock.If you come at 4 o’clock, I will be happy from 3 o’clock.
True
False

증감 연산

i = 10
i+= 1
print(i)
i-= 2
print(i)
++i    # 아무 동작도 하지 않음
print(i)
#i++    # 오류 발생
11
9
9

사용자 정의 함수

def print_reverse(string):
    print(string[::-1].upper())

print_reverse('python')
NOHTYP
def add(a, b):
    return a + b

print(add(2, 3))
print(add(3.14, 5.5))
print(add(1+2j, 3+4j))
print(add("abs", "def"))
5
8.64
(4+6j)
absdef

배열

a = [4, 2, 7, 3, 5]
print(a[-2])     # 뒤에서 두번째 위치에 있는 데이터
print(a[4])      # index가 4인 데이터
print(a[0:2])    # 0 <= index < 2 범위에 있는 데이터
print(a[::-1])
3
5
[4, 2]
[5, 3, 7, 2, 4]

 문자열 소문자 변환 + 나누기

email = 'LoveMe@gmail.com'
email = email.lower()
id = email.split('@')[0]
print(id)
loveme

모듈 사용하기

import random
min = 1
max = 6
i = 0
while i < 3:
    num = random.randint(min, max)
    print(num, end='')
    i = i + 1
613(실행할 때마다 다름)

Dictionary(딕셔너리)

순서가 없는 불변의 키(Key)와 가변의 값(Value)의 쌍으로 이루어진 객체들의 집합

country = {'대한민국':'서울', '미국':'워싱턴', '독일':'베를린'}
print(country.keys())
print(country.values())
print(country.items())
print(country.get('대한민국'))
country['대한민국'] = 'Seoul'
print(country.get('대한민국'))
dict_keys(['대한민국', '미국', '독일'])
dict_values(['서울', '워싱턴', '베를린'])
dict_items([('대한민국', '서울'), ('미국', '워싱턴'), ('독일', '베를린')])
서울
Seoul
fruits = {"banana":[500, 20], "apple":[1000, 10], "kiwi":[250, 5]}

price_amount = fruits.values()
payment = 0
for amt in price_amount:
    payment += amt[0] * amt[1]

print('지불금액: %d원' % payment)
지불금액: 21250원

List

순서가 있는 가변의 객체들의 모임

a = [10, 20]
b = [30, 40]

print(a + b)
print(a * 2)

a.append([10, 2]); print(a)    # 뒤에 추가
a.extend([10, 2]); print(a)    # 뒤에 병합
a.insert(1, 8); print(a)       # index 1에 값 삽입 (변경 X)
a.remove(10); print(a)         # 값 삭제 (여러 개이면 첫 번째만 삭제)
a.remove(10); print(a)
a.reverse(); print(a)          # 역순 정렬
a[0] = 5; print(a)             # index 5에 값 변경
[10, 20, 30, 40]
[10, 20, 10, 20]
[10, 20, [10, 2]]
[10, 20, [10, 2], 10, 2]
[10, 8, 20, [10, 2], 10, 2]
[8, 20, [10, 2], 10, 2]
[8, 20, [10, 2], 2]
[2, [10, 2], 20, 8]
[5, [10, 2], 20, 8]

Set

임의의 순서를 가진 중복되지 않은 요소들의 가변 모임

travel = {'서울', '제주', '대전', '부산'}
print("제주" in travel)
print("춘천" in travel)
travel.add('제주'); print(travel)
travel.add("군산"); print(travel)
travel.remove('대전'); print(travel)
travel.remove("부산"); print(travel)
travel.update(['강화','순천']); print(travel)
travel.clear()
print(travel)
True
False
{'대전', '서울', '제주', '부산'}
{'부산', '제주', '군산', '대전', '서울'}
{'부산', '제주', '군산', '서울'}
{'제주', '군산', '서울'}
{'제주', '군산', '서울', '순천', '강화'}
set()
a = set()
a.add(1)
a.add(9)
a.add(5)
a.add(1)
print(a)

b = {3, 5, 1}

print(a | b)    # 합집합
print(a & b)    # 교집합
print(a - b)    # a 에서 b의 요소 제거
print(a ^ b)    # a 와 b 공통 요소 제거
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
{1, 5, 9}
{1, 3, 5, 9}
{1, 5}
{9}
{9, 3}
{1, 3, 5, 9}
{1, 5}
{9}
{9, 3}

Tuple (튜플)

순서가 있는 불변의 객체들의 모임

tuple = ()
print(tuple)

tuple = (1, 2)
tuple = tuple + (3, 4)
print(tuple)

tuple = 1, 3
print(tuple)

print(tuple * 2)
print(3 in tuple)
print(type(tuple))

tuple = ("python", (1, 3, 5))
print(tuple)
print(tuple[0][0])
print(tuple[1][0])

#tuple[0] = 4    # 오류
()
(1, 2, 3, 4)
(1, 3)
(1, 3, 1, 3)
True
<class 'tuple'>
('python', (1, 3, 5))
p
1

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓