230925_스터디노트

Sihyun Kim·2023년 9월 26일

자료구조 문제풀이

39_[연습문제] 리스트(01)

  • 약수와 소수 구해서 리스트에 넣기
userNum = int(input('1보다 큰 정수 입력: '))

divisorList = []
primeList = []

for d in range(1, userNum+1):
    if userNum % d == 0:
        divisorList.append(d)

for p in range(2, userNum+1):
    flag = True
    for i in range(2, p):
        if p % i == 0:
            flag = False

    if flag == True:
        primeList.append(p)

print(f'약수: {divisorList}')
print(f'소수: {primeList}')

40_[연습문제] 리스트(02)

  • 1부터 100 사이에 난수 10개를 생성한 후 짝수와 홀수를 구분해서 리스트에 저장, 개수 출력
import random

randList = random.sample(range(1, 101), 10)

evenList = []
oddList = []

for num in randList:
    if num % 2 == 0:
        evenList.append(num)
    else:
        oddList.append(num)

print(randList)
print(f'짝수: {evenList}, ({len(evenList)}개)')
print(f'홀수: {oddList}, ({len(oddList)}개)')

41_[연습문제] 리스트(03)

  • 방문객 100명의 연령대를 난수로 구하고, 각 그룹의 입장료를 적용해서 요금 총합계 구하기
import random

visitorList = []

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

babyFare = 0; kidFare = 200; YouthFare = 300
AdultFare = 500; ElderFare = 0

babyList = []; kidList = []; youthList = []; adultList = []; elderList = []

for n in visitorList:
    if n <= 7:
        babyList.append(n)
    elif 8 <= n <= 13:
        kidList.append(n)
    elif 14 <= n <= 19:
        youthList.append(n)
    elif 20 <= n <= 64:
        adultList.append(n)
    elif n >= 65:
        elderList.append(n)

babyTotal = len(babyList) * babyFare
kidTotal = len(kidList) * kidFare
youthTotal = len(youthList) * YouthFare
adultTotal = len(adultList) * AdultFare
elderTotal = len(elderList) * ElderFare
dailyTotal = babyTotal + kidTotal + youthTotal + adultTotal + elderTotal
dailyTotal = format(dailyTotal, ',')

print('-' * 25)
print(f'영유아\t:{len(babyList)}명\t:{babyTotal}원')
print(f'어린이\t:{len(kidList)}명\t:{kidTotal}원')
print(f'청소년\t:{len(youthList)}명\t:{youthTotal}원')
print(f'성인\t\t:{len(adultList)}명\t:{adultTotal}원')
print(f'어르신\t:{len(elderList)}명\t:{elderTotal}원')

print('-' * 25)

print(f'1일 요금 총합계: {dailyTotal}원')

print('-' * 25)

42_[연습문제] 리스트(04)

  • 기존 리스트에서 중복 아이템을 제거하기

  • 내 풀이 (for문 사용해서 새로운 리스트에 저장)

numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
newNumbers = []

for num in numbers:
    if num not in newNumbers:
        newNumbers.append(num)
    else:
        pass

print(newNumbers)
  • 영상 풀이 (while문 이용해서 remove)
numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]

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

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

    idx += 1

print(numbers)

43_[연습문제] 리스트(05)

numList = [2, 4, 7, 9]
result = []

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

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

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

print(result)
print(len(result))

44_[연습문제] 튜플(01)

  • 평균 학점 4.0이 되려면 마지막 학년에는 몇 학점을 받아야 하는가
scores = (3.7, 4.2), (2.9, 4.3), (4.1, 4.2)

totalScore = 0; avg = 0; n = 0
graduateScore = 0; wantedScore = 0

for n1, n2 in scores:
    totalScore += n1 + n2
    n += 2

avg = totalScore / n

print(f'3학년 총학점: {totalScore}')
print(f'3학년 평균: {avg}')
print('-' * 50)

graduateScore = (4.0 * 8) - totalScore
print(f'4학년 목표 학점: {round(graduateScore, 2)}')
wantedScore = graduateScore / 2

print(f' 4학년 한학기 목표 학점: {round(wantedScore, 2)}')

45_[연습문제] 튜플(02)

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

hapList = list(tuple1)
gyoList = []

for n2 in tuple2:
    if n2 not in hapList:
        hapList.append(n2)

hapList.sort()
hapList = tuple(hapList)

print(f'합집합: {hapList}')

for num in tuple1:
    if num in tuple2:
        gyoList.append(num)

gyoList.sort()
gyoList = tuple(gyoList)

print(f'교집합: {gyoList}')

46_[연습문제] 튜플(03)

  • 인덱스 위치 찾기, 최대/최소값과 그 인덱스 찾기
nums = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3)

print(nums[:4])
print(nums[2:5])
print(nums[3:])
print(nums[2:-1])
print(nums[0::3])

print(max(nums))
print(nums.index(max(nums)))

print(min(nums))
print(nums.index(min(nums)))
  • 점수를 입력하면 학점을 출력해보자
scoreKor = int(input('국어 점수 입력: '))
scoreEng = int(input('영어 점수 입력: '))
scoreMat = int(input('수학 점수 입력: '))
scoreSci = int(input('과학 점수 입력: '))
scoreHis = int(input('역사 점수 입력: '))

scoreList = ({'kor': scoreKor}, {'eng': scoreEng}, {'mat': scoreMat}, {'sci': scoreSci}, {'his': scoreHis})

print(scoreList)

for item in scoreList:
    for key in item.keys():

        if item[key] >= 90:
            item[key] = 'A'
        elif 80 <= item[key] < 90:
            item[key] = 'B'
        elif 70 <= item[key] < 80:
            item[key] = 'C'
        elif 60 <= item[key] < 70:
            item[key] = 'D'
        elif item[key] < 60:
            item[key] = 'F'

print(scoreList)

😅

  • 튜플 안에 딕셔너리를 넣어야 수정이 된다
    딕셔너리 for문으로 불러와서 쓰는 방법 아직 어색함 주의

47_[연습문제] 튜플(04)

48_[연습문제] 튜플(05)

  • 학급별 학생 수를 나타낸 튜플을 이용해서 아래 요구 사항을 출력
    • 전체 학생, 평균 학생수, 학생수 max/min, 편차
stdCnt = ({'cls01': 18}, {'cls02': 21}, {'cls03': 20}, {'cls03': 19}, {'cls05': 22}, {'cls06': 20}, {'cls07': 23}, {'cls08': 17})

total = 0
avg = 0
minClass = 0; minCnt = 0
maxClass = 0; maxCnt = 0

for item in stdCnt:
    for key in item.keys():
        total += item[key]

        if item[key] > maxCnt:
            maxClass = key
            maxCnt = item[key]

        if minClass == 0 or item[key] < minCnt:
            minClass = key
            minCnt = item[key]

avg = total / (len(stdCnt))

print(f'전체 학생 수: {total}명')
print(f'평균 학생 수: {avg}명')
print(f'학생 수가 가장 적은 학급: {minClass}({minCnt})명')
print(f'학생 수가 가장 많은 학급: {maxClass}({maxCnt})명')

newList = stdCnt
for item in newList:
    for key in item.keys():
        item[key] = item[key] - avg

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

😐

  • 강의 풀이에서는 enumerate 함수 사용
for idx, dic in enumerate(stdCnt):
    for key, value in dic.items():
profile
문과이과예체능통합형인재

0개의 댓글