자료구조 문제풀이

YJ·2023년 3월 21일

▷ 오늘 학습 내용: 자료구조 강의(문풀 1~3)

01_리스트

    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
        elif age >=65: group5 +=1

    g1Price = group1 * 0
    g2Price = group2 * 200
    g3Price = group3 * 300
    g4Price = group4 * 500
    g5Price = group5 * 0

    totalPrice = format((g1Price + g2Price + g3Price + g4Price + g5Price),',')

    print('영유아\t : {}명\t : {}원'.format(group1,group1Price))
    print('어린이\t : {}명\t : {}원'.format(group2,group2Price))
    print('청소년\t : {}명\t : {}원'.format(group3,group3Price))
    print('성인\t\t : {}명\t : {}원'.format(group4,group4Price))
    print('어르신\t : {}명\t : {}원'.format(group5,group5Price))
    print('-'*30)
    print('1일 요금 총합계: {}원'.format(totalPrice))

리스트에서 중복 아이템(숫자)을 제거하는 프로그램 만들기

    numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
    print('numbers {}'.format(numbers))

    idx = 0
    while True:

        if idx >= len(numbers):
           break

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

        idx += 1

    print('numbers {}'.format(numbers))

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('result: {}'.format(result))
    print('result: {}개'.format(len(result)))

02_튜플

    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,1)
    avg = round((total / 6),1)
    print('3학년 총학점: {}'.format(total))
    print('3학년 평균: {}'.format(avg))

    TargetScore = round((4.0 * 8 -total),1)
    minScore = round(TargetScore/2,1)
    print('4학년 목표 총학점: {}'.format(TargetScore))
    print('4학년 한학기 최소학점: {}'.format(minScore))

    scores = list(scores)
    scores.append((minScore, minScore))
    scores = tuple(scores)
    print('scores: {}'.format(scores))

튜플 합집합과 교집합 출력하기

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

    #result1 = 합집합, result2 = 교집합
    result1 = list(tuple1)
    result2 = list()

    for n in tuple2:
        if n not in result1:
            result1.append(n)
        else:
            result2.append(n)

    result1 = tuple(sorted(result1))
    result2 = tuple(sorted(result2))

    print('합집합(중복X): {}'.format(result1))
    print('교집합: {}'.format(result2))
  # while문
    tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
    tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
    
    #result1 = 합집합, result2 = 교집합
    result1 = tuple1 + tuple2  #tuple형태
    result1 = list(result1)  #list로 변경
    result2 = list()

    idx = 0
    while True:
        if idx >= len(result1):
            break
        if result1.count(result1[idx]) >= 2:
            result2.append(result1[idx])
            result1.remove(result1[idx])
            continue
        idx += 1

    print('result1: {}'.format(tuple(sorted(result1))))
    print('result2: {}'.format(tuple(sorted(result2))))

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

    fruits = list(fruits)

    cIdx = 0; nIdx = 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:  #내림차순: '>'로 변경
            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))

학급별 학생수를 나타낸 튜플을 이용해서 데이터 출력하기

    studentCnt = ({'cls01':18},{'cls02':21},{'cls03':20},{'cls04':19},
                  {'cls05':22},{'cls06':20},{'cls07':23},{'cls08':17})

    totalCnt = 0
    minCnt = 0; minCls = ''
    maxCnt = 0; maxCls = ''

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

            if maxCnt < v:
                maxCnt = v
                maxCls = k

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

    avgCnt = totalCnt / len(studentCnt)    

    for idx,dic in enumerate(studentCnt):
        for k,v in dic.items():
            dic[k] = v-avgCnt

    print('전체 학생 수 : {}명'.format(totalCnt))
    print('평균 학생 수 : {}명'.format(avgCnt))
    print('학생 수가 가장 적은 학급: {}({}명)'.format(minCls, minCnt))
    print('학생 수가 가장 많은 학급: {}({}명)'.format(maxCls, maxCnt))
    print('학급별 학생 편차: {}'.format(studentCnt))

03_딕셔너리

삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하고 출력

  dic = {}

  for n in range(3,11):
      sum = 180 * (n-2)
      ang = int(sum/n)
      dic[n] = [sum,ang]
      
  print(dic)

1부터 10까지 각각의 정수에 대한 약수를 저장하는 딕셔너리 출력

  dic = {}

  for n1 in range(1, 11):
      list = []
      
      for n2 in range(1, n1+1):
          if n1 % n2 == 0:
              list.append(n2)

      dic[n1] = list
      
  print(dic)

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


  weather = '오늘은 날씨가 너무 좋아요.
  splitList = weather.split()
  
  print(splitList)
  # ['오늘은', '날씨가', '너무', '좋아요.']

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

  print(dic)
  # {0: '오늘은', 1: '날씨가', 2: '너무', 3: '좋아요.'}
  • txt.replace(a,b) → txt의 a를 b로 바꾸기

▷ 내일 학습 계획: 알고리즘 강의(1~7)

[이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.]

0개의 댓글