25. 06. 06 공부일지

behumble·2025년 6월 10일

공부일지

목록 보기
19/20

회고

기본적인 파이썬 문법과 내장 함수들을 다양한 문제에 적용해보며 실력을 다질 수 있었다.
for/while, sort/sorted, map, join 등 함수와 반복문의 차이를 실제로 써보며 명확히 이해했다. 실습을 통해 작은 코드의 차이가 결과에 어떻게 영향을 주는지 몸소 체감할 수 있었다.

keywords

✅ sort() : 리스트를 그대로 정렬하고 싶을 때
✅ sorted() : 원래 리스트를 유지하면서, 정렬된 복사본 생성
✅ for 반복문 : 횟수가 정해져 있을 때 사용
✅ while 반복문 : "~할때까지"라는 느낌이 있을 때 사용
✅ map() : 리스트 안의 모든 값에 어떤 작업을 한번에 똑같이 해줌
✅ swapcase() : 대문자는 소문자로, 소문자는 대문자로
✅ index() : 리스트나 문자열에서 특정 값이 처음 나오는 위치를 알려주는 함수
✅ replace() : 문자열에서 특정 글자를 다른 글자로 바꿔주는 함수
✅ join() : join() : 여러개의 문자열을 하나로 붙여주는 함수

programmers

삼각형의 완성 조건

def solution(sides):
    sides.sort(reverse = True)
    total = sides[1] + sides[2]
    if sides[0] < total:
        answer = 1
    else:
        answer = 2
    return answer
  • sort()와 a = list.sorted()의 사용법 차이
    -- sort() : 리스트를 그대로 정렬하고 싶을 때
    -- a = list.sorted() : 원래 리스트는 두고, 정렬된 복사본이 필요할 때

배열자르기

def solution(numbers, num1, num2):
    answer = numbers[num1:num2+1:1]
    return answer
  • 파이썬의 인덱스는 0부터 시작한다는 것에 주의!

피자자르기

def solution(slice, n):
    pizzas = 0
    while pizzas * slice < n:
        pizzas += 1
    return pizzas
  • 같은 반복문인 for문과 while문의 사용시기에 대해 헷갈리는 경우가 종종 발생하고 있다.
    -- for : 횟수가 정해져 있을 때 사용(예시 : 10번 반복을 해야해)
    -- while : 조건일 참일동안 반복(예시 : ~~할때까지)

점의 위치 구하기

def solution(dot):
    if dot[0] > 0 and dot[1] > 0: # 1사분면
        answer = 1
    elif dot[0] < 0 and dot[1] > 0: # 2사분면
        answer = 2
    elif dot[0] < 0 and dot[1] < 0: # 3사분면
        answer = 3
    else:
        answer = 4
    return answer

배열의 유사도

def solution(s1, s2):
    count = 0
    for i in s1:
        if i in s2:
            count += 1
    return count

순서쌍의 개수

def solution(n):
    num_list = []
    for i in range(1,n+1):
        if n % i == 0:
            num_list.append(i)
    return len(num_list)

n의 배수 고르기

def solution(n, numlist):
    newlist = []
    for i in range(len(numlist)):
        if numlist[i] % n == 0:
            newlist.append(numlist[i])
    return newlist

배열 원소의 길이

def solution(strlist):
    lenlist = []
    for i in strlist:
        lenlist.append(len(i))
    return lenlist

아이스 아메리카노

def solution(money):
    newlist = []
    countcoffee = money // 5500
    newlist.append(countcoffee)
    change = money - (5500 * countcoffee)
    newlist.append(change)
    return newlist

중복된 숫자개수

def solution(array, n):
    count = 0
    for num in array:
        if num == n:
            count += 1
    return count

배열 두배 만들기

def solution(numbers):
    doublelist = []
    for n in numbers:
        n = n * 2
        doublelist.append(n)
    return doublelist

중앙값 구하기

def solution(array):
    array.sort()
    return array[len(array) // 2]

짝수는 싫어요

def solution(n):
    oddlist = []
    for num in range(1,n+1):
        if num <= n and num % 2 != 0:
            oddlist.append(num)
    return oddlist

옷가게 할인받기

def solution(price):
    if price >= 500000:
        pay = price * 0.8
    elif price >= 300000:
        pay = price * 0.9
    elif price >= 100000:
        pay = price * 0.95
    else:
        pay = price
    return pay

개미군단

def solution(hp):
    j_ant = hp // 5 
    hp =  hp % 5 
        
    b_ant =  hp // 3
    hp = hp % 3
        
    i_ant = hp
    return j_ant + b_ant + i_ant

숨어있는 숫자의 덧셈

def solution(my_string):
    digit_list = []
    for i in my_string:
        if i.isdigit() == True:
            digit_list.append(i)
    intdigit_list = list(map(int,digit_list))
    # digit_list의 값을 int로 전부 바꿔서 list로 변환한다.
    total = sum(intdigit_list)
    return total
  • map : 리스트 안의 모든 값에 어떤 작업을 한번에 똑같이 해줌
    -- 기본구조 : map(함수, 반복가능한 자료)

최댓값 만들기

def solution(numbers):
    numbers.sort(reverse = True)
    max_num1 = numbers[0] * numbers[1]
    max_num2 = numbers[-1] * numbers[-2]
    if max_num1 > max_num2:
        answer = max_num1
    else:
        answer = max_num2
    return answer

암호해독

def solution(cipher, code):
    result = ''
    for i in range(1, len(cipher) + 1):
        if i % code == 0:
            result += cipher[i - 1]
    return result

대문자와 소문자

def solution(my_string):
    swap_string = my_string.swapcase()
    return swap_string
  • swapcase() : 대문자는 소문자로, 소문자는 대문자로 바꿔주는 함수

인덱스바꾸기

def solution(my_string, num1, num2):
    new_list = list(my_string)
    new_list[num1], new_list[num2] = new_list[num2], new_list[num1]
    return ''.join(new_list)

약수구하기

def solution(n):
    measure_list = []
    for i in range(1,n+1):
        if n % i == 0:
            measure_list.append(i)
    return measure_list

가장 큰 수 찾기

def solution(array):
    max_num = max(array)
    max_idx = array.index(max_num)
    return [max_num, max_idx]
  • max() : 리스트나 문자열에서 가장 큰 값을 찾아주는 함수
    -- 문자열의 경우 사전에서 뒤에 있는 문자일수록 큰 값임
  • index() : 리스트나 문자열에서 특정 값이 처음 나오는 위치를 알려주는 함수

문자열 정렬하기

def solution(my_string):
    lower_string = my_string.lower()
    abc_string = sorted(lower_string)
    string = ''.join(abc_string)
    return string
  • sorted 사용이유
    -- lower_string이 문자열이기 때문
  • sort() : 리스트만 사용가능, sorted() : 문자열, 리스트 모두 가능

숫자 찾기

def solution(num, k):
    num_str = str(num)
    for i in range(len(num_str)):
        if num_str[i] == str(k):
            return i + 1
    return -1

문자 반복 출력하기

def solution(my_string, n):
    result_list = []
    for i in range(len(my_string)):
        result_list.append(my_string[i] * n)
    result = ''.join(result_list)
    return result
  • join() : 여러개의 문자열을 하나로 붙여주는 함수
    -- 기본사용법 : "구분자".join(문자열리스트)

    words = ['apple', 'banana', 'cherry']
    result = ','.join(words)
    
    print(result)  # 👉 'apple,banana,cherry'

공배수

def solution(number, n, m):
    if number % n == 0 and number % m == 0:
        return 1
    else:
        return 0

더 크게 합치기

def solution(a, b):
    plus1 = str(a) + str(b)
    plus2 = str(b) + str(a)
    if plus1 > plus2:
        return int(plus1)
    elif plus1 == plus2:
        return int(plus1)
    else:
        return int(plus2)

문자열 붙여서 출력하기

str1, str2 = input().strip().split(' ')
string = str1 + str2
new = string.replace(" ", "")
print(new)
  • replace() : 문자열에서 특정 글자를 다른 글자로 바꿔주는 함수
    -- 문자열.replace(바꿀문자, 새문자)

문자리스트를 문자열로 변환하기

def solution(arr):
    arr_list = ''.join(arr)
    return arr_list

약수의 합

def solution(n):
    measure = []
    for i in range(1, n+1):
        if n % i == 0:
            measure.append(i)
    return sum(measure)

자릿수 더하기

def solution(N):
    str_N = str(N)                   
    list_N = list(map(int, str_N))    
    total = sum(list_N)               
    return total

x만큼 간격이 있는 n개의 숫자

def solution(x, n):
    result = []
    for i in range(1, n+1):
        xx = x * i
        result.append(xx)
    return result

나머지가 1이 되는 수

def solution(n):
    for x in range(1, n+1):
        if n % x == 1:
            return x

0개의 댓글