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):
if number % n == 0:
flag = False
break
if flag:
listB.append(number)
print(f'{inputNum}까지의 약수 = {listA}, \n소수 = {listB})')
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'even Nums = {evens}, {len(evens)}개 \nodd Nums = {odds}, {len(odds)}개 \nranNumList = {randomList}')
import random
allPeopleAge = []
infant = []
child = []
teen = []
adult = []
old = []
n = 1
while n <= 100:
ranPersonAge = random.randint(1, 100)
allPeopleAge.append(ranPersonAge)
n += 1
print(allPeopleAge)
print(len(allPeopleAge))
for age in allPeopleAge:
if age <= 7 and age >= 0:
infant.append(age)
elif age >= 8 and age <= 13:
child.append(age)
elif age >= 14 and age <= 19:
teen.append(age)
elif age >= 20 and age <= 64:
adult.append(age)
else:
old.append(age)
print('-'66)
print(f'영유아\t:\t{len(infant)}\t:\t0원')
print(f'어린이\t:\t{len(child)}\t:\t{len(child)200}원')
print(f'청소년\t:\t{len(teen)}\t:\t{len(teen)300}원')
print(f'성인\t:\t{len(adult)}\t:\t{len(adult)500}원')
print(f'노인\t:\t{len(old)}\t:\t0원')
print('-'66)
print(f'1일 요금 총 합계: {len(child)200 + len(teen)300 + len(adult)500}')
print('-'*66)
friends = []
for i in range(5):
friends.append(input('친구 이름 입력: '))
print(f'friends: {friends}')
friends.sort()
print(f'friends: {friends}')
numbers = [1, 2, 4, 66, 333, 44, 33, 66, 3, 1, 2, 2, 1, 4, 33, 55, 66, 32]
print(numbers)
idx = 0
while True:
if idx >= len(numbers):
break
if numbers.count(numbers[idx]) >= 2:
numbers.remove(number[idx])
continue
idx += 1
print(numbers)
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)}')
import math
numbers = [4, 6, 7, 9]
permutation = math.factorial(len(numbers)) / math.factorial(len(numbers) - 2)
print(f'result: {int(permutation)}')
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}')
grade4TagrgetScore = round((4.0 * 8 - total), 1)
print(f'4학년 총 목표 학점: {grade4TagrgetScore}')
minScore = round((grade4TagrgetScore / 2), 1)
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)
합집합 = list(tuple1)
교집합 = list()
for n in tuple2:
if n not in 합집합:
합집합.append(n)
else:
교집합.append(n)
합집합 = tuple(sorted(합집합))
교집합 = tuple(sorted(교집합))
print(f'합집합: {합집합}')
print(f'교집합: {교집합}')
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
합집합 = tuple1 + tuple2
교집합 = list()
합집합 = list(합집합)
idx = 0
while True:
if idx >= len(합집합):
break
if 합집합.count(합집합[idx]) >= 2:
교집합.append(합집합[idx])
합집합.remove(합집합[idx])
continue
idx += 1
합집합 = tuple(sorted(합집합))
교집합 = tuple(sorted(교집합))
print(f'합집합: {합집합}')
print(f'교집합: {교집합}')
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] >= 90:
item[key] = 'D'
else:
item[key] = 'E'
print(scores)
scores = (
{'kor' : 84},
{'eng' : 94},
{'mat' : 67},
{'sci' : 88},
{'his' : 97},
{'spa' : 75}
)
scores = list(scores)
cIdx = 0 # 현재 인덱스 값, 비교의 기준이 되는 것
nIdx = 1 # 비교의 대상이 되는 것
eIdx = len(scores) - 1 # 끝에 해당되는 인덱스 값
flag = True
while flag:
curDic = scores[cIdx] # 끝날때까지 변화가 없다
nextDic = scores[nIdx] # 한 번씩 증가를 해줘야
curDicScore = list(curDic.values())[0] # 벨류즈에서 0번째
nextDicScore = list(nextDic.values())[0]
if nextDicScore < curDicScore: # '>' 이렇게 바꾸면 내림차순 됨
scores.insert(cIdx, scores.pop(nIdx)) # 현재 인덱스 값에 삽입, 다음 인덱스 값의 점수를 삭제
nIdx = cIdx + 1
continue
nIdx += 1
if nIdx > eIdx:
cIdx += 1
nIdx = cIdx + 1
if cIdx == 5:
flag = False
print(tuple(scores))
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}')
subject = ['국어', '영어', '수학', '과학', '국사']
scores = {}
for s in subject:
score = input(s + '점수 입력: ')
scores[s] = score
print(f'과목별 점수: {scores}')
dic = {}
for n in range(3, 11):
sum = 180 * (n-2)
ang = int(sum / n)
dic[n] = [sum, ang]
print(dic)
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)
sentence = '공적인 일 말고도 살다보면 사적으로 힘들고 우울한 날도 많으실겁니다. 기분이 우울한 느낌이 들때 힘이되는 좋은글을 읽으면 그래도 힐링이 되는데요. 들으면 기분 좋아지는 글귀를 모아봤습니다. 모두 이 글을 읽어보시고 힘을 얻으시면 좋겠습니다!'
splitSentence = sentence.split()
print(splitSentence)
dic = {}
for idx, v in enumerate(splitSentence):
dic[idx] = v
print(dic)
words = {'꺼지다':'가다',
'쩔다':'엄청나다',
'짭새':'경찰관',
'꼽사리':'중간에 낀 사람',
'먹튀':'먹고 도망',
'지린다':'겁을 먹다',
'쪼개다':'웃다',
'뒷담 까다':'험담하다'}
txt = '강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.'
keys = list(words.keys())
txtMod = ''
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)
members = {}
n =1
while n < 6:
mail = input('mail: ')
pw = input('password: ')
if mail in members:
print('u already signed here in')
continue
else:
members[mail] = pw
n += 1
for key in members.keys():
print(f'{key} : {members[key]}')
while True:
delMail = input('mail u want to delet: ')
if delMail in members:
delPw = input('password: ')
if members[delMail] == delPw:
del members[delMail]
print(f'{delMail}')
break
else:
print('password should be checked again')
else:
print('mail should be checked again')
for key in members.keys():
print(f'{key} : {members[key]}')
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 k1 in students.keys():
print('-' * 40)
print('회원번호 : {}'.format(k1))
student = students[k1]
for k2 in student.keys():
print('{} : {}'.format(k2, student[k2]))
memNo = input('조회할 회원번호를 입력하세요.: ')
print('{} : {}'.format(memNo, students[memNo]))
datas = [3, 2, 5, 7, 9, 1, 0, 8, 6, 4]
print(f'datas: {datas}')
print(f'datas length: {len(datas)}')
searchData = int(input('찾으려는 숫자 입력: '))
searchResultIdx = -1
n = 0
while True:
if n == len(datas):
searchResultIdx = -1
break
elif datas[n] == searchData:
searchResultIdx = n
break
n += 1
print(f'searchResultIdx: [{searchResultIdx}]')
datas = [3, 2, 5, 7, 9, 1, 0, 8, 6, 4]
print(f'datas: {datas}')
print(f'datas length: {len(datas)}')
searchData = int(input('찾으려는 숫자 입력: '))
searchResultIdx = -1
datas.append(searchData)
n = 0
while True:
# if n == len(datas):
# searchResultIdx = -1
# break
if datas[n] == searchData:
if n != len(datas) - 1:
searchResultIdx = n
break
n += 1
print(f'datas: {datas}')
print(f'datas length: {len(datas)}')
print(f'searchResultIdx: [{searchResultIdx}]')
nums = [4, 7, 10, 2, 4, 7, 0, 2, 7, 3, 9]
print(f'nums: {nums}')
print(f'nums length: {len(nums)}')
searchData = int(input('찾으려는 숫자 입력: '))
searchResultIdx = -1
nums.append(searchData)
n = 0
while True:
if nums[n] == searchData:
if n != len(nums) - 1:
searchResultIdx = n
break
n += 1
print(f'nums: {nums}')
print(f'nums length: {len(nums)}')
print(f'searchResultIdx: [{searchResultIdx}]')
if searchResultIdx < 0:
print(f'찾으려는 {searchData}가(이) 없습니다.')
else:
print(f'찾으려는 {searchData}의 위치(인덱스)는 {searchResultIdx}입니다.')
nums = [4, 7, 10, 2, 4, 7, 0, 2, 7, 3, 9]
print(f'nums: {nums}')
print(f'nums length: {len(nums)}')
searchData = int(input('찾으려는 숫자 입력: '))
searchResultIdxs = []
nums.append(searchData)
n = 0
while True:
if nums[n] == searchData:
if n != len(nums) - 1:
searchResultIdxs.append(n)
else:
break
n += 1
print(f'nums: {nums}')
print(f'nums length: {len(nums)}')
print(f'searchResultIdxs: {searchResultIdxs}')
print(f'searchResultCnts: {len(searchResultIdxs)}')
datas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(f'datas: {datas}')
print(f'datas length: {len(datas)}')
searchData = int(input('찾으려는 숫자 입력: '))
searchResultIdx = -1
staIdx = 0
endIdx = len(datas) - 1
midIdx = (staIdx + endIdx) // 2
midVal = datas[midIdx]
print(f'midIdx: {midIdx}')
print(f'midVal: {midVal}')
while searchData <= datas[len(datas)-1] and searchData >= datas[0]:
if searchData == datas[len(datas)-1]:
searchResultIdx = len(datas)-1
break
if searchData > midVal:
staIdx = midIdx
midIdx = (staIdx + endIdx) // 2
midVal = datas[midIdx]
print(f'midIdx: {midIdx}')
print(f'midVal: {midVal}')
elif searchData < midVal:
endIdx = midIdx
midIdx = (staIdx + endIdx) // 2
midVal = datas[midIdx]
print(f'midIdx: {midIdx}')
print(f'midVal: {midVal}')
elif searchData == midVal:
searchResultIdx = midIdx
break
print(f'searchResultIdx: [{searchResultIdx}]')
nums = [4, 10, 22, 5, 0, 17, 7, 11, 9, 61, 88]
print(f'nums: {nums}')
nums.sort()
print(f'nums: {nums}')
searchData = int(input('찾으려는 숫자 입력: '))
searchResultIdx = -1
staIdx = 0
endIdx = len(nums) - 1
midIdx = (staIdx + endIdx) // 2
midVal = nums[midIdx]
while searchData <= nums[len(nums)-1] and searchData >= nums[0]:
if searchData == nums[len(nums)-1]:
searchResultIdx = len(nums)-1
break
if searchData > midVal:
staIdx = midIdx
midIdx = (staIdx + endIdx) // 2
midVal = nums[midIdx]
print(f'midIdx: {midIdx}')
print(f'midVal: {midVal}')
elif searchData < midVal:
endIdx = midIdx
midIdx = (staIdx + endIdx) // 2
midVal = nums[midIdx]
print(f'midIdx: {midIdx}')
print(f'midVal: {midVal}')
elif searchData == midVal:
searchResultIdx = midIdx
break
print(f'searchResultIdx: [{searchResultIdx}]')
import random
scores = random.sample(range(50, 101), 20)
ranks = [0 for i in range(20)]
print(scores)
print(ranks)
for idx, sco1 in enumerate(scores):
for sco2 in scores:
if sco1 < sco2:
ranks[idx] += 1
print(scores)
print(ranks)
for i, s in enumerate(scores):
print(f'score:{s} \t rank:{ranks[i] + 1}')
import rankMod as rm
import random
midStuScos = random.sample(range(50, 101), 20)
endStuScos = random.sample(range(50, 101), 20)
rd = rm.RankDeviation(midStuScos, endStuScos)
rd.setMidRank()
print(f'midStuScos: {midStuScos}')
print(f'mid_rank: {rd.getMidRank()}')
rd.setEndRank()
print(f'endStuScos: {endStuScos}')
print(f'end_rank: {rd.getEndRank()}')
rd.printRankDeviation()
import random
class RankDeviation:
def __init__(self, mss, ess):
self.midStuScos = mss
self.endStuScos = ess
self.midRanks = [0 for i in range(len(mss))]
self.endRanks = [0 for i in range(len(mss))]
self.rankDeviation = [0 for i in range(len(mss))]
def setRank(self, ss, rs):
for idx, sco1 in enumerate(ss):
for sco2 in ss:
if sco1 < sco2:
rs[idx] += 1
def setMidRank(self):
self.setRank(self.midStuScos, self.midRanks)
def getMidRank(self):
return self.midRanks
def setEndRank(self):
self.setRank(self.endStuScos, self.endRanks)
def getEndRank(self):
return self.endRanks
def printRankDeviation(self):
for idx, mRank in enumerate(self.midRanks):
deviation = mRank - self.endRanks[idx]
if deviation > 0:
deviation = '↑' + str(abs(deviation))
elif deviation < 0:
deviation = '↓' + str(abs(deviation))
else:
deviation = '=' + str(abs(deviation))
print(f'mid_rank: {mRank} \t end_rank: {self.endRanks[idx]} \t Deviation: {deviation}')
nums = [10, 2, 7, 21, 0]
length = len(nums) - 1
for i in range(length):
for j in range(length-i):
if nums[j] > nums[j+1]:
# temp = nums[j]
# nums[j] = nums[j+1]
# nums[j+1] = temp
nums[j], nums[j+1] = nums[j+1], nums[j]
print(nums)
print()
print(f'sorted nums: {nums}')
import copy
def bubbleSort(ns):
cns = copy.copy(ns)
length = len(cns) - 1
for i in range(length):
for j in range(length - i):
if cns[j] > cns[j + 1]:
cns[j], cns[j + 1] = cns[j + 1], cns[j]
return cns
nums = [10, 2, 7, 21, 0]
sortedNums = bubbleSort(nums)
print(f'nums: {nums}')
print(f'sortedNums: {sortedNums}')
import sortMod as sm
import random as rd
students = []
for i in range(20):
students.append(rd.randint(170, 185))
print(f'students: {students}')
print(f'students length: {len(students)}')
sortedStudents = sm.bubbleSort(students)
print(f'students: {students}')
print(f'sortedStudents: {sortedStudents}')
import copy
def bubbleSort(ns, deepCopy = True): # ns = Nums
if deepCopy:
cns = copy.copy(ns)
else:
cns = ns
length = len(cns) - 1 # 가장 끝에서 바로 앞에 있는 것 까지만 바교
for i in range(length):
for j in range(length - i):
if cns[j] > cns[j + 1]:
cns[j], cns[j + 1] = cns[j + 1], cns[j]
return cns
import sortMod as sm
nums = [5, 10, 2, 1, 0]
result = sm.sortNumber(nums, asc=False)
print(f'result: {result}')
def sortNumber(ns, asc=True):
if asc:
for i1 in range(1, len(ns)):
i2 = i1 - 1
cNum = ns[i1]
while ns[i2] > cNum and i2 >= 0:
ns[i2 + 1] = ns[i2]
i2 -= 1
ns[i2+1] = cNum
else:
for i1 in range(1, len(ns)):
i2 = i1 - 1
cNum = ns[i1]
while ns[i2] < cNum and i2 >= 0:
ns[i2 + 1] = ns[i2]
i2 -= 1
ns[i2 + 1] = cNum
return ns