RUBY
튜플을 이용한 프로그래밍(파이썬) 본문
튜플을 이용한 프로그래밍(파이썬)
자주 접속하는 웹사이트 비번을 튜플에 저장해보자
passwds = ('password1234', 'abc123', 'qwerty', 'letmein', 'welcome00')
print(f'passwds : {passwds}')
passwds : ('password1234', 'abc123', 'qwerty', 'letmein', 'welcome00')
대학생 길동이의 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('-'*60)
grade4TagetScore = round((4.0 * 8 - total), 1)
print(f'4학년 목표 총학점: {grade4TagetScore}')
minScore = round(grade4TagetScore / 2, 1)
print(f'4학년 한학기 최소학점: {minScore}')
scores = list(scores)
scores.append((minScore, minScore))
print('-'*60)
scores = tuple(scores)
print(f'scores: {scores}')
3학년 총학점: 23.4
3학년 평균: 3.9
------------------------------------------------------------
4학년 목표 총학점: 8.6
4학년 한학기 최소학점: 4.3
------------------------------------------------------------
scores: ((3.7, 4.2), (2.9, 4.3), (4.1, 4.2), (4.3, 4.3))
다음 2개의 튜플에 대해서 합집합과 교집합을 출력해보자
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)
for n in tempHap:
if tempHap.count(n) > 1:
tempGyo.append(n)
tempHap.remove(n)
print(f'합집합(중복X): {tuple(sorted(tempHap))}')
print(f'교집합 : {tuple(sorted(tempGyo))}')
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
tempHap = list(tuple1)
tempGyo = list()
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}')
합집합(중복X) : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)
시험 점수를 입력한 후 튜플에 저장하고 과목별 학점을 출력해보자
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}')
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(f'scores: {scores}')
국어 점수 입력: 90
영어 점수 입력: 86
수학 점수 입력: 77
과학 점수 입력: 69
국사 점수 입력: 54
scores: ({'kor': 90}, {'eng': 86}, {'mat': 77}, {'sci': 69}, {'his': 54})
scores: ({'kor': 'A'}, {'eng': 'B'}, {'mat': 'C'}, {'sci': 'D'}, {'his': 'F'})
다음 튜플의 과일 개수에 대해서 오름차순 및 내림차순으로 정렬해보자
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))
({'수박': 8}, {'참외': 12}, {'포도': 13}, {'자몽': 15}, {'사과': 17}, {'자두': 19})
학급별 학생 수를 나타낸 튜플을 이용해서, 요구 사항에 맞는 데이터를 출력하는 프로그램을 만들어보자
* 전체 학생 수
* 평균 학생 수
* 학생 수가 가장 적은 학급
* 학생 수가 가장 많은 학급
* 학급별 학생 편차
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 idx == 0 or minStdCnt > v:
minStdCnt = v
minCls = k
if maxStdCnt < v:
maxStdCnt = v
maxCls = k
print(f'전체 학생 수: {totalCnt}명')
avgCnt = totalCnt/len(studentCnt)
print(f'평균 학생 수: {round(avgCnt, 2)}명')
print(f'학생 수가 가장 적은 학급: {minCls}({minStdCnt}명)')
print(f'학생 수가 가장 많은 학급: {maxCls}({maxStdCnt}명)')
for idx, dic in enumerate(studentCnt):
for k, v in dic.items():
deviation.append({k:round(v-avgCnt, 2)})
print(f'학급별 학생 편차: {deviation}')
전체 학생 수: 160명
평균 학생 수: 20.0명
학생 수가 가장 적은 학급: cls08(17명)
학생 수가 가장 많은 학급: cls07(23명)
학급별 학생 편차: [{'cls01': -2.0}, {'cls02': 1.0}, {'cls03': 0.0}, {'cls04': -1.0}, {'cls05': 2.0}, {'cls06': 0.0}, {'cls07': 3.0}, {'cls08': -3.0}]
'프로그래밍 언어 > Python' 카테고리의 다른 글
선형검색, 보초법 (파이썬) (0) | 2023.01.25 |
---|---|
딕셔너리를 이용한 프로그래밍(파이썬) (0) | 2023.01.24 |
리스트를 이용한 프로그래밍(파이썬) (0) | 2023.01.24 |
in, len(), clear() 딕셔너리(파이썬) (0) | 2023.01.23 |
del, pop() 딕셔너리 삭제(파이썬) (0) | 2023.01.23 |
Comments