연습문제1
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)
for n2 in range(2,inputNum+1):
flag = True
for n in range(2, n2):
if n2 % n ==0:
flag = False
#1과 자기자신 외에 나누어떨어지는 수가 있다면 소수가 아니므로 False
# (ex n2가 10라면 n은 2~9가 들어가서 for문이 돌아감)
break
if flag:
listB.append(n2)
print(inputNum,'의 약수 : {}'.format(listA))
print(inputNum,'까지의 소수 : {}'.format(listB))
연습문제02
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(randomList)
print(f'짝수 : {evens}, 개수 : {len(evens)}개')
print(f'홀수 : {odds}, 개수 : {len(odds)}개')
연습문제03
1일 총입장객 100명 / 1일 전체입장 요금 구하기
0~7세:무료 / 8~13세: 200 / 14~19세: 300 / 20~64세: 500 / 65세 이상 : 무료
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
elif age >= 65:
group5 +=1
group1Price = group1 * 0
group2Price = group2 * 200
group3Price = group3 * 300
group4Price = group4 * 500
group5Price = group5 * 0
sum = group1Price + group2Price +group3Price + group4Price + group5Price
print('*' * 25)
print(f'영유아 : {group1}명 / {group1Price}원')
print(f'어린이 : {group2}명 / {group2Price}원')
print(f'청소년 : {group3}명 / {group3Price}원')
print(f'성인 : {group4}명 / {group4Price}원')
print(f'어르신 : {group5}명 / {group5Price}원')
print(f'1일 요금 총합계 : {sum}원')
print('*' * 25)
연습문제04
친구 이름 다섯명 저장, 오름차, 내림차 정렬
중복아이템 제거
numbers = [2,22,7,8,9,2,7,3,5,2,7,1,3]
print(numbers)
idx = 0
while True:
if idx >= len(numbers):
break
if numbers.count(numbers[idx]) >=2: #idx 자리에 있는 데이터의 갯수가 2개 이상(중복이라면)
numbers.remove(numbers[idx]) #ex)idx가 0인 경우, numbers[idx]는 2, 리스트에서 2의 갯수는 3개
continue
idx +=1
print(f'numbers : {numbers}')
연습문제04
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}')
#순열공식 사용 가능 n!/(n-r)! n개 중 r개 택하는 경우
import math
pernutation = math.factorial(len(numbers))/ math.factorial(len(numbers)-2)
print(int(pernutation))