1부터 사용자가 입력한 숫자까지의 약수와 소수를 리스트에 각각 저장하고 ,이것을 출력하는 프로그램을 만들어보자.
inputNum = int(input('1보다 큰 정수 입력: '))
listA = []
listB = []
#약수
for n in range(1, inputNum+1):
if n == 1:
listA.append(n)
else:
if inputNum % n == 0:
listA.append(n)
print('{}의 약수: {}'.format(inputNum, 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('{}까지의 소수: {}'.format(inputNum, listB))
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)}개')
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
else:
group5 += 1
group1Price = group1 * 0
group2Price = group2 * 200
group3Price = group3 * 300
group4Price = group4 * 500
group5Price = group5 * 0
print('-'*25)
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('-'*25)
sum = group1Price+group2Price+group3Price+group4Price+group5Price
sumFormat = format(sum, ',')
print(f'1일 요금 총합계: {sumFormat}원')
print('-'*25)
1) 이름 다섯 명을 리스트에 저장하고 오름차순과 내림차순으로 정렬해보자.
friends = []
for i in range(5):
friends.append(input('친구 이름 입력: '))
print(f'friends: {friends}')
friends.sort()
print(f'friends(오름차순): {friends}')
friends.sort(reverse=True)
print(f'friends(내림차순): {friends}')
2) 리스트에서 중복 아이템 (숫자)을 제거하는 프로그램을 만들어보자.
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}')
1) 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)}')
2) 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(f'result: {result}')
print(f'result length: {len(result)}')
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}')
grade4TargetScore = round((4.0*8 - total), 1)
print(f'4학년 목표 총학점: {grade4TargetScore}')
minscore = round((grade4TargetScore/2), 1)
print(f'4학년 한학기 최소학점: {minscore}')
scores = list(scores)
scores.append((minscore, minscore))
scores = tuple(scores)
print(f'scores: {scores}')
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 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'합집합: {tempHap}')
print(f'교집합: {tempGyo}')
시험 점수를 입력한 후 튜플에 저장하고 과목별 학점을 출력해보자 .
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(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(scores)
튜플 안의 값은 변경 불가이지만,
여기서는 튜플 안 딕셔너리 값이라 변경가능하다.
다음 튜플의 과일 개수에 대해서 오름차순 및 내림차순으로 정렬해보자.
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
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}')
과목별 점수를 딕셔너리에 저장하고 출력하는 프로그램을 만들어보자 .
subject = ['국어', '영어', '수학', '과학', '국사']
scores = {}
for s in subject:
score = int(input(s + ' 점수 입력: '))
scores[s] = score
print(f'과목별 점수: {scores}')
1) 삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램을 만들어보자.
dic = {}
for n in range(3, 11):
hap = 180 * (n-2)
ang = int(hap / n)
dic[n] = [hap, ang]
print(dic)
2) 1부터 10 까지 각각의 정수에 대한 약수를 저장하는 딕셔너리를 만들고 출력하는 프로그램을 만들어보자.
dic = {}
for n1 in range(2, 11):
tempList = []
for n2 in range(1, n1+1):
if n1 % n2 == 0:
tempList.append(n2)
dic[n1] = tempList
print(dic)
1) 다음 문구를 공백으로 구분하여 리스트에 저장한 후,인덱스와 단어를 이용해서 딕셔너리에 저장해보자.
aboutPython = '파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어이다.'
splitList = aboutPython.split()
print(splitList)
dic = {}
for idx, v in enumerate(splitList):
dic[idx] = v
print(dic)
2) 다음 문장에서 비속어를 찾고 비속어를 표준어로 변경하는 프로그램을 만들어보자.
words = {'짭새':'경찰관', '먹튀': '먹고 도망', '쪼개다':'웃다'}
txt = '강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.'
keys = list(words.keys())
for key in keys:
if key in txt:
print('key: {}'.format(key))
print('words[{}]: {}'.format(key, words[key]))
txt = txt.replace(key, words[key])
print(txt)
1) 딕셔너리를 이용해서 5명의 회원을 가입 받고 전체 회원 정보를 출력하는 프로그램을 만들어보자 .
members = {}
n = 1
while n < 6:
mail = input('메일 입력: ')
pw = input('비번 입력: ')
if mail in members:
print('이미 사용 중인 메일 계정입니다.')
continue
else:
members[mail] = pw
n += 1
for key in members.keys():
print(f'{key}: {members[key]}')
2) 위의 프로그램을 이용해서 특정 회원 계정을 삭제하는 프로그램을 만들어보자.
#삭제
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문과 while문을 자유롭게 사용할 수 있으면 좋겠다.
튜플은 변경, 삭제가 안된다는 제한으로 인해 그대로는 쓰기 어려운 것 같다.