inputNum = int(input('1부터 큰 정수 입력: '))
listA = []
listB = []
for n in range(1, inputNum+1):
if inputNum % n == 0:
listA.append(n)
for n in range(2, inputNum+1):
flag = True
for num in range(2, n): # 각 수에 대해 소수인지 확인
if n % num == 0: # 소수(n)는 2~(n-1)의 약수를 가지지 않음
flag = False
break
if flag:
listB.append(n)
print('{}의 약수: {}'.format(inputNum, listA))
print('{}까지의 소수: {}'.format(inputNum, listB))
import random
randomList = random.sample(range(1, 101), 10) # random.sample은 무조건 리스트타입 반환
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))
babyCnt, kidCnt, teenCnt, adultCnt, oldCnt = 0, 0, 0, 0, 0
for age in visitors:
if age >= 0 and age <= 7:
babyCnt += 1
elif age >= 8 and age <= 13:
kidCnt += 1
elif age >= 14 and age <= 19:
teenCnt += 1
elif age >= 20 and age <= 64:
adultCnt += 1
elif age >= 65:
oldCnt += 1
babyPrice = babyCnt * 0
kidPrice = kidCnt * 200
teenPrice = teenCnt * 300
adultPrice = adultCnt * 500
oldPrice = oldCnt * 0
totalPrice = babyPrice + kidPrice + teenPrice + adultPrice + oldPrice
print('-' * 30)
print('영유아\t: {}명\t: {}원'.format(babyCnt, babyPrice))
print('어린이\t: {}명\t: {}원'.format(kidCnt, kidPrice))
print('청소년\t: {}명\t: {}원'.format(teenCnt, teenPrice))
print('성인\t\t: {}명\t: {}원'.format(adultCnt, adultPrice))
print('어르신\t: {}명\t: {}원'.format(oldCnt, oldPrice))
print('-' * 30)
print('1일 요금 총합계: {}원'.format(format(totalPrice, ',')))
print('-' * 30)
friends = []
for i in range(5): # 반복문 이용시 더 간단
friends.append(input('친구 이름 입력: '))
print(f'친구들 : {friends}')
friends.sort() # sort()는 결과값 반환X. 명령어일 뿐!
print(f'오름차순 : {friends}')
friends.sort(reverse=True)
print(f'내림차순 : {friends}')
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): # 인덱스가 len(numbers)(=13)이 되는 순간 끝내라
break
if numbers.count(numbers[idx]) >= 2: # 인덱스에 해당하는 수가 2개 이상일때
numbers.remove(numbers[idx]) # 해당 수를 삭제
continue # 해당 인덱스의 수를 삭제했기 때문에(다음 수들은 1씩 앞으로 땡겨지니까) 인덱스를 1 늘리지 않고 진행
idx += 1
print(f'numbers : {numbers}')
numbers = [4, 6, 7, 9]
result = []
for n1 in numbers:
for n2 in numbers:
if n1 == n2:
continue # 같은 숫자 2개를 선택하면 바로 반복문을 반복하여 append는 하지 않음
result.append([n1, n2])
print(f'result: {result}')
print(f'result length: {len(result)}') # 12
-> 중첩 반복문!!!!!!!
import math
per = math.factorial(len(numbers)) / math.factorial(len(numbers) - 2)
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(result)
print(len(result)) # 24
scores = ((3.7, 4.2), (2.9, 4.3), (4.1, 4.2))
total = 0; avg = 0
goalScoreAvg = 4.0
for s1 in scores:
for s2 in s1:
total += s2 # 3학년까지의 학점 총합 구하기
total = round(total, 1)
avg = round(total / 6, 1)
print(f'3학년 총학점: {total}')
print(f'3학년 평균: {avg}')
grade4TargetScore = round((4.0 * 8 - total), 1) # 4학년에 필요한 총학점
minScore = round(grade4TargetScore/2, 1)
print(f'4학년 목표 총학점: {grade4TargetScore}')
print(f'4학년 한학기 최소학점: {minScore}')
scores = list(scores) # 튜플은 수정불가라서 리스트로 변환 후 수정하기
scores.append((minScore, minScore))
scores = tuple(scores)
print(f'scores: {scores}')
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
totalNum = list(tuple1)
commonNum = list()
for n in tuple2:
if n not in totalNum:
totalNum.append(n)
else:
commonNum.append(n)
totalNum = tuple(sorted(totalNum)) # sorted()는 값을 반환해줌!
commonNum = tuple(sorted(commonNum))
print(f'합집합(중복X)\t: {totalNum}')
print(f'교집합\t\t: {commonNum}')
totalNum = list(tuple1 + tuple2)
commonNum = list()
idx = 0
while True:
if idx >= len(totalNum):
break
if totalNum.count(totalNum[idx]) >= 2:
commonNum.append(totalNum[idx])
totalNum.remove(totalNum[idx])
continue
idx += 1
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}')
-> 튜플은 수정불가지만 튜플 안에 있는 딕셔너리는 수정 가능!
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] # 현재 위치의 딕셔너리의 value값을 가져옴(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)
-> 오름차순 정렬
-> 어렵!!!!!!!
studentCnt = ({'cls01':18},
{'cls02':21},
{'cls03':20},
{'cls04':19},
{'cls05':22},
{'cls06':20},
{'cls07':23},
{'cls08':17})
sum = 0; avg = 0
minCnt = 0; maxCnt = 0
minCls = ''; maxCls = ''
deviation = []
for idx, dic in enumerate(studentCnt): # 인덱스와 item을 가져옴
for k, v in dic.items(): # 각 아이템에 대한 key,value값을 가져옴
sum += v
if minCnt == 0 or minCnt > v:
minCnt = v
minCls = k
if maxCnt < v:
maxCnt = v
maxCls = k
avg = sum / len(studentCnt)
print(f'전체 학생 수: {sum}명')
print(f'평균 학생 수: {avg}명')
print(f'학생 수가 가장 적은 학급: {minCls}({minCnt}명)')
print(f'학생 수가 가장 많은 학급: {maxCls}({maxCnt}명)')
for idx, dic in enumerate(studentCnt):
for k, v in dic.items():
deviation.append(v - avg)
print(f'학급별 학생 편차: {deviation}')
subject = ['국어', '영어', '수학', '과학', '국사']
scores = {}
for s in subject:
score = int(input(s + ' 점수 입력: '))
scores[s] = score # 각 키값에 value값 저장하기
print(f'과목별 점수 : {scores}')
-> 아직 '딕셔너리[key]=value' 개념이 생소하고 헷갈림!! 인덱스랑 헷갈리지 말기
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'}
id = input('ID 입력: ')
pw = input('PW 입력: ')
if id in members:
if pw == members[id]:
print('로그인 성공!!')
else:
print('비밀번호 확인')
else:
print('아이디 확인')
dic = {}
for n in range(3, 11):
hap = 180 * (n-2)
ang = int(hap / n)
dic[n] = [hap, ang] # value값을 리스트로 저장
print(dic)
dic = {}
for n in range(1, 11):
tempList = [] # 약수를 구해서 저장하는 리스트
for yak in range(1, n+1):
if n % yak == 0:
tempList.append(yak)
dic[n] = tempList
print(dic)
aboutPython = '파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어이다.'
splitList = aboutPython.split() # 공백으로 구분해서 문자열을 잘라준다
print(splitList)
dic = {}
for idx, word in enumerate(splitList):
dic[idx] = word
print(dic)
words = {'꺼지다':'가다',
'쩔다':'엄청나다',
'짭새':'경찰관',
'꼽사리':'중간에 낀 사람',
'먹튀':'먹고 도망',
'지린다':'겁을 먹다',
'쪼개다':'웃다',
'뒷담 까다':'험담하다'}
txt = '강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.'
for key in words.keys():
if key in txt:
print('key: {}'.format(key))
print('words[key]: {}'.format(words[key]))
txt = txt.replace(key, words[key]) # replace(바꿀대상, 대체할것)
print(txt)
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('{} : {}'.format(key, members[key]))
while True:
delMail = input('삭제할 계정(메일) 입력: ')
if delMail in members:
delPw = input('비번 입력: ')
if delPw == members[delMail]:
del members[delMail]
print(f'{delMail} 계정 삭제 완료!')
break
else:
print('비번 확인 요망')
else:
print('계정 확인 요망')
for key in members.keys():
print('{} : {}'.format(key, members[key]))
students = {'S21-0001':{'이름':'박병찬',
'성구분':'M',
'전공':'체육',
'연락처':'010-1234-5678',
'메일':'byungchan99@gmail.com',
'취미':['농구','게임']},
'S21-0002':{'이름':'기상호',
'성구분':'M',
'전공':'체육',
'연락처':'010-1233-5672',
'메일':'sangho94@gmail.com',
'취미':['농구','게임']},
'S21-0003':{'이름':'성준수',
'성구분':'M',
'전공':'체육',
'연락처':'010-3143-5612',
'메일':'junsu97@gmail.com',
'취미':['농구','게임']}}
for key1 in students.keys():
print('-' * 40)
print(f'학생번호: {key1}')
student = students[key1]
for key2 in student.keys():
print('{} : {}'.format(key2, student[key2]))
studentNo = input('조회대상 학생번호 입력: ')
print('{} : {}'.format(studentNo, students[studentNo]))
<제로베이스 데이터 취업 스쿨>