Search

연습 문제

Ex1.
# 1부터 사용자가 입력한 숫자까지의 약수와 소수를 리스트에 각각 저장하고 # 출력하는 프로그램을 만들자. inputNum = int(input('1보다 큰 정수 입력: ')) listA = [] listB = [] # 약수 for n in range(1, inputNum + 1): if inputNum % n == 0: # 약수인 조건 listA.append(n) # 소수 for num in range(2, inputNum): # 2 ~ inputNum - 1 까지의 숫자에서 flag = True for j in range(2,num): if num % j == 0: # 하나라도 나눠떨어지는 숫자가 있다고 하면 flag = False break if flag: listB.append(num) print('{}의 약수 : {}'.format(inputNum, listA)) print('{}의 소수 : {}'.format(inputNum, listB))
Python
복사
Ex 2.
# 1 부터 100 사이에 난수 10개를 생성한 뒤 짝수와 홀수를 구분해서 리스트에 저장하고 각각의 개수를 출력하자. import random randNums = random.sample(range(1,101), 10) even = [] odd = [] for r in randNums: if r % 2 == 0: # 짝수이면 even.append(r) else: odd.append(r) print('짝수 결과: {}, 개수 : {}'.format(even,len(even))) print('홀수 결과: {}, 개수 : {}'.format(odd,len(odd)))
Python
복사
Ex3.
# 100명의 사람들의 나이 정보를 난수 발생해서 구해보자. import random randomAge = random.sample(range(0,101),100) # 0 ~ 7 : 무료 , 8 ~ 13 : 200, 14 ~ 19:300, 20 ~ 64: 500, 65 ~ : 무료 infant = []; infantFare = 0 child = []; childFare = 200 young = []; youngFare = 300 adult = []; adultFare = 500 senior = []; seniorFare = 0 for cnt in randomAge: if cnt < 8: # 영유아 infant.append(cnt) elif 8 <= cnt <= 13: # 어린이 child.append(cnt) elif 14 <= cnt <= 19: # 청소년 young.append(cnt) elif 20 <= cnt <= 64: # 어른 adult.append(cnt) else: # 노인 senior.append(cnt) infantTot = len(infant)*infantFare childTot = len(child)*childFare youngTot = len(young)*youngFare adultTot = len(adult)*adultFare seniorTot = len(senior)*seniorFare print('-'*35) print('영유아: {}명 : {}원'.format(len(infant), infantTot)) print('어린이: {}명 : {}원'.format(len(child), childTot)) print('청소년: {}명 : {}원'.format(len(young), youngTot)) print('성인: {}명 : {}원'.format(len(adult), adultTot)) print('노인: {}명 : {}원'.format(len(senior), seniorTot)) print('-'*35) tot_sum = infantTot + childTot + youngTot + adultTot + seniorTot print('1일 요금 총합계 : {}원'.format(format(tot_sum,',')))
Python
복사
 강사님 풀이
random.sample 이 아닌 random.randint(1,100)과 for문을 이용하면 100명의 1 ~ 100 사이의 age 를 만들어 낼 수 있다.
나이의 경우, 중복해서 샘플하는 것이 더 논리적으로 납득이 되기 때문이다.
import random visitors = [] for i in range(100): visitors.append(random.randint(1,100)) group1, group2, group3, group4, group5 = 0,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'영유아 : {group1}명 : {group1Price}원') print(f'어린이 : {group2}명 : {group2Price}원') print(f'청소년 : {group3}명 : {group3Price}원') print(f'성인 : {group4}명 : {group4Price}원') print(f'노인 : {group5}명 : {group5Price}원') print('-'*25) sum = group1Price + group2Price + group3Price + group4Price + group5Price print('1일 요금 총 합계 : {}'.format(format(sum, ',')))
Python
복사
Ex 4.
# 친구 이름 다섯명을 리스트에 저장하고 오름차순과 내림차순으로 정렬하자. friend = [] for i in range(5): # 5번 반복 friend.append(input('친구 이름 입력: ')) print('친구들 : {}'.format(friend)) friend.sort() print('오름차순 : {}'.format(friend)) friend.sort(reverse=True) print('내림차순 : {}'.format(friend))
Python
복사
Ex 5.
# 다음 리스트에서 중복 숫자를 제거하는 프로그램을 만들자. 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 # 인덱스 + 1 해주지 않는 이유는 현재 인덱스 값이 제거됐기 때문에 다음 값이 인덱스 + 1이 아니기 때문 idx += 1 print(f'중복 제거한 numbers : {numbers}')
Python
복사
Ex 6.
# 4개의 숫자 중 서로 다른 숫자 2개를 선택해서 만들 수 있는 모든 경우의 수를 출력하자. # 순서가 다르면 다른 값이기 때문에 , 순열이다. numbers = [4,6,7,9] results = [] # 일단, 순서가 다른 경우도 포함한 결과를 만든다. # 하지만, 이중 반복문을 활용하면 구할 수 있다. for n1 in numbers: for n2 in numbers: if n1 == n2: # 같다면 다음 값으로 continue results.append([n1,n2]) # 같지 않으면 두 조합의 리스트를 결과 리스트에 더하기 print(f'result : {results}') print(f'result length: {len(results)}')
Python
복사
# 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: # 앞의 n1이나 n2와 같을 경우에 다음 값으로 진행 continue result.append([n1,n2,n3]) print(f'result : {result}') print(f'result length : {len(result)}')
Python
복사
Ex 7.
# 대학생 길동이의 1,2,3학년 성적이 주어진다. 졸업할 때 4.0이상의 학점을 받기 위해 4학년 때 받아야 하는 # 1,2학기의 최소 학점을 구하자. scores = ((3.7,4.2),(2.9,4.3),(4.1,4.2)) # 3학년까지의 총학점 sum = 0 for score in scores: sum += score[0] + score[1] # 3학년 평균 : 소수점 1자리까지만 avg_3 = round(sum / 6 ,1) # 4학년때까지의 총학점이 32점 이상이 되어야 평균 4.0 으로 졸업할 수 있다. target_sum = round(32 - sum,1) avg_least = round(target_sum / 2,1) print(f'3학년 총학점 : {sum}') print(f'3학년 평균 : {avg_3}') print('-'*25) print(f'4학년 목표 총학점: {target_sum}') print(f'4학년 한학기 최소학점: {avg_least}') # 마지막으로 4학년 최소 학점까지 튜플 원소에 더해주고 출력 avg_4 = (avg_least,avg_least) print(avg_4) scores = scores + (avg_4,) print(f'scores : {scores}')
Python
복사
 강사님 코드와 차이점
# 1. 튜플 안의 튜플 원소들의 합을 구하는 과정 for score in scores: for s2 in score: # 이중 for 문을 활용해서 총합을 구하셨다. sum += s2 # 2. 튜플 원소로 추가하는 과정 # 나는 기존의 튜플에 튜플을 더하는 과정으로 값을 구했다면 # 강사님은 기존의 튜플을 리스트로 변경 후, 값을 추가한 뒤 다시 튜플로 변경해주는 과정으로 구하셨다. scores = list(scores) scores.append((avg_least,avg_least)) scores = tuple(scores)
Python
복사
Ex 8.
# 다음 두 개의 튜플에 대해서 합집합과 교집합을 출력하자. t1 = (1,3,2,6,12,5,7,8) t2 = (0,5,2,9,8,6,17,3) # 튜플의 경우, 변경에 제약이 따르기 때문에 리스트로 변경부터 하자. t1 = list(t1) t2 = list(t2) # 1. 합집합 : 중복되면 하나만 남긴다. # 두 리스트를 합친 다음, 중복된 값만 하나씩 남기면 된다. result = t1 + t2 idx = 0 while True: if idx >= len(result): break if result.count(result[idx]) >= 2: result.remove(result[idx]) continue idx += 1 result.sort() result = tuple(result) # 2. 교집합 : 두 튜플에 중복되는 원소들만 추출 result2 = [] for n1 in t1: for n2 in t2: if n1 == n2: result2.append(n1) result2.sort() result2 = tuple(result2) print(f'합집합(중복X) : {result}') print(f'교집합 : {result2}')
Python
복사
강사님 풀이
in / not in 키워드로 합집합 & 교집합을 구할 수 있다.
sort() 말고, sorted() 함수를 사용하면 튜플도 정렬할 수 있다.
하지만, 결과는 리스트로 나온다는 점 주의하자
# in / not in 키워드를 활용하면 해결됐다. t1 = (1,3,2,6,12,5,7,8) t2 = (0,5,2,9,8,6,17,3) tempHap = list(t1) tempGyo = [] # in / not in 키워드를 활용하면 교집합과 합집합을 한꺼번에 해결할 수 있다. for n in t2: if n not in tempHap: # 없다면 합집합으로 넣어주고 tempHap.append(n) else: # 있다면 교집합이니까 tempGyo 에 넣는다. tempGyo.append(n) tempHap = tuple(sorted(tempHap)) tempGyo = tuple(sorted (tempGyo)) print(f'합집합(중복X) : {tempHap}') print(f'교집합 : {tempGyo}')
Python
복사
t1 = (1,3,2,6,12,5,7,8) t2 = (0,5,2, ,8,6,17,3) tempHap = t1 + t2 # 튜플도 '+' 연산으로 더해질 수 있다. tempGyo = [] tempHap = list(tempHap) ########### 나의 코드와 다른 차이점 ############## # 합집합과 교집합을 while문 하나로 구현할 수 있다. idx = 0 while True: if idx >= len(tempHap): break if tempHap.count(tempHap[idx]) >= 2: tempGyo.append(tempHap[idx]) # 교집합에서는 더하고 tempHap.remove(tempHap[idx]) # 합집합에서는 빼면 continue idx += 1 tempHap = tuple(sorted(tempHap)) tempGyo = tuple(sorted(tempGyo)) print(f'합집합(중복X) : {tempHap}') print(f'교집합 : {tempGyo}')
Python
복사
Ex 9.
리스트또는 튜플.index(값) : 값에 해당하는 index 찾기
min(리스트 또는 튜플) / max(리스트 또는 튜플) : 최솟값과 최댓값 찾기
# 주어진 튜플을 요구 사항에 맞춰 슬라이싱 하자. numbers = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3) print(f'numbers[:4] : {numbers[:4]}') print(f'numbers[2:5] : {numbers[2:5]}') print(f'numbers[3:] : {numbers[3:]}') print(f'numbers[2:-1] : {numbers[2:-1]}') print(f'numbers[::3] : {numbers[::3]}')
Python
복사
Ex 10.
# 시험점수를 입력한 후 튜플에 저장하고 과목별 학점을 출력하자. 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 score in scores: for key in score.keys(): if score[key] >= 90: score[key] = 'A' elif score[key] >= 80: score[key] = 'B' elif score[key] >= 70: score[key] = 'C' elif score[key] >= 60: score[key] = 'D' else: score[key] = 'F' print(f'학점 : {scores}')
Python
복사
Ex 11. 다시 풀고 이해하기!!
딕셔너리 정렬하기
딕셔너리는 .sort() 나 sorted() 함수를 사용하지 못한다.
# 주어진 튜플의 과일의 개수에 대해 오름차순 , 내림차순으로 정렬하자. fruits = ({'수박':8}, {'포도':13}, {'참외':12}, {'사과':17}, {'자두':19}, {'자몽':15}) fruits = list(fruits) # 자유자재로 활용하기 위해 리스트로 변환 cIdx = 0; nIdx = 1 # 현재 index와 다음 Index 를 초기화 eIdx = len(fruits) - 1 # 마지막 index도 지정 -> 범위를 제한해주기 위해서 flag = True while flag: curDic = fruits[cIdx] # 튜플 원소에 먼저 접근 nextDic = fruits[nIdx] curDicCnt = list(curDic.values())[0] #딕셔너리 value값에 접근 nextDicCnt = list(nextDic.values())[0] if nextDicCnt < curDicCnt: # value 값끼리 대소 비교 , 오름차순 정렬 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))
Python
복사
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))
Python
복사
Ex 12.
# 학급별 학생수를 나타낸 튜플을 이용해서, 요구 사항에 맞는 데이터를 출력하는 프로그램을 만들자. studentCnt = ({'cls01':18}, {'cls02':21}, {'cls03':20}, {'cls04':19}, {'cls05':22}, {'cls06':20}, {'cls07':23}, {'cls08':17} ) studentCnt = list(studentCnt) tot = 0 min_cnt = 0; min_cls = '' max_cnt = 0; max_cls = '' deviation = [] for idx, dic in enumerate(studentCnt): for key, value in dic.items(): tot += value if min_cnt == 0 or min_cnt > value: min_cnt = value min_cls = key if max_cnt < value: max_cnt = value max_cls = key print(f'전체 학생 수 : {tot}') avgCnt = round(tot / len(studentCnt),1) print(f'평균 학생 수 : {avgCnt}') print(f'학생 수가 가장 적은 학급 : {min_cls}, 학생 수 : {min_cnt}') print(f'학생 수가 가장 많은 학급 : {max_cls}, 학생 수 : {max_cnt}') # 편차 구하기 for idx, dic in enumerate(studentCnt): for k, v in dic.items(): deviation.append(v - avgCnt) print(f'학급별 학생 편차: {deviation}')
Python
복사
Ex 13.
# 과목별 점수를 딕셔너리에 저장하고 출력하는 프로그램을 만들자. subject = ['국어','영어','수학','과학','국사'] scores = {} # 나중에 만들 딕셔너리 for s in subject: score = int(input(s + '점수 입력: ')) scores[s] = score print(f'과목별 점수 : {scores}')
Python
복사
EX 14.
# 사용자의 아이디, 비밀번호를 이용해서 로그인 프로그램을 만들자. # key, value 에 아이디, 비밀번호가 적혀져있는 딕셔너리를 만든 뒤 # id와 비밀번호를 입력받아서 해당하는 key값과 value값이 있는지 확인하면 된다. # in / not in 을 활용하면 된다.
Python
복사
Ex 15.
내각의 합 공식 : 180 * (내각 수 - 2)
# 삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램을 만들자. dic = {} # 내각의 합 : 180 * (내각수 - 2) for n in range(3,11): hap = 180 * (n-2) # 내각 합 # 한 내각의 크기 ang = int(hap / n) dic[n] = [hap,ang] print(dic)
Python
복사
Ex 16.
# 1부터 10까지 각각의 정수에 대한 약수를 저장하는 딕셔너리를 만들고 출력하는 프로그램 dic = {} for n in range(2,11): tempList = [] for j in range(1,n+1): # 1 ~ n 까지 약수 확인 if n % j == 0: tempList.append(j) dic[n] = tempList print(dic)
Python
복사
Ex 17.
문자열.split(구분값) :
문자열을 특정 구분값으로 구분하여 리스트로 반환
# 다음 문구를 공백으로 구분하여 리스트에 저장 후, 인덱스와 단어를 이용해서 딕셔너리에 저장하자. aboutPython = '파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어다.' tempList = aboutPython.split(' ') # 리스트로 반환된다 dic = {} for idx, v in enumerate(tempList): dic[idx] = v print(dic)
Python
복사
Ex 18.
문자열.replace(’바뀔문자’ , ’바꿀문자’)
# 주어진 문장에서 비속어를 찾아 표준어로 변경하는 프로그램을 만들자. words = { '꺼지다': '가다', '쩔다': '엄청나다', '짭새':'경찰관', '꼽사리':'중간에 낀 사람', '먹튀': '먹고 도망', '지린다': '겁을 먹다', '쪼개다':'웃다', '뒷담 까다':'험담하다' } st = '강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.' for key in words: if key in st: st = st.replace(key,words[key]) print(st)
Python
복사
Ex 19.
# 딕셔너리를 이용해서 5명의 회원을 입력받고 전체 회원정보를 출력하는 프로그램 id = [] pw = [] dic = {} for i in range(5): id.append(input('메일 입력: ')) pw.append(input('비밀번호 입력: ')) dic[id[i]] = pw[i] for i in dic: print(f'{i} : {dic[i]} ')
Python
복사
강사님 풀이
# 딕셔너리를 이용해서 5명의 회원을 입력받고 전체 회원정보를 출력하는 프로그램 dic = {} for i in range(5): mail = input('메일 입력: ') pw = input('비밀번호 입력: ') # 이미 있는 계정인지 확인해야 됨 if mail in dic: print('이미 사용 중인 계정입니다.') continue else: dic[mail] = pw n += 1 for key in dic.keys(): print(f'{key} : {dic[key]}')
Python
복사
# 딕셔너리를 이용해서 5명의 회원을 입력받고 전체 회원정보를 출력하는 프로그램 id = [] pw = [] dic = {} for i in range(5): id.append(input('메일 입력: ')) pw.append(input('비밀번호 입력: ')) dic[id[i]] = pw[i] while True: del_mail = input('삭제할 계정 입력: ') if del_mail not in dic: print('계정 확인 요망!') continue else: del_pw = input('비번 입력: ') if dic[del_mail] != del_pw: # 비번이 틀리면 print('비번 확인 요망!') continue else: del dic[del_mail] print(f'{del_mail}님 삭제완료!') break
Python
복사