15. 자료구조_문풀1

wonny_·2023년 7월 23일
0

자료구조&알고리즘

목록 보기
4/10
  • 리스트 1
Q. 중복 아이템 제거

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

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

    idx += 1

print(f'numbers: {numbers}')   

  • 리스트 2
Q. 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)}')
___________________________________________________________________

<경우의 >

import math
pernutation = math.factorial(len(numbers)) / math.factorial(len(numbers) -2)
print(f'pernutation : {int(pernutation)}')
print()

  • 튜플 1
  Q. 대학생 길동이의 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, 1)
  avg = round(total/ 6, 1)

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

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

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

  scores = tuple(scores)
  print(f'scores: {scores}')

  • 튜플 2
Q. 두 개의 튜플에 대해 합집합과 교집합 출력

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)

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
     
tempHap = tuple(sorted(tempHap))
tempGyo = tuple(sorted(tempGyo))

print(f'합집합(중복x) : {tempHap}')
print(f'교집합: {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)

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

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

print(f'합집합  : {tempHap}')
print(f'교집합: {tempGyo}')

  • 튜플 3
Q. 튜플 요구 사항에 맞춰 아이템 슬라이스 

numbers = (8.7, 9.0, 9.1, 8.6, 9.3, 7.9, 8.1, 8.3)

print(f'Index 0부터 3까지: {numbers[:4]}')
print(f'Index 2부터 4까지: {numbers[2:5]}')
print(f'Index 3부터 끝까지: {numbers[3:]}')
print(f'Index 2부터 뒤에서 -2까지: {numbers[2:-1]}')
print(f'Index 0부터 끝까지 3단계: {numbers[::3]}')


print(f'최소값: {min(numbers)}')
print(f'최대값: {max(numbers)}')

print(f'최소값 인덱스: {numbers.index(min(numbers))}')
print(f'최대값 인덱스: {numbers.index(max(numbers))}')

Q. 시험점수를 입력 후 튜플에 저장하고 과목별 학점 출력

korScore = int(input('국어점수 입력: '))
engScore = int(input('영어점수 입력: '))
matScore = int(input('수학점수 입력: '))
sciScore = int(input('과학점수 입력: '))
hisScore = int(input('국사점수 입력: '))

scores = ({'kor': korScore},
      {'eng': engScore},
      {'mat': matScore},
      {'sci': sciScore},
      {'his': hisScore})

print(f'scores: {scores}')
scores = list(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'   
           
           
scores = tuple(scores)
print(f'scroes: {scores}')          

  • 튜플 4
Q. 튜플 과일 개수에 대해 오름차순 및 내림차순 정렬

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

 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]
     extDicCnt = 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
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
fruits = tuple(fruits)
print(fruits)

  • 튜플 5
Q. 학급별 학생 수를 튜플 이용해서 요구 사항에 맞는 데이터 출력 

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 = 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}')

profile
파이팅

1개의 댓글

comment-user-thumbnail
2023년 7월 23일

감사합니다. 이런 정보를 나눠주셔서 좋아요.

답글 달기