[월말평가 대비]

체리마루·2024년 1월 28일

[함수 만들기 연습]

- 리스트에서 최솟값을 구하는 로직 (min() 사용 불가)

#1
import sys

def find_min(lst):
    min_value = lst[0]
    for i in lst:
        if i < min_value:
            min_value = i

    return min_value

lst = list(map(int, sys.stdin.readline().split()))
print(find_min(lst))
#2
import sys

def find_min(lst):
    min_value = lst[0]
    for i in lst:
        if i < min_value:
            min_value = i

    return min_value

lst = [2, 5, 9, 10, 3, 2]
print(find_min(lst))

- 딕셔너리 데이터에서 내가 원하는 물건의 총합을 계산해서 반환하는 로직

#1
import sys

def calculate_total(dic, items):
    total = 0
    for item in items:
        if item in dic:
            total += dic[item]
    return total


dic = {"사과": 1000, "바나나": 800, "오렌지": 1200}
items = sys.stdin.readline().strip().split()

print(calculate_total(dic, items))
#2
def menuprice(dic, items):
    total = 0
    for i in items:
        if i in dic:
            total += dic[i]
    return total


price_dict = {'커피' : 5000, '과자': 3000, '음료': 2000 , '양말': 1000}
print(menuprice(price_dict, ['커피', '과자', '양말']))

- 평균값 계산 (sum(), len() 사용 불가)

#1
def calculate_average(lst):
    total = 0
    count = 0
    for num in lst:
        total += num
        count += 1

    return total / count

print(calculate_average([1, 2, 3, 4, 5]))
#2
def make_average(lst):
    total = 0
    count = 0
    for num in lst:
        total += num
        count += 1

    return int(total / count)

num_list = [300, 200, 50, 400, 20]
print(make_average(num_list))   # 194

- 리스트 안에서 특정 문자열이 담긴 문자열의 개수를 카운트 (카운트해서, 딕셔너리화 해야됨)

#1
def count_keyword(lst, keyword):
    result_dict = {}
    for string in lst:
        if keyword in string:
            if string in result_dict:
                result_dict[string] += 1
            else:
                result_dict[string] = 1
    return result_dict

print(count_keyword(['pineapple', 'lemon', 'apple', 'apple candy', 'melon', 'watermelon'], 'apple'))

ex) 매터모스트 혈액형 문제

def total_people(bloods):
    total = 0
    for _ in bloods:
        total += 1
    return total

def type_of_blood(bloods):
    types = []
    for blood in bloods:
        if blood not in types:
            types.append(blood)
    return types

def getsu(bloods):
    count_dict = {}
    for blood in bloods:
        if blood in count_dict:
            count_dict[blood] += 1
        else:
            count_dict[blood] = 1
    return count_dict

bloods = ['o', 'a', 'a', 'b', 'ab', 'a', 'o', 'ab', 'a', 'b', 'b', 'b', 'ab', 'o', 'o']
print(total_people(bloods))  # 총 인원수 출력
print(type_of_blood(bloods))  # 혈액형의 종류 출력
print(getsu(bloods))  # 각 혈액형의 개수 출력

- 딕셔너리의 특정 키-값에 대해서, 문자열의 길이를 체크하는 로직 (len() 사용 불가)

#1
def dict_len(test_dict, key):
    val_len = 0
    key_len = 0

    for i in key:
        val_len += 1

    for i in test_dict[key]:
        key_len += 1

    return f'{val_len}, {key_len}'


test_dict = {'지안': '우와우아오아우', '채원': '아아아아채원이이이', '헌규': '화면', '윤하': '코딩천재다'}
print(dict_len(test_dict, '채원'))  # 2, 9
#2
def get_length_of_value(dict, key):
    if key not in dict:
        return "해당 키가 딕셔너리에 없습니다."

    length = 0
    for _ in dict[key]:
        length += 1
    return length

print(get_length_of_value({'A': 'apple', 'B': 'banana', 'C': 'candy', 'D': 'dinosaur', 'E': 'elephant'}, 'D'))

- 리스트에서 중복되어 있지 않은 요소를 반환 (하나만 반환 and 여러 개 반환 둘 다 연습해보기)

#1
def banhwan(my_list):
    unique_list = []
    for i in my_list:
        if my_list.count(i) == 1:
            unique_list.append(i)
    return unique_list 

test_list = [5,3,8,6,1,4,3,4,5,3,2,6,1,0]
print(banhwan(test_list))  # 출력 결과: [8, 2, 0]
#2
def banhwan(my_list):
    count_dict = {}
    for i in my_list:
        if i in count_dict:
            count_dict[i] += 1
        else:
            count_dict[i] = 1

    unique_list = []
    for key, value in count_dict.items():
        if value == 1:
            unique_list.append(key)

    return unique_list

test_list = [5,3,8,6,1,4,3,4,5,3,2,6,1,0]
print(banhwan(test_list))  # 출력 결과: [8, 2, 0]

- 비밀번호1 & 비밀번호2가 있을 때, 비밀번호 재확인 로직 (입력값에 대한 확인, return True or False)

def check_password(password1, password2):
    if password1 == password2:
        return True
    else:
        return False

print(check_password('123456', '123456')) #True
print(check_password('123456', '654321')) #False

- 문자열 내에 특정 문자가 있는지 여부를 확인하는 방법

def check_char(input_string, input_char):
    for s in input_string:
        if s == input_char:
            return True
    return False

print(check_char('Hello, world!', 'w'))
print(check_char('Hello, world!', 'z'))

- 진수 변환 (10진수 -> 2진수, 8진수, 16진수)

#1
def jinbup(num):
    binary = bin(num)[2:]
    octal = oct(num)[2:]
    hexadecimal = hex(num)[2:]
    return f'{binary}, {octal}, {hexadecimal}'

num = 23
print(jinbup(num))
#2
def byeonhwan(num):
    def decimal_to_base(num, base):
        jinsu = "0123456789ABCDEF"
        if num < base:
            return jinsu[num]
        else:
            return decimal_to_base(num//base, base) + jinsu[num%base]

    binary = decimal_to_base(num, 2)
    octal = decimal_to_base(num, 8)
    hexadecimal = decimal_to_base(num, 16)
    return f'{binary}, {octal}, {hexadecimal}'

print(byeonhwan(60))

- (심화) 2차원 배열의 범위를 벗어나는 그러한 x, y좌표인지 판단하기

#1
def check_arr(x, y, arr):
    row_num = len(arr)
    col_num = len(arr[0])

    if x >= row_num or x < 0:
        return False

    if y >= col_num or y < 0:
        return False

    else:
        return True

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(check_arr(1, 2, array))  # True
print(check_arr(3, 0, array))  # False
#2
def check_arr(x, y, list):
    try:
        list[x][y] in list
        result = True

    except IndexError:
        result = False

    return f'출력 결과: {result}'



array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(check_arr(1, 2, array))  # 출력 결과: True
print(check_arr(3, 0, array))  # 출력 결과: False

- (심화) 2차원 배열의 특정 값이 있는 x, y좌표를 반환

#1
def find_value(arr, value):
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            if arr[i][j] == value:
                return i, j
    return None

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(find_value(arr, 7))  # (2, 0)
#2
def find_value_in_array(array, value):
    row = 0
    while True:
        try:
            col = 0
            while True:
                try:
                    if array[row][col] == value:
                        return row, col
                except IndexError:
                    break
                col += 1
        except IndexError:
            break
        row += 1
    return None

# 예시로 3x3 배열과 '5' 값을 사용해봅시다.
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(find_value_in_array(array, 5))  # 출력 결과: (1, 1)
  • 반환하는 데이터 타입 주의하기!! ex) True(Boolean) & 'True'(str) / (3, 4) & [3, 4]
profile
멋쟁이 토마토 개발자 🍅

0개의 댓글