[Zerobase][Python Mid] Tuple&Dictionary 문제풀이

솔비·2023년 12월 6일

💻 Python. w/zerobase

목록 보기
19/33
post-thumbnail

⬇️ Tuple & Dictionary 이론
https://velog.io/@sxlbl/Zerobase자료구조-Tuple과-Dictionary


자료구조 [Tuple]


📖 1번문제

졸업할 때 4.0이상의 받기위해 받아야하는 1,2학기 최소학점

scores = (3.7,4.2),(2.9,4.3),(4.1,4.2)

total_avg = 4.0
total_sum = 32.0

now_sum = 0
now_avg = 0

for idx, score in enumerate(scores) :
    now_sum += sum(score)
    now_avg = round( now_sum / ( ( idx +1 ) * 2 ) ,2)

    print(f'{idx +1}학년 총 학점 : {now_sum}')
    print(f'{idx +1}학년 평균 학점 : {now_avg}')
    print('-'*50)

    if idx + 1 == 3 :
        goal = round(total_sum - now_sum,2)

        print(f'{idx + 2}학년 목표 총 학점 : {goal}')
        print(f'{idx + 2}학년 한학기 최소학점 : {goal/2}')
        print('-' * 50)

        scores = list(scores)
        scores.append((goal/2,goal/2))
        scores = tuple(scores)
        print(f'scores : {scores}')

📁 풀이기록

각 학년별 총 학점과 평균학점을 출력한 후
if 조건을 걸어 3학년까지의 합이 되었을 때
달성해야할 goal을 출력했다.

해당 목표 점수를 추가할 때,
tuple형태이기 때문에 list로 형변환해서 추가한 후
다시 tuple로 형변환해서 출력하였다.


📖 2번문제

합집합과 교집합을 출력해보자

tuple1 = (1,3,2,6,12,5,7,8)
tuple2 = (0,5,2,9,8,6,17,3)


combination = list(tuple2)
intersection = []

for i in tuple1 :
    if i not in combination :
        combination.append(i)

    if i in tuple2 :
        intersection.append(i)

combination.sort()
intersection.sort()

combination = tuple(combination)
intersection = tuple(intersection)

print(f'합집합(중복X) : {combination}')
print(f'교집합 : {intersection}')

📁 풀이기록

while문으로도 풀어보면,

tuple1 = (1,3,2,6,12,5,7,8)
tuple2 = (0,5,2,9,8,6,17,3)


combination = list(tuple1 + tuple2)
intersection = []

idx = 0
while True :

    if idx >= len(combination) :
        break

    if combination.count(combination[idx]) >= 2 :
        intersection.append(combination[idx])
        combination.remove(combination[idx])
        continue

    idx += 1

combination = tuple(sorted(combination))
intersection = tuple(sorted(intersection))

print(f'합집합 : {combination}')
print(f'교집합 : {intersection}')

튜플의 덧셈연산을 이용했다.
(변경은 안되지면 더한값을 다른 변수에 담아주는 방식)
A + B = C

처음에
intersection.append(combination[idx])
combination.remove(combination[idx])
두가지 위치를 바꿔서 코딩해서 교집합 값이 잘못 나왔는데,
idx를 삭제한뒤 그 idx 값을 append하면
바뀐 아이템값이 들어가기 때문에 결과가 잘못나온것.
idx를 활용한 문제풀이 때 주의해야겠다.


📖 3번문제

시험 점수를 입력한 후 튜플에 저장하고 과목별 학점을 출력해보자

kor = int(input('국어점수입력 : '))
eng = int(input('영어점수입력 : '))
mat = int(input('수학점수입력 : '))
sci = int(input('과학점수입력 : '))
his = int(input('역사점수입력 : '))


scores = (
    {'kor': kor},{'eng': eng},{'mat': mat},{'sci': sci},{'his': his}
)

print(f'scores : {scores}')


for dic in scores :
    for key in dic.keys() :
        if dic[key] >= 90 :
            dic[key] = 'A'
        elif dic[key] >= 80 :
            dic[key] = 'B'
        elif dic[key] >= 70 :
            dic[key] = 'C'
        elif dic[key] >= 60 :
            dic[key] = 'D'
        else :
            dic[key] = 'F'


print(f'scores : {scores}')

📁 풀이기록

for문으로 튜플 내 딕셔너리를 뽑은 후
dic.keys()를 활용해 key값과 value값을 추출하고
value를 조건에 따라 변경하였다.

❗튜플은 수정이 안되지만
튜플안의 딕셔너리는 수정이 가능하다


📖 4번문제 🌟

다음 튜플의 과일 개수에 대해서 오름차순 및 내림차순으로 정렬해보자

fruits = (
    {'수박':8},{'포도':13},{'참외':12},{'사과':17},{'자두':19},{'자몽':15})

fruits = list(fruits)


idx = 0 ; n_idx = 1
e_idx = len(fruits)-1

while True :

    c_dic = fruits[idx]
    n_dic = fruits[n_idx]

    c_dic_cnt = list(c_dic.values())[0]
    n_dic_cnt = list(n_dic.values())[0]

    if c_dic_cnt > n_dic_cnt :
        fruits.insert(idx,fruits.pop(n_idx))
        n_idx = idx + 1
        continue

    n_idx += 1

    if n_idx > e_idx :
        idx += 1
        n_idx = idx +1

        if idx == e_idx -1 :
            break



print(fruits)

📁 풀이기록 🌟

꽤나 어려웠던 문제 ㅜㅜ
튜플을 리스트로 변환해준 뒤,
인덱스를 활용해 리스트 내 딕셔너리를 뽑을 수 있다.
딕셔너리의 value를 리스트에 담고 [0]으로 과일 개수를 뽑는다.

현재 인덱스와 다음인데스 내 딕셔너리 value를 비교해주면서
자리를 바꾸는 방식

❗fruits.pop(n_idx)에서
fruits.pop(n_idx)는 fruits[n_idx] 값을 담고있다.
그래서 fruits.insert(idx,fruits.pop(n_idx))처럼 동시에 삭제 추가가 가능 !


📖 5번문제

학급별 학생수를 나타낸 튜플을 이용해서 요구사항에 맞는 데이터를 출력하는 프로그램

요구사항

  • 전체 학생수
  • 평균학생수
  • 학생수가 가장 적은 학급
  • 학생수가 가장 많은 학급
  • 학급별 학생 편차
students = (
    {'cls01':18},{'cls02':21},{'cls03':20},{'cls04':19}
    ,{'cls05':22},{'cls06':20},{'cls07':23},{'cls08':17}
)

students = list(students)

sum_student = 0
max_class = ''
max_student = 0
min_class = ''
min_student = 0



for idx, dic in enumerate(students) :
    for key, value in dic.items() :
        sum_student += value


        if max_student < value :
            max_student = value
            max_class = key

        if min_student == 0 or min_student > value:
            min_student = value
            min_class = key

avg_student = sum_student / len(students)

print(f'전체 학생 수 : {sum_student}')
print(f'평균 학생 수 : {avg_student}')
print(f'학생 수가 가장 적은 학급 : {min_class}({min_student})')
print(f'학생 수가 가장 많은 학급 : {max_class}({max_student})')

for dic in students :
    for key,value in dic.items() :
        dic[key] = value - avg_student

print(f'학급별 학생 편차 : {students})')

📁 풀이기록

딕셔너리 .keys() / .items() / .values() 정리

  1. 그 자체로 print하면 key와 value값 자체로 사용할 수 없다.
print({'cls01':18}.keys())			#dict_keys(['cls01'])
print({'cls01':18}.values())		#dict_values([18])
print({'cls01':18}.items())			#dict_items([('cls01', 18)])
  1. 값 그대로 사용하려면 for문을 활용해야한다.
for i in {'cls01':18}.keys() :
    print(i)			#cls01
for i in {'cls01':18}.values() :
    print(i)			#18
for i in {'cls01':18}.items() :
    print(i)			#('cls01', 18)
    print(i[0])			#cls01 #type : str
    print(i[1])			#18		#type : int
  1. 딕셔너리의 enumerate나 for문은 key값을 반환한다.
for i in {'cls01':18} :
    print(i)			#cls01

for i in enumerate({'cls01':18}) :
    print(i)			#(0, 'cls01') #idx번호와 key값

자료구조 [Dictionary]


📖 1번문제

사용자의 아이디, 비밀번호를 이용해서 로그인 프로그램을 만들어보자


members = {
    'abcd': '1234',
    'aaaa': '1111',
    'bbbb': '2222',
    'cccc': '3333',
    'dddd': '4444',
    'eeee': '5555',
}

id = input('아이디 입력 : ')
fw = input('비밀번호 입력 : ')


if id not in members :
    print('아이디 확인하셈')
else :
    if members[id] != fw :
        print('비번확인하셈')
    else :
        print('로그인성공')

📁 풀이기록

in과 not in은 리스트, 튜플에서는 아이템값이 존재하는지
딕셔너리에서는 key값이 존재하는지를 알 수 있다.
id는 members에 key값으로 존재하므로
조건문을 통해 원하는 내용을 출력 할 수 있다.


📖 2번문제

삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램을 만들어보자

#n각형 내각의 합 ㅣ 180 * (n-2)
#n각형 내각 | 내각의합/n

dic = {}

for n in range(3,11) :
    n_sum = 180 * (n-2)
    n_ang = int(n_sum / n)

    dic[n] = [n_sum,n_ang]

print(dic)

📁 풀이기록

내각의 합과 내각에 대한 지식만 있으면 쉽게 풀 수 있는 문제였다.


📖 3번문제

1번

다음 문구를 공백으로 구분하여 리스트에 저장한 후 인덱스와 단어를 이용해서 딕셔너리에 저장


about_pyton = '파이썬은 1991년 프로그래머인 귀도 반 로썸이 발표한 고급 프로그래밍 언어이다.'

dic = {}
split_list = about_pyton.split()

for idx, str in enumerate(split_list) :
    dic[idx] = str

print(dic)

2번

다음 문장에서 비속어를 찾고 비속어를 표준어로 변경하는 프로그램을 만들어보자
#'강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.'

word = {
    '쪼개다' : '웃다',
    '짭새' : '경찰관',
    '먹튀' : '먹고 도망',
}

txt = '강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.'

keys = list(word.keys())

for key in keys :
    if key in txt :
        txt = txt.replace(key,word[key])

print(txt)

📁 풀이기록

1번

split 메소드를 사용해서 문자열을 잘라 리스트 형태로 반환했다.

2번

replace 메소드를 사용해서 words 딕셔너리의 value값으로 변경해주었다.

자주쓰는 메소드 관련 정리 내용


📖 4번문제

5개의 이메일과 아이디를 받아서 딕셔너리에 저장하고
특정 회원계정을 삭제하는 프로그램

#저장

mail = {}

n = 1
while n < 6 :

    id = input('계정 입력 : ')

    if id not in mail :
        pw = input('비번 입력 : ')
        mail[id] = pw
        n += 1
        
    else :
        print('이미 있는 계정입니다.')

#삭제
for key in mail.keys() :
    print(f'{key} : {mail[key]}')

while True :
    delete = input('삭제할 계정 입력 : ')

    if delete not in mail :
        print('계정확인요망')
    else :
        pw = int(input('비번입력 입력 : '))

        if mail[delete] == pw :
            print(f'{delete}님 삭제완료!')
            print(f'{delete} :{pw}')
            del mail[delete]
            break


        else :
            print('비번 확인요망')

Zero Base 데이터분석 스쿨
Daily Study Note
profile
Study Log

0개의 댓글