[3주차] 자료구조 문제풀이

이철민·2023년 2월 16일
0

[리스트 연습문제]

  • 1) 1부터 사용자가 입력한 숫자까지의 약수와 소수를 리스트에 각각 저장하고, 이것을 출력하는 프로그램을 만들어보자.
inputNum = int(input('1보다 큰 정수 입력: '))
listA = []   # 약수
listB = []   # 소수

for n in range(1, inputNum+1):
    if n == 1:
        listA.append(n)
    else:
        if inputNum % n == 0:
            listA.append(n)

for number in range(2,inputNum+1):
    flag = True
    for n in range(2,number):   # 자기보다 1 작은 수까지로 자신을 나눴을때 나누어떨어지는 수가 없으면 소수.
        if number % n == 0:     # number가 number 이하의 어떤 값 n으로 나누어진다면, 약수가 존재한다는 뜻.
            flag = False
            break

    if flag:
        listB.append(number)

print('약수: {}'.format(listA))
print('소수: {}'.format(listB))
  • 2) 1부터 100까지의 난수 10개를 생성한 후 짝수와 홀수를 구분해서 리스트에 저장하고 각각의 개수를 출력하는 프로그램을 만들어보자.
import random

randomList = random.sample(range(1,101),10)    # 샘플이 반환해주는 데이터는 무조건 리스트 타입!
oddList = []
evenList = []

for i in randomList:
    if i % 2 == 0:
        evenList.append(i)
    else:
        oddList.append(i)

print(f'짝수 리스트: {evenList}')
print(f'짝수 개수: {len(evenList)}')

print(f'홀수 리스트: {oddList}')
print(f'홀수 개수: {len(oddList)}')
  • 3) 사진 참조
import random

visitors = []

for n in range(100):
    visitors.append(random.randint(1, 100))

group1, group2, group3, group4, group5 = 0, 0, 0, 0, 0

for age in visitors:
    if age >=0 and age <= 7:
        group1 += 1
    elif age >= 8 and age <= 13:
        group2 += 1
    elif age >= 14 and age <= 19:
        group3 += 1
    elif age >= 20 and age <= 64:
        group4 += 1
    else:
        group5 += 1

group1Price = group1 * 0
group2Price = group2 * 200
group3Price = group3 * 300
group4Price = group4 * 500
group5Price = group5 * 0

print('-' * 25)
print(f'영유아: {group1}명, {group1Price}원')
print(f'어린이: {group2}명, {group2Price}원')
print(f'청소년: {group3}명, {group3Price}원')
print(f'성인: {group4}명, {group4Price}원')
print(f'어르신: {group5}명, {group5Price}원')
print('-' * 25)

sum = group1Price + group2Price + group3Price + group4Price + group5Price
sumFormat = format(sum, ',')
print(f'1일 총 요금: {sumFormat}원')
print('-' * 25)
  • 4-1) 친구 이름 다섯 명을 리스트에 저장하고 오름차순과 내림차순으로 정렬해보자.
friends = []

for i in range(5):
    friends.append(input('친구 이름 입력: '))

print(f'친구들: {friends}')

friends.sort()
print(f'오름차순: {friends}')

friends.sort(reverse=True)
print(f'내림차순: {friends}')
  • 4-2) 다음 리스트에서 중복 아이템(숫자)를 제거하는 프로그램을 만들어보자.
numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
print(f'numbers: {numbers}')

idx = 0
while True:

    if idx >= len(numbers):
        break  # while문을 빠져나와라

    if numbers.count(numbers[idx]) >= 2:
        numbers.remove(numbers[idx])
        continue

    idx += 1

print(f'numbers: {numbers}')
  • 5-1) 4개의 숫자 중 서로 다른 숫자 2개를 선택해서 만들 수 있는 모든 경우의 수를 출력하는 프로그램
numbers = [4, 6, 7, 9]
result = []

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue

        result.append([n1,n2])

print(f'result: {result}')
print(f'result length: {len(result)}')
# 순열의 공식: n! / (n-r)!

import math

permutation = math.factorial(len(numbers)) / math.factorial(len(numbers) - 2)
print(f'permutation: {int(permutation)}')
  • 5-2) 실습2: 4개의 숫자 중 서로 다른 숫자 3개를 선택해서 만들 수 있는 모든 경우의 수를 출력하는 프로그램
numbers = [4, 6, 7, 9]
result = []

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue

        for n3 in numbers:
            if n1 == n3 or n2 == n3:
                continue

            result.append([n1, n2, n3])

print(f'result: {result}')

[튜플 연습문제]

  • 1) 대학생 길동이의 1,2,3학년 성적은 다음과 같다. 졸업할 때 4.0이상의 학점을 받기 위해 길동이가 받아야 하는 4학년 1,2학기의 최소 학점은?
scores = ((3.7, 4.2), (2.9, 4.3), (4.1, 4.2))
total = 0

for s1 in scores:
    for s2 in s1:
        total += s2

total = round(total, 2)
avg = round((total / 6), 2)

print(f'3학년 총 학점: {total}')
print(f'3학년 평균: {avg}')

grade4TargetScore = round((4.0 * 8 - total), 1)
print(f'4학년 목표 총 학점: {grade4TargetScore}')

minScore = round((grade4TargetScore / 2), 1)
print(f'4학년 한 학기 최소 학점: {minScore}')

scores = list(scores)
scores.append((minScore, minScore))

scores = tuple(scores)
print(f'scores: {scores}')
  • 2) 다음 2개의 튜플에 대해서 합집합과 교집함을 출력해보자.
# for문

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

tempHap = list(tuple1)
tempGyo = []

for n in tuple2:
    if n not in tempHap:
        tempHap.append(n)
    else:
        tempGyo.append(n)

tempHap = tuple(sorted(tempHap))
tempGyo = tuple(sorted(tempGyo))

print(f'합집합(중복X)\t: {tempHap}')
print(f'교집합\t\t: {tempGyo}')
# while문

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

tempHap = tuple1 + tuple2
tempGyo = list()
tempHap = list(tempHap)

print(f'tempHap: {tempHap}')
print(f'tempGyo: {tempGyo}')

idx = 0
while True:
    if idx >= len(tempHap):
        break

    if tempHap.count(tempHap[idx]) >= 2:
        tempGyo.append(tempHap[idx])
        tempHap.remove(tempHap[idx])
        continue

    idx += 1

print(f'tempHap: {tuple(sorted(tempHap))}')
print(f'tempGyo: {tuple(sorted(tempGyo))}')
  • 3-1) 다음 튜플을 요구 사항에 맞춰 아이템을 슬라이스하자.
numbers = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3)

# index 0부터 3까지
print(f'numbers[0:4]: {numbers[0:4]}')

# index 2부터 뒤에서 -2까지
print(f'numbers[2:-1]: {numbers[2:-1]}')

# index 0부터 끝까지 3단계
print(f'numbers[::3]: {numbers[::3]}')

# 최댓값과 최소값 구하기 -> min(), max() 함수 이용! -> 이 값들의 index가 궁금하면 index() 함수 이용!
print(f'최솟값: {min(numbers)}')
print(f'최솟값: {numbers.index(min(numbers))}')

print(f'최댓값: {max(numbers)}')
print(f'최댓값: {numbers.index(max(numbers))}')
  • 3-2) 시험 점수를 입력한 후 튜플에 저장하고 과목별 학점을 출력해보자.
korScore = int(input('국어 점수 입력: '))
engScore = int(input('영어 점수 입력: '))
mathScore = int(input('수학 점수 입력: '))
sciScore = int(input('과학 점수 입력: '))
hisScore = int(input('국사 점수 입력: '))

# 튜플 안에 딕셔너리를 넣었기 때문에, 딕셔너리 안에 있는 값들을 수정할 수 있는 것!
scores = ({'kor':korScore}, {'eng':engScore}, {'math':mathScore}, {'sci':sciScore}, {'his':hisScore})

print(scores)

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

print(scores)
  • 4) 다음 튜플의 과일 개수에 대해서 오름차순 및 내림차순으로 정렬해보자.
fruits = ({'수학': 8}, {'포도':13}, {'참외':12}, {'사과':17}, {'자두':19}, {'자몽':15})
fruits = list(fruits)

cIdx = 0; nIdx = 1          # 처음 비교를 시작하는 것이 인덱스 0과 1이기 때문.
eIdx = len(fruits) - 1

flag = True
while flag:
    curDic = fruits[cIdx]
    nextDic = fruits[nIdx]

    curDicCnt = list(curDic.values())[0]
    nextDicCnt = list(nextDic.values())[0]

    if nextDicCnt < curDicCnt:     # 내림차순은 여기서 if nextDicCnt > curDicCnt 만 하면 됨.
        fruits.insert(cIdx, fruits.pop(nIdx))
        nIdx = cIdx + 1
        continue

    nIdx += 1
    if nIdx > eIdx:
        cIdx += 1
        nIdx = cIdx + 1

        if cIdx == 5:
            flag = False

print(tuple(fruits))
  • 5) 학급별 학생 수를 나타낸 튜플을 이용해서, 요구 사항에 맞는 데이터를 출력해보자.
studentCnt = ({'cls01':18}, {'cls02':21}, {'cls03':20}, {'cls04':19},
              {'cls05':22}, {'cls06':20}, {'cls07':23}, {'cls08':17})

totalCnt = 0
minStdCnt = 0; minCls = ''
maxStdCnt = 0; maxCls = ''
deviation = []

for idx, dic in enumerate(studentCnt):
    for k, v in dic.items():
        totalCnt += v

    if minStdCnt == 0 or  minStdCnt > v:
        minStdCnt = v
        minCls = k

    if maxStdCnt < v:
        maxStdCnt = v
        maxCls = k

print(f'전체 학생 수: {totalCnt}명')

avgCnt = totalCnt / len(studentCnt)
print(f'평균 학생 수: {avgCnt}명')

print(f'학생 수가 가장 적은 학급: {minCls}({minStdCnt})')
print(f'학생 수가 가장 많은 학급: {maxCls}({maxStdCnt})')

for idx, dic in enumerate(studentCnt):
    for k, v in dic.items():
        deviation.append(v - avgCnt)

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

[딕셔너리 연습문제]

  • 1-1) 과목별 점수를 딕셔너리에 저장하고 출력하는 프로그램을 만들자.
subject = ['국어', '영어', '수학', '과학', '국사']
scores = {}

for s in subject:
    score = int(input(s + ' 점수 입력: '))
    scores[s] = score

print(f'과목별 점수: {scores}')
  • 1-2) 사용자의 아이디, 비밀번호를 이용해서 로그인 프로그램을 만들어보자.
members= {'qwer':'12345', 'asdf': '67890', 'zxcv':'54321'}

memID = input('아이디 입력: ')
memPW = input('비밀번호 입력: ')

if memID in members:
    if members[memID] == memPW:
        print('로그인 성공!!')
    else:
        print('비밀번호 확인!!')

else:
    print('아이디 확인!!')
  • 2-1) 삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램을 만들어보자.
    • n각형의 내각의 합: 180 * (n-2)
dic = {}
for n in range(3,11):
    hap = 180 * (n-2)
    angle = int(hap/n)
    dic[n] = [hap,angle]

print(dic)
  • 2-2) 1부터 10까지 각각의 정수에 대한 약수를 저장하는 딕셔너리를 만들고 출력해보자.
dic = {}
for n1 in range(2, 11):
    tempList = []
    for n2 in range(1, n1 + 1):
        if n1 % n2 == 0:
            tempList.append(n2)

    dic[n1] = tempList

print(dic)
  • 3-1) 다음 문구를 공백으로 구분하여 리스트에 저장한 후, 인덱스와 단어를 이용해서 딕셔너리에 저장해보자.
aboutPython = '파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어이다.'

splitList = aboutPython.split()     # split(): 공백을 기준으로 데이터를 분리해 리스트 타입으로 반환

dic = {}
for idx, value in enumerate(splitList):
    dic[idx] = value

print(dic)
  • 3-2) 다음 문장에서 비속어를 찾고 비속어를 표준어로 변경하는 프로그램을 만들어보자.
words = {'쪼개다':'웃다', '짭새':'경찰관', '먹튀':'먹고 도망'}

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

keys = list(words.keys())

for key in keys:
    if key in text:
        print('key: {}'.format(key))
        print('words[{}]: {}'.format(key, words[key]))
        text = text.replace(key, words[key])       # text.replace(n1, n2) : text 리스트의 n1 값을 n2로 바꾸겠다.

print(text)
  • 4-1) 딕셔너리를 이용해서 5명의 회원을 가입 받고 전체 회원 정보를 출력하는 프로그램을 만들어보자.
members = {}

n = 1
while n < 6:
    mail = input('메일 입력: ')
    pw = input('비번 입력: ')

    if mail in members:
        print('이미 사용중인 메일 계정 입니다.')
        continue

    else:
        members[mail] = pw
        n += 1

for key in members.keys():
    print(f'{key} : {members[key]}')
  • 4-2) 위의 프로그램을 이용해서 특정 회원 계정을 삭제하는 프로그램을 만들어보자.
members = {}
n = 1
while n < 6:
    mail = input('메일 입력: ')
    pw = input('비번 입력: ')

    if mail in members:
        print('이미 사용중인 메일 계정 입니다.')
        continue

    else:
        members[mail] = pw
        n += 1

for key in members.keys():
    print(f'{key} : {members[key]}')

while True:
    delMail = input('삭제할 계정(메일) 입력: ')

    if delMail in members:
        delPw = input('비번 입력: ')
        if members[delMail] == delPw
            del members[delMail]
            print(f'{delMail} 계정 삭제 완료')
            break
        else:  # 메일은 일치하나, 비번이 일치하지 않을 경우
            print('비번 확인 요망!')

    else:  # 메일부터 일치하지 않을 경우
        print('계정 확인 요망!!')

for key in members.keys():
    print(f'{key} : {members[key]}')
  • 5)
students = {'s21-0001':{'이름':'최성훈',
                        '성구분':'M',
                        '전공':'디자인',
                        '연락처':'010-1234-5678',
                        '메일':'hun@gamil.com',
                        '취미':['농구', '음악']},
            's21-0002':{'이름':'탁영우',
                        '성구분':'M',
                        '전공':'바리스타',
                        '연락처':'010-5678-9012',
                        '메일':'yeong@gamil.com',
                        '취미':['축구']},
            's21-0003': {'이름': '황진영',
                        '성구분': 'W',
                        '전공': '음악',
                        '연락처': '010-9012-3456',
                        '메일': 'jin@gamil.com',
                        '취미': ['수영','코딩']}}


for k1 in students.keys():
    print('-' * 40)
    print('학생번호: {}'.format(k1))

    student = students[k1]
    for k2 in student.keys():
        print('{}: {}'.format(k2, student[k2]))

studentNo = input('조회 대상 학생 번호 입력: ')
print('{}: {}'.format(studentNo, students[studentNo]))
profile
늘 온 마음을 다해 :)

0개의 댓글