스터디노트(자료구조 문제풀이 1~3)

zoe·2023년 3월 21일
0

💡 [연습문제] 리스트 01

💡 1부터 사용자가 입력한 숫자까지의 약수와 소수를 리스트에 각각 저장하고, 이것을 출력하는 프로그램을 생성

# 1부터 사용자가 입력한 숫자까지의 약수와 소수를 리스트에 각각 저장하고,
# 이것을 출력하는 프로그램을 생성

inputNum = int(input('1보다 큰 정수 입력 : '))

listA = []
listB = []

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

for number in range(2, inputNum+1):
    flag = True
    for n in range(2, number):
        if number % n == 0:
            flag = False
            break # ★★★
    if flag:
        listB.append(number)
print(listB)

[연습문제] 리스트 02

1부터 100사이에 난수 10개를 생성한 후 짝수와 홀수를 구분해서 리스트에 저장하고 각각의 개수를 출력하는 프로그램을 생성

# 1부터 100사이에 난수 10개를 생성한 후 짝수와 홀수를 구분해서 리스트에
# 저장하고 각각의 개수를 출력하는 프로그램을 생성

import random

randomList = random.sample(range(1, 101), 10) # ★
evens = []
odds = []

for n in randomList:
    if n % 2 == 0:
        evens.append(n)
    else:
        odds.append(n)

print(f'짝수 : {evens}, 개수 : {len(evens)}')
print(f'홀수 : {odds}, 개수 : {len(odds)}')

💡 [연습문제] 리스트 03

💡 다음은 공원 입장료를 나타낸 표이다. 1일 총 입장객이 100명이라고 할 때, 1일 전체 입장 요금을 구하는 프로그램을 생성. 단, 입장 고객의 나이는 난수를 이용

# 다음은 공원 입장료를 나타낸 표이다. 1일 총 입장객이 100명이라고 할 때,
# 1일 전체 입장 요금을 구하는 프로그램을 생성
# 단, 입장 고객의 나이는 난수를 이용

# import random
# 
# visitors = []
# rNum = 100
# for i in range(5):
#     visitNumber = random.randint(1,rNum)
#     visitors.append(visitNumber)
#     rNum -= visitNumber
# 
# #print(visitor)
# 
# group1 = visitors[0] * 0
# group2 = visitors[1] * 200
# group3 = visitors[2] * 300
# group4 = visitors[3] * 500
# group5 = visitors[4] * 0
# 
# print('-'*30)
# print(f'영유아\t : {visitors[0]}명\t : {group1}원')
# print(f'어린이\t : {visitors[1]}명\t : {group2}원')
# print(f'청소년\t : {visitors[2]}명\t : {group3}원')
# print(f'성인\t\t : {visitors[3]}명\t : {group4}원')
# print(f'어르신\t : {visitors[4]}명\t : {group5}원')
# print('-'*30)
# print(f'1일 요금 총합계 : {group1+group2+group3+group4+group5}원')
# print('-'*30)


import random

visitors = []

for n in range(100): # 방문객 나이 생성
    visitors.append(random.randint(1, 100))
#print(visitor)

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

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


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

💡 [연습문제] 리스트 04

친구 이름 다섯 명을 리스트에 저장하고 오름차순과 내림차순으로 정렬

# 친구 이름 다섯 명을 리스트에 저장하고 오름차순과 내림차순으로 정렬

friendName = []

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

print(f'친구들 : {friendName}')
friendName.sort()
print(f'오름차순 : {friendName}')
friendName.sort(reverse=True)
print(f'내림차순 : {friendName}')

💡 다음 리스트에서 중복 아이템(숫자)을 제거하는 프로그램을 생성

# 다음 리스트에서 중복 아이템(숫자)을 제거하는 프로그램을 생성

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

💡 [연습문제] 리스트 05

💡 4개의 숫자 중 서로 다른 숫자 2개를 선택해서 만들 수 있는 모든 경우의 수를 출력하는 프로그램을 생성

# 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
pernutation = math.factorial(len(numbers)) / math.factorial(len(numbers)-2)
print(f'pernutation : {pernutation}')
print()

💡 4개의 숫자 중 서로 다른 숫자 3개를 선택해서 만들 수 있는 모든 경우의 수를 출력하는 프로그램을 생성

# 4개의 숫자 중 서로 다른 숫자 3개를 선택해서 만들 수 있는 모든 경우의 수를
# 출력하는 프로그램을 생성

numbers = [4, 6, 7, 9]

# result = []
# for n1 in numbers:
#     for n2 in numbers:
#         for n3 in numbers:
#             if n1 == n2 or n1 == n3 or n2 == n3:
#                 continue
#             result.append([n1, n2, n3])
# print(f'result : {result}')
# print(f'result length : {len(result)}')


result2 = []
for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue
        for n3 in numbers:
            if n1 == n3 or n2 == n3:
                continue
            result2.append([n1, n2, n3])
print(f'result : {result2}')
print(f'result length : {len(result2)}')

💡 [연습문제] 튜플 01

자주 접속하는 웹사이트 비번을 튜플에 저장

# 자주 접속하는 웹사이트 비번을 튜플에 저장

passwords = ('password1234', 'abc123', 'qwerty', 'letmein', 'welcome00')
print(f'passwords : {passwords}')

💡 대학생 길동이의 1, 2, 3학년의 성적은 다음과 같다. 졸업할 때 4.0이상의 학점을 받기 위해 길동이가 받아야 하는 4학년 1, 2학기의 최소 학점을 구하기

# 대학생 길동이의 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}')

💡 [연습문제] 튜플 02

💡 다음 2개의 튜플에 대해서 합집합과 교집합을 출력

# 다음 2개의 튜플에 대해서 합집합과 교집합을 출력

# tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
# tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
#
# tempHap = list(tuple1)
# tempGyo = list()
#
# for num in tuple2:
#     if num not in tempHap:
#         tempHap.append(num)
#     else:
#         tempGyo.append(num)
# tempHap = tuple(sorted(tempHap))
# tempGyo.sort()
# tempGyo = tuple(tempGyo)
# print(f'합집합(중복X)\t : {tempHap}')
# print(f'교집합\t\t : {tempGyo}')



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)\t : {tempHap}')
print(f'교집합\t\t : {tempGyo}')

[연습문제] 튜플 03

다음 튜플을 요구 사항에 맞춰 아이템을 슬라이스

# 다음 튜플을 요구 사항에 맞춰 아이템을 슬라이스

numbers = (8.7, 9.0, 9.1, 9.2, 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:-2]}')
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))}')

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

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

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] < 90 and item[key] >= 80:
            item[key] = 'B'
        elif item[key] < 80 and item[key] >= 70:
            item[key] = 'C'
        elif item[key] < 70 and item[key] >= 60:
            item[key] = 'D'
        else:
            item[key] = 'F'
scores = tuple(scores)
print(f'scores : {scores}')

💡 [연습문제] 튜플 04

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

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

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]
    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)


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)

💡 [연습문제] 튜플 05

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

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

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

totalCnt = 0
avg = 0
minStdClass = ''
minStdCnt = 0
maxStdClass = ''
maxStdCnt = 0
deviationClass = list(studentCnt)
deviation = []


for item in studentCnt:
    for cls in item.keys():
        totalCnt += item[cls]
        if minStdCnt == 0 or minStdCnt > item[cls]:
            minStdCnt = item[cls]
            minStdClass = cls
        if  maxStdCnt < item[cls]:
            maxStdCnt = item[cls]
            maxStdClass = cls

avg = totalCnt / len(studentCnt)
for item in deviationClass:
    for cls in item.keys():
        item[cls] = (item[cls] - avg)

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

print(f'전체 학생 수 : {totalCnt} 명')
print(f'평균 학생 수 : {avg} 명')
print(f'학생 수가 가장 적은 학급 : {minStdClass}({minStdCnt} 명)')
print(f'학생 수가 가장 적은 학급 : {maxStdClass}({maxStdCnt} 명)')
print(f'학급별 학생 편차 : {deviationClass}')
print(f'학급별 학생 편차2 : {deviation}')

💡 [연습문제] 딕셔너리 01

💡 과목별 점수를 딕셔너리에 저장하고 출력하는 프로그램을 생성

# 과목별 점수를 딕셔너리에 저장하고 출력하는 프로그램을 생성

subject = ['국어', '영어', '수학', '과학', '국사']
scores = {}

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

print(f'과목별 점수 : {scores}')

💡 사용자의 아이디, 비밀번호를 이용해서 로그인 프로그램을 생성

# 사용자의 아이디, 비밀번호를 이용해서 로그인 프로그램을 생성

members = {'urkpo':'0928^7$', 'xxayv':'%2*9$91','lsqvx':'!0%)%%4',
           'heums':'%@3^0%3', 'uwcmc':'85236(&','iemwv':')8!36^&',
           'sqblx':')^2)0!(', 'jbbpy':'67269*3', 'hjkwu':'$&@@#64',
           'fvwwy':'82$%)31'}

inputId = input('ID 입력 : ')
inputPW = input('PW 입력 : ')

# if inputId not in members.keys():
#     print('아이디 확인!')
# else:
#     if inputPW not in members.values():
#         print('비밀번호 확인')
#     else:
#         print('로그인 성공!')


if inputId in members:
    if members[inputId] == inputPW:
        print('로그인 성공')
    else:
        print('비밀번호 확인!')
else:
    print('아이디 확인')

💡 [연습문제] 딕셔너리 02

💡 삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램을 생성
n각형 내각의 합 : 180 * (n-2)

# 삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램을 생성
# n각형 내각의 합 : 180 * (n-2)


dic = {}

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

print(dic)

💡 1부터 10까지 각각의 정수에 대한 약수를 저장하는 딕셔너리를 만들고 출력하는 프로그램을 생성

# 1부터 10까지 각각의 정수에 대한 약수를 저장하는 딕셔너리를 만들고 출력하는 프로그램을 생성

dic = {}

for num in range(1, 11):
    tempList = [] # ★★★
    for n in range(1, num+1): # ★
        if num % n == 0:
            tempList.append(n)
    dic[num] = tempList

print(dic)

💡 [연습문제] 딕셔너리 03

  • .split() : 문자열을 특정 규칙에 따라 자른 후 리스트로 반환
  • find() : 문자열 찾아 index 반환, 찾으면 index, 못찾으면 -1값 반환 (출처 : w3school)

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

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

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

pythonList = aboutPython.split(' ')
print(pythonList)
pythonDic = {}
for idx, str in enumerate(pythonList):
    pythonDic[idx] = str

print(pythonDic)

💡 다음 문장에서 비속어를 찾고 비속어를 표준어로 변경하는 프로그램을 생성

# 다음 문장에서 비속어를 찾고 비속어를 표준어로 변경하는 프로그램을 생성

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

words = {'꺼지다':'가다', '쩔다':'엄청나다','짭새':'경찰관','꼽사리':'중간에 낀 사람',
         '먹튀':'먹고 도망', '지린다':'겁을 먹다', '쪼개다':'웃다', '뒷담 까다':'험담하다'}

#sentenceList = sentence.split()
# print(sentence)
#
# for key in words.keys():
#     if sentence.find(key) != -1:
#         print(f'key : {key}')
#         print(f'words[{key}] : {words[key]}')
#         sentence = sentence.replace(key, words[key])
#         #print(sentence)
# print(sentence)
# print()


keys = list(words.keys())

for key in keys: # ★★★
    if key in sentence:
        print(f'key : {key}')
        print(f'words[{key}] : {words[key]}')
        sentence = sentence.replace(key, words[key])

print(sentence)

💡 [연습문제] 딕셔너리 04

딕셔너리를 이용해서 5명의 회원을 가입 받고 전체 회원 정보를 출력하는 프로그램을 생성

# 딕셔너리를 이용해서 5명의 회원을 가입 받고 전체 회원 정보를 출력하는 프로그램을 생성

# member = {}
#
# for num in range(5):
#     inputMail = input('메일 입력 : ')
#     inputPW = input('비번 입력 : ')
#
#     member[inputMail] = inputPW
#
# print(member)

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

    if mail in members:
        print('이미 사용 중인 메일 계정입니다.')
        continue
    else:
        members[mail] = pw
        n += 1
print(members)

💡 위의 프로그램을 이용해서 특정 회원 계정을 삭제하는 프로그램을 생성

# 위의 프로그램을 이용해서 특정 회원 계정을 삭제하는 프로그램을 생성

print(members)

# while True:
#     removeMail = input('삭제할 계정 입력 : ')
#     if removeMail not in members:
#         print('계정 확인 요망!')
#     else:
#         recheckPw = input('비번 입력 : ')
#         if recheckPw not in members.values():
#             print('비번 확인 요망!')
#         else:
#             del members[removeMail]
#             print(f'{removeMail}님 삭제 완료!')
#             break

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

💡 [연습문제] 딕셔너리 05

💡 다음은 학생 정보 테이블이다. 파이썬에서 학생 정보를 가장 효율적으로 저장하고 관리할 수 있는 자료구조를 선택해서 컨테이너 자료형으로 생성

# 다음은 학생 정보 테이블이다. 파이썬에서 학생 정보를 가장 효율적으로 저장하고
# 관리할 수 있는 자료구조를 선택해서 컨테이너 자료형으로 생성

students = {'S21-0001':{'이름':'최성훈',
                        '성구분':'M',
                        '전공':'디자인',
                        '연락처':'010-1234-5678',
                        '메일':'hun@gmail.com',
                        '취미':['농구','음악']},
            'S21-0002': {'이름': '탁영우',
                         '성구분': 'M',
                         '전공': '바리스트',
                         '연락처': '010-5678-9012',
                         '메일': 'yeong@gmail.com',
                               '취미':['축구']},
            'S21-0003': {'이름': '황진영',
                         '성구분': 'W',
                         '전공': '음악',
                         '연락처': '010-9012-3456',
                         '메일': 'jin@gmail.com',
                               '취미':['수영', '코딩']}}

print(students)

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

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

studentNo = input('조회 대상 학생 번호 입력 : ')
print('{} : {}' .format(studentNo, students[studentNo]))

💻 출처 : 제로베이스 데이터 취업 스쿨

0개의 댓글