💻 keep going
정리하는데 시간이 오래 걸리지만 다시 한 번 복습한다 생각하고 하면 마음이 편해진다.
앞으로도 꾸준하게 정리한 것을 업로드 해야겠다.
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)
# 소수
for number in range(2, inputNum + 1):
flag = True
for n in range(2, number):
# 1과 자기 자신이 아닌 약수가 또 있다.
if number % n == 0 :
flag = False
break
if flag:
listB.append(number)
print(listA)
print(listB)
1보다 큰 정수 입력 : 15
[1, 3, 5, 15]
[2, 3, 5, 7, 11, 13]
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("짝수 : {}, 개수 : {}개".format(evens, len(evens)))
print("홀수 : {}, 개수 : {}개".format(odds, len(odds)))
짝수 : [80, 4, 76, 20, 98, 14], 개수 : 6개
홀수 : [27, 17, 11, 29], 개수 : 4개
(단, 입장 고객의 나이는 난수를 이용한다.)
import random
visitors = []
for n in range(100):
visitors.append(random.randint(1, 100))
print(visitors)
group1, group2, group3, group4, group5 = 0, 0, 0, 0, 0 # 한번에 초기화
for age in visitors:
if 0 <= age <= 7 :
group1 += 1
elif 8 <= age <= 13:
group2 += 1
elif 14 <= age <= 19:
group3 += 1
elif 20 <= age <= 64:
group4 += 1
elif 65 <= age :
group5 += 1
group1Price = group1 * 0
group2Price = group2 * 200
group3Price = group3 * 300
group4Price = group4 * 500
group5Price = group5 * 0
print("-" * 30)
print("영유아\t : {}명\t : {}원".format(group1, group1Price))
print("어린이\t : {}명\t : {}원".format(group2, group2Price))
print("청소년\t : {}명\t : {}원".format(group3, group3Price))
print("성인 \t : {}명\t : {}원".format(group4, group4Price))
print("어르신\t : {}명\t : {}원".format(group5, group5Price))
print("-" * 30)
sum = group1Price + group2Price + group3Price + group4Price + group5Price
sumFormat = format(sum, ",")
# = print("총합 : {:,}원".format(sum))
print("총합 : {}원".format(sumFormat))
[56, 38, 80, 75, 44, 46, 40, 67, 43, 49, 66, 95, 24, 37, 20, 56, 80, 44, 67, 85, 98, 48, 64, 52, 77, 2, 71, 8, 39, 84, 44, 64, 55, 25, 29, 13, 16, 75, 78, 46, 48, 46, 24, 69, 28, 16, 14, 13, 16, 74, 79, 8, 17, 95, 13, 63, 95, 77, 79, 58, 38, 7, 75, 76, 65, 67, 87, 8, 6, 30, 51, 32, 46, 10, 45, 59, 55, 57, 96, 68, 37, 38, 82, 67, 63, 25, 49, 23, 33, 40, 1, 74, 33, 99, 74, 65, 56, 4, 47, 39]
------------------------------
영유아 : 5명 : 0원
어린이 : 7명 : 1400원
청소년 : 5명 : 1500원
성인 : 49명 : 24500원
어르신 : 34명 : 0원
------------------------------
총합 : 27,400원
friends = []
for n in range(5):
friends.append(input("친구 이름 입력 :"))
print(friends)
# 오름차순 reverse=False 생략가능
friends.sort(reverse=False)
print(friends)
# 내림차순
friends.sort(reverse=True)
print(friends)
친구 이름 입력 :박지원
친구 이름 입력 :김지원
친구 이름 입력 :이지원
친구 이름 입력 :조지원
친구 이름 입력 :하지원
['박지원', '김지원', '이지원', '조지원', '하지원']
['김지원', '박지원', '이지원', '조지원', '하지원']
['하지원', '조지원', '이지원', '박지원', '김지원']
# set() 을 이용해서 중복 제거
numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
print(f"numbers : {numbers}")
# 리스트 안 중복값 삭제
# -> set() : {}형태로 나오기에 list(set()) 해줘야 함
setNumbers = set(numbers)
print(f"setNumbers : {setNumbers}")
numbers : [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
setNumbers : {1, 2, 3, 5, 7, 8, 9, 22}
# while문을 이용해서 중복 제거
numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
idx = 0
while True:
if idx >= len(numbers):
break
# idx에 위치한 값이 numbers에서 2번이상 등장하는지 확인
if numbers.count(numbers[idx]) >= 2:
# 현재 인덱스에 위치한 값을 리스트에서 제거
numbers.remove(numbers[idx])
continue
idx += 1
print(f"numbers : {numbers}")
numbers : [22, 8, 9, 5, 2, 7, 1, 3]
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)}")
result : [[4, 6], [4, 7], [4, 9], [6, 4], [6, 7], [6, 9], [7, 4], [7, 6], [7, 9], [9, 4], [9, 6], [9, 7]]
result length : 12
# 순열 공식 : n! / (n-r)!
import math
p = int(math.factorial(len(numbers)) / math.factorial(len(numbers) - 2))
print(p)
12
numbers = [4, 6, 7, 9]
result = []
for n1 in numbers:
for n2 in numbers:
if n1 == n2:
continue
for n3 in numbers:
if n3 == n1 or n3 == n2:
continue
result.append([n1, n2, n3])
print(result)
[[4, 6, 7], [4, 6, 9], [4, 7, 6], [4, 7, 9], [4, 9, 6], [4, 9, 7], [6, 4, 7], [6, 4, 9], [6, 7, 4], [6, 7, 9], [6, 9, 4], [6, 9, 7], [7, 4, 6], [7, 4, 9], [7, 6, 4], [7, 6, 9], [7, 9, 4], [7, 9, 6], [9, 4, 6], [9, 4, 7], [9, 6, 4], [9, 6, 7], [9, 7, 4], [9, 7, 6]]
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))
# 4.0 * 8 : 평균 4.0을 위한 전체 점수
grade4TargetScore = round((4.0 * 8 - total), 1)
print(f"4학년 목표 총 학점 : {grade4TargetScore}")
# 4학년 1학기
minScore = round((grade4TargetScore / 2), 1)
print(f"4학년 한 학기 최소학점 : {minScore}")
scores = list(scores)
scores.append((minScore, minScore))
scores = tuple(scores)
print(scores)
3학년 총학점 : 23.4점
3학년 평균 : 3.9점
4학년 목표 총 학점 : 8.6
4학년 한 학기 최소학점 : 4.3
((3.7, 4.2), (2.9, 4.3), (4.1, 4.2), (4.3, 4.3))
# 방법 1
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
# 합집합
unionSet = set(tuple1).union(set(tuple2))
unionSet = tuple(unionSet)
print(f"합집합 : {unionSet}")
# 교집합
intersectionSet = set(tuple1).intersection(set(tuple2))
intersectionSet = tuple(intersectionSet)
print(f"교집합 : {intersectionSet}")
합집합 : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)
# 방법 2
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
# 튜플을 리스트 방식으로 먼저 바꿔준다
tempUni = list(tuple1)
tempInter = []
for n in tuple2:
if n not in tempUni:
tempUni.append(n)
else :
tempInter.append(n)
# sorted() : 오름차순으로 정렬
tempUni = tuple(sorted(tempUni))
tempInter = tuple(sorted(tempInter))
print(f"합집합 : {(tempUni)}")
print(f"교집합 : {(tempInter)}")
합집합 : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)
# 방법 3
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
tempUni = tuple1 + tuple2
tempInter = sorted(list())
tempUni = sorted(list(tempUni))
print(f"tempUni : {tempUni}")
print(f"tempInter : {tempInter}")
idx = 0
while True :
if idx >= len(tempUni):
break
if tempUni.count(tempUni[idx]) >= 2:
tempInter.append(tempUni[idx])
tempUni.remove(tempUni[idx])
continue
idx += 1
print()
print(f"tempUni : {tuple(tempUni)}")
print(f"tempInter : {tuple(tempInter)}")
tempUni : [0, 1, 2, 2, 3, 3, 5, 5, 6, 6, 7, 8, 8, 9, 12, 17]
tempInter : []
tempUni : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
tempInter : (2, 3, 5, 6, 8)
kor = int(input("국어 점수 입력 :"))
eng = int(input("영어 점수 입력 :"))
mat = int(input("수학 점수 입력 :"))
sci = int(input("과학 점수 입력 :"))
his = int(input("국사 점수 입력 :"))
scores = ({"국어":kor},
{"영어":eng},
{"수학:":mat},
{"과학":sci},
{"국사":his})
print("scores : {}".format(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)
국어 점수 입력 :80
영어 점수 입력 :70
수학 점수 입력 :65
과학 점수 입력 :40
국사 점수 입력 :90
scores : ({'국어': 80}, {'영어': 70}, {'수학:': 65}, {'과학': 40}, {'국사': 90})
({'국어': 'B'}, {'영어': 'C'}, {'수학:': 'D'}, {'과학': 'F'}, {'국사': 'A'})
numbers = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3)
# Index 0부터 3까지
print("numbers[:4] : {}".format(numbers[:4]))
# Index 2부터 4까지
print("numbers[2:5] : {}".format(numbers[2:5]))
# Index 3부터 끝까지
print("numbers[3:] : {}".format(numbers[3:]))
# Index 2부터 뒤에서 -2까지
print("numbers[2:-1] : {}".format(numbers[2:-1]))
# Index 0부터 끝까지 3단계씩
print("numbers[0::3] : {}".format(numbers[0::3]))
numbers[:4] : (8.7, 9.0, 9.1, 9.2)
numbers[2:5] : (9.1, 9.2, 8.6)
numbers[3:] : (9.2, 8.6, 9.3, 7.9, 8.1, 8.3)
numbers[2:-1] : (9.1, 9.2, 8.6, 9.3, 7.9, 8.1)
numbers[0::3] : (8.7, 9.2, 7.9)
numbers = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3)
print(f"최솟값 : {min(numbers)}")
print("최솟값 index {}".format(numbers.index(min(numbers))))
print(f"최댓값 : {max(numbers)}")
print("최댓값 index {}".format(numbers.index(max(numbers))))
최솟값 : 7.9
최솟값 index 6
최댓값 : 9.3
최댓값 index 5
fruits = {"수박":8}, {"포도":13}, {"참외":12}, {"사과":17}, {"자두":19}, {"자몽":15}
fruits = list(fruits)
# 현재 index
cIdx = 0
# 현재와 비교하는 index
nIdx = 1
# 마지막 index
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 = []
# index값과 dic에 key, value 구함
for idx, dic in enumerate(studentCnt):
for key, value in dic.items():
totalCnt += value
if minStdCnt == 0 or minStdCnt > value:
minStdCnt = value
minCls = key
if maxStdCnt < value:
maxStdCnt = value
maxCls = key
print(f"전체 학생 수 : {totalCnt}")
avgCnt = totalCnt / len(studentCnt)
print(f"평균 학생 수 : {avgCnt}")
print(f"학생 수가 가장 적은 학급 : {minCls}({minStdCnt})")
print(f"학생 수가 가장 많은 학급 : {maxCls}({maxStdCnt})")
전체 학생 수 : 160
평균 학생 수 : 20.0
학생 수가 가장 적은 학급 : cls08(17)
학생 수가 가장 많은 학급 : cls07(23)
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 = []
# index값과 dic에 key, value 구함
for idx, dic in enumerate(studentCnt):
for key, value in dic.items():
totalCnt += value
if minStdCnt == 0 or minStdCnt > value:
minStdCnt = value
minCls = key
if maxStdCnt < value:
maxStdCnt = value
maxCls = key
avgCnt = totalCnt / len(studentCnt)
# 편차 구하기
for idx, dic in enumerate(studentCnt):
for key, value in dic.items():
deviation.append(value - avgCnt)
print(f"학급별 학생 편차 : {deviation}")
학급별 학생 편차 : [-2.0, 1.0, 0.0, -1.0, 2.0, 0.0, 3.0, -3.0]
members = {'urkpo':'0928^7$',
'xxayv':'%2*9$91',
'lsqvx':'!0%)&&4',
'heums':'%@3^0%3',
'uwcmc':'85236(&',
'iemwv':')8!36^&',
'sqblx':')^2)9!(',
'jbbpy':'67269*3',
'hjkwu':'$&@@#64',
'fvwwy':'82$%)31'}
memID = input("ID 입력 : ")
memPW = input("PW 입력 : ")
if memID in members:
if members[memID] == memPW:
print("로그인 성공!!")
else :
print("비밀번호 확인")
ID 입력 : xxayv
PW 입력 : %2*9$91
로그인 성공!!
subject = ["국어", "영어", "수학", "과학", "국사"]
scores = {}
for s in subject:
score = input(s + "점수 입력 :")
# "scores" 사전에 새로운 키-값 쌍을 추가!
# ex) scores["국어"] = 88 (벨류값을 설정)
scores[s] = score
print(f"과목별 점수 : {scores}")
for i in scores.items():
print(i)
국어점수 입력 :80
영어점수 입력 :70
수학점수 입력 :80
과학점수 입력 :65
국사점수 입력 :70
과목별 점수 : {'국어': '80', '영어': '70', '수학': '80', '과학': '65', '국사': '70'}
('국어', '80')
('영어', '70')
('수학', '80')
('과학', '65')
('국사', '70')
(n각형의 내각의 합 : 180 x (n-2))
dic = {}
for n in range(3, 10):
hap = 180 * (n - 2)
ang = int(hap / n)
# dic안으로 key값 3(n) 의 value값을 [hap, ang]로 설정
dic[n] = [hap,ang]
print(dic)
{3: [180, 60], 4: [360, 90], 5: [540, 108], 6: [720, 120], 7: [900, 128], 8: [1080, 135], 9: [1260, 140]}
ic = {}
for n1 in range(1, 11):
#반복할 때마다 새로운 "tempList" 생성
# 따라서 n1 값에 대해 tempList가 초기화되고 해당 n1의 약수만 저장
tempList = []
# n1 + 1 : n1의 대한 약수
for n2 in range(1, n1 + 1):
# n2는 n1의 약수
if n1 % n2 == 0:
tempList.append(n2)
dic[n1] = tempList
print(dic)
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5], 6: [1, 2, 3, 6], 7: [1, 7], 8: [1, 2, 4, 8], 9: [1, 3, 9], 10: [1, 2, 5, 10]}
aboutPython = "파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 " \
"고급 프로그래밍 언어이다."
print(aboutPython)
splitList = aboutPython.split()
print(splitList)
dic = {}
for idx, v in enumerate(splitList):
dic[idx] = v
print(dic)
파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어이다.
['파이썬은', '1991년', '프로그래머인', '귀도', '반', '로섬이', '발표한', '고급', '프로그래밍', '언어이다.']
{0: '파이썬은', 1: '1991년', 2: '프로그래머인', 3: '귀도', 4: '반', 5: '로섬이', 6: '발표한', 7: '고급', 8: '프로그래밍', 9: '언어이다.'}
txt = "강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다."
words = {'꺼지다':'가다',
'쩔다':'엄청나다',
'짭새':'경찰관',
'꼽사리':'중간에 낀 사람',
'먹튀':'먹고 도망',
'지린다':'겁을 먹다',
'쪼개다':'웃다',
'뒷담 까다':'험담하다'}
# key값 빼내기
keys = list(words.keys())
print(keys)
for key in keys:
if key in txt:
print("key : {}".format(key))
print("word[{}] : {}".format(key, words[key]))
txt = txt.replace(key, words[key])
print(txt)
['꺼지다', '쩔다', '짭새', '꼽사리', '먹튀', '지린다', '쪼개다', '뒷담 까다']
key : 짭새
word[짭새] : 경찰관
key : 먹튀
word[먹튀] : 먹고 도망
key : 쪼개다
word[쪼개다] : 웃다
강도는 서로 웃다, 경찰관를 보고 빠르게 따돌리며 먹고 도망했다.
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]}")
# 프로그램을 이용해서 특정 회원 계정을 삭제하는 프로그램
while True:
delMail = input("삭제 계정(메일) 입력 : ")
if delMail in members:
delPw = input("비밀번호 입력 :")
# members에 delMail 에 해당하는 벨류가 delPw와 같으면
if members[delMail] == delPw:
# members 딕셔너리에 delMail 키와 값 모두 삭제
del members[delMail]
print(f"{delMail} 계정 삭제 완료!")
break
# Pw가 일치하지 않는 경우
else :
print("비번 확인 요망!!")
else :
print("계정 확인 요망!!")
print(members)
메일 입력 : a1@naver.com
비번 입력 : 123
메일 입력 : a2@naver.com
비번 입력 : 123
메일 입력 : a3@naver.com
비번 입력 : 123
메일 입력 : a4@naver.com
비번 입력 : 123
메일 입력 : a5@naver.com
비번 입력 : 123
a1@naver.com : 123
a2@naver.com : 123
a3@naver.com : 123
a4@naver.com : 123
a5@naver.com : 123
삭제 계정(메일) 입력 : a5@naver.com
비밀번호 입력 :123
a5@naver.com 계정 삭제 완료!
{'a1@naver.com': '123', 'a2@naver.com': '123', 'a3@naver.com': '123', 'a4@naver.com': '123'}
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',
'취미': ['수영', '코딩']}}
# 딕셔너리에서 반복하면서 전체데이터를 조회할 수 있는 가장 효율적인 방법 for문
for k1 in students.keys():
print(f"회원 번호 : {k1}")
print()
student = students[k1]
# students의 벨류값에 대한 반복문
for k2 in student.keys():
# student[k2] : students 벨류값의 벨류값
print("{} : {}".format(k2, student[k2]))
studentNo = input("조회 대상 학생 번호 : ")
print("{} : {}".format(studentNo, students[studentNo]))
회원 번호 : 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
취미 : ['수영', '코딩']
조회 대상 학생 번호 : S21-0003
S21-0003 : {'이름': '황진영', '성구분': 'W', '전공': '음악', '연락처': '010-9012-3456', '메일': 'jin@gmail.com', '취미': ['수영', '코딩']}