💥 CODEKATA
~ 80문제
SQL
77문제부터 영어인데 번역하기 넘 힘들어여 . . ...................
풀기 시룸............
드랍할지두............
판다스 넘 재미없다
파이썬 문제만 풀고 싶다
torr......
▶ 파이썬 숙제 ~ 24번까지
더보기
더보기
# #숙제1
# #Hello World를 5번 출력
for i in range(5):
print("Hello World")
# #숙제2
# #1부터 44까지 짝수만 출력
# % 2 == 0, % 1 == 0 다 해보기
for i in range(1,45):
if i % 1 == 0 and i % 2 == 0:
print(i)
# #숙제3
# #1부터 44까지 짝수는 * 4, 홀수 그냥 출력
for i in range(1,45):
if i % 2 == 0:
print(i*4)
else:
print(i)
# #숙제4
# #Hello World 4번 출력
for i in range(4):
print("Hello World")
# #숙제5
# #numbers = [1, 2, 3, 4, 5]
# #순회를 돌아 numbers 요소 출력
numbers = [1, 2, 3, 4, 5]
for i in numbers:
print(i)
# #숙제6
# #1부터 4까지 합 계산
total = 0
for i in range(1,5):
total += i
print(total)
# #숙제7
# #사용자가 입력한 숫자의 구구단을 출력 (input)
# #예시)
# #입력값 : 3
# #아래는 출력 값
# #3 * 1 = 3
# #3 * 2 = 6
# #3 * 3 = 9
# #...
while True:
scoreavg_num = input("입력값 : ")
try:
num = int(scoreavg_num)
for i in range(1, 10):
print(f"{num} * {i} = {num * i}")
break
except:
print("입력값이 숫자가 아닙니다")
#숙제8 (어려움 모르면 패스)
#피보나치 수열에서 14개만 출력
#a, b = 1, 1
#for문
#출력
#숙제9
#numbers = [11, 22, 33, 44, 55]
#target = 44
#found = False
#44를 찾을 시 찾았다라고 print로 출력
numbers = [11, 22, 33, 44, 55]
target = 44
found = False
for i in numbers:
if i == target:
print(f"target => {i} 찾았다 !")
break
else:
print(f"{i} => {found}")
#숙제10
#1부터 100까지 3과 7의 배수만 출력
for i in range(1,101):
if i % 3 == 0 and i % 7 == 0:
print(i)
#숙제11
#numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#홀수만 새로운 리스트에 추가
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
mylist = []
for i in numbers:
if i % 2 != 0:
mylist.append(i)
print(mylist)
#숙제12
#사용자가 입력한 숫자를 받아, 팩토리얼 계산
while True:
try:
scoreavg_num = int(input("숫자를 입력하세요 >>> "))
total = 1
for i in range(scoreavg_num, 0, -1):
print(f"{i} * {total} = {i * total}")
total = i * total
break
except:
print("숫자만 입력하세요.")
#숙제13
#아래 리스트에서 최솟값과 최댓값 찾기
#numbers = [44, 12, 35, 96, 46, 87, 2, 63]
numbers = [44, 12, 35, 96, 46, 87, 2, 63]
print(f"최댓값 : {max(numbers)}\n최솟값 : {min(numbers)}")
#숙제14
#아래 리스트의 요소를 뒤에서부터 출력
#numbers = [44, 12, 35, 96, 46, 87, 2, 63]
numbers = [44, 12, 35, 96, 46, 87, 2, 63]
numbers.reverse()
for i in numbers:
print(i)
#숙제15
#회문(palindrome)일 경우 회문입니다 출력, 아닐 경우 아님 출력
#회문 예: 토마토, 구로구, ....등등
#hint: 인덱싱?????
scoreavg = list(input("회문일까요? >>> "))
if scoreavg[0] == scoreavg[len(scoreavg)-1]:
print("회문입니다.")
else:
print("회문이 아닙니다.")
#숙제16
#사용자의 입력을 숫자를 입력 받아, 0, 양수, 음수 판별
while True:
try:
scoreavg = int(input("숫자를 입력하세요 >>> "))
if scoreavg > 0:
print("양수")
elif scoreavg < 0:
print("음수")
else:
print("0")
break
except:
print("숫자가 아닙니다")
#숙제17
#사용자에게 3개의 숫자를 받고, 그 중 가장 큰 수 출력
while True:
try:
scoreavg = list(map(int, input("3개의 숫자를 입력하세요 (띄어쓰기로 구별) >>> ").split()))
print(f"가장 큰 수 : {max(scoreavg)}")
break
except:
print("정확하게 입력하세요.")
#숙제18
#사용자에게 요일을 받고, 그 요일이 주말이면 주말입니다로 출력
scoreavg = list(input("요일을 입력하세요 >>> "))
if scoreavg[0] in ("토", "일"):
print("주말입니다.")
else:
print("주말 x")
#숙제19
#0부터 100사이의 점수를 받아 학점 출력
#90이상 A
#80이상 B
#70이상 C
#60이상 D
#60미만 F
while True:
try:
scoreavg = int(input("점수를 입력하세요 (0~100) >>> "))
if scoreavg >= 90:
print("A")
elif scoreavg >= 80:
print("B")
elif scoreavg >= 70:
print("C")
elif scoreavg >= 60:
print("D")
elif 0 <= scoreavg < 60:
print("F")
else:
print("올바른 점수를 입력하세요.")
continue
break
except:
print("올바른 점수를 입력하세요.")
#숙제20
#숙제19와 동일 but 조건 추가
#만약에 100초과의 점수를 받을 경우, 바보라고 출력
while True:
try:
scoreavg = int(input("점수를 입력하세요 (0~100) >>> "))
if scoreavg > 100:
print("바보")
elif scoreavg >= 90:
print("A")
elif scoreavg >= 80:
print("B")
elif scoreavg >= 70:
print("C")
elif scoreavg >= 60:
print("D")
elif 0 <= scoreavg < 60:
print("F")
else:
print("올바른 점수를 입력하세요.")
continue
break
except:
print("올바른 점수를 입력하세요.")
#숙제21
#숙제20와 동일 but 조건 추가
#만약에 100초과의 점수를 받을 경우 바보라고 출력, 0미만일 경우 멍청이라고 출력
while True:
try:
scoreavg = int(input("점수를 입력하세요 (0~100) >>> "))
if scoreavg > 100:
print("바보")
elif scoreavg >= 90:
print("A")
elif scoreavg >= 80:
print("B")
elif scoreavg >= 70:
print("C")
elif scoreavg >= 60:
print("D")
elif 0 <= scoreavg < 60:
print("F")
else:
print("멍청이")
break
except:
print("올바른 점수를 입력하세요.")
#숙제22
#id = admin
#password = 1234
#로그인 성공 시, 로그인 성공 출력
#로그인 실패 시, 로그인 실패 출력
scoreavg_id = input("id를 입력하세요 >>> ")
scoreavg_pw = int(input("비밀번호를 입력하세요 >>> "))
id = "admin"
password = 1234
if scoreavg_id == id and scoreavg_pw == password:
print("로그인 성공")
else:
print("로그인 실패")
#숙제23
#사용자에게 3개의 숫자를 받아, 오름차순 정렬하여 출력
while True:
try:
scoreavg = list(map(int, input("3개의 숫자를 입력하세요 (띄어쓰기로 구별) >>> ").split()))
scoreavg.sort()
for i in scoreavg:
print(i, end=' ')
break
except:
print("정확하게 입력하세요.")
#숙제24
#숙제21과 동일 but 조건 추가
#5개의 숫자를 받은 뒤 그 평균을 구하고, 그에 따른 등급 출력
while True:
try:
user = list(map(int, input("5개의 숫자를 입력하세요 (띄어쓰기로 구별) >>> ").split()))
scoreavg = round(sum(user) / len(user), 1)
print(scoreavg)
if scoreavg > 100:
print("바보")
elif scoreavg >= 90:
print("A")
elif scoreavg >= 80:
print("B")
elif scoreavg >= 70:
print("C")
elif scoreavg >= 60:
print("D")
elif 0 <= scoreavg < 60:
print("F")
else:
print("멍청이")
break
except:
print("정확하게 입력하세요.")
▶ 파이썬 숙제 ~32번까지
더보기
더보기
# 숙제 - 25
# number = [1, 4, 4, 4, 4, 4, 4]에 중복 제거 해주세요
number = [1, 4, 4, 4, 4, 4, 4]
number_set = set(number)
print(number_set)
# 숙제 - 26
# number = [1, 4, 4, 4, 4, 4, 4, 5]에서 5 제거 후 출력해주세요
number = [1, 4, 4, 4, 4, 4, 4, 5]
number.pop(-1)
print(number)
# 숙제 - 27
# number = [1, 2, 3, 4, 5]에서 3 제거 후 나머지 요소의 평균 값 구해주세요
idx = 0
for i in number:
if i == 3:
print(idx)
break
idx += 1
del number[idx]
avgnum = round(sum(number) / len(number))
print(avgnum)
# 숙제 - 28
# number = [1, 2, 3, 4, 5]에서 뒤의 3개만 출력해주세요 후 귀차나 슬슬
number = [1, 2, 3, 4, 5]
for i in number[:1:-1]:
print(i)
# 숙제 - 29
# number = [1, 4, 4, 4, 4, 4, 4, 5]에서 중복된 요소의 개수 출력
number = [1, 4, 4, 4, 4, 4, 4, 5]
remo = set(number)
cnt = len(number) - len(remo) + 1
print(f"중복된 요소의 개수 {cnt}개")
# 숙제 - 30
# number = [1, 4, 4, 4, 4, 4, 4. 5]에서 요소 4의 위치(인덱스)를 출력하세요
number = [1, 4, 4, 4, 4, 4, 4, 5]
for i in range(0, len(number)-1):
if number[i] == 4:
print("index : ", i)
# 숙제 - 31
# list_1 = [1, 2, 3]
# list_2 = [4, 5, 6]
# 위의 두개의 리스트를 하나로 합쳐주세요
list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
listall = list_1 + list_2
print(listall)
🔰 과제
▶ 개인 과제 - 필수
더보기
더보기
- **문제 1 : 데이터 로딩 & 구조 확인하기**
### **문제 설명**
CSV를 DataFrame으로 로드한 뒤 구조를 빠르게 진단합니다. 분석의 첫 단계입니다.
### **필요 지식**
`pd.read_csv`, `DataFrame.shape`, `DataFrame.info`, `DataFrame.head`
### **지시 사항**
1. `StudentsPerformance.csv`를 DataFrame으로 로드
2. 행·열 수와 컬럼별 dtype/info 출력
3. 상위 5행 출력
### **시각화 요구**
(없음)
### **채점 포인트**
- 파일 로딩 코드 정확성
- `.shape`, `.info()`, `.head()` 출력 여부
###############################################################################
import pandas as pd
df = pd.read_csv("StudentsPerformance.csv")
print(df.shape)
print(df.info())
print(df.head())
**문제 2 : 결측치 & 중복 점검하기 **
### **문제 설명**
데이터 품질 확인을 위해 결측치와 중복 행을 점검합니다.
### **필요 지식**
`DataFrame.isna().sum`, `DataFrame.duplicated`, `DataFrame.drop_duplicates`
### **지시 사항**
1. 컬럼별 결측치 개수 출력
2. 중복 행 개수 출력
3. 중복 제거 후 현재 행 수 출력
### **시각화 요구**
(없음)
### **채점 포인트**
- 결측/중복 점검 코드 유무
- 중복 제거 후 변화 확인
###############################################################################
import pandas as pd
df = pd.read_csv("StudentsPerformance.csv")
print(df.isna().sum())
print(df.duplicated().sum())
df.drop_duplicates(inplace=True)
print(df.shape)
- **문제 3 : 단일 히스토그램 - 수학 점수 분포 확인하기**
### **문제 설명**
수학 점수 컬럼의 분포 모양을 히스토그램으로 확인합니다.
### **필요 지식**
`plt.hist` 또는 `Series.hist`, bin 개수 설정, 축 라벨/제목
### **지시 사항**
1. `math score`에 대해 **bins=20**으로 히스토그램
2. 제목/축 라벨 설정
### **시각화 요구**
- 단일 히스토그램 1개
- 보기 좋게 `tight_layout()`
- 예상 결과
### **채점 포인트**
- bin 수 적용
- 제목/축 라벨 명시
- 단일 그래프 사용
###############################################################################
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("StudentsPerformance.csv")
plt.hist(df["math score"], bins=20)
plt.xlabel("math score")
plt.ylabel("count")
plt.title("Histogram - Math Score")
plt.tight_layout()
plt.show()
- **문제 4 : 세 과목 모두 80점 이상 → 성별 분포 단일 막대그래프로 나타내기**
### **문제 설명**
고득점자 집단(세 과목 모두 80점 이상)을 추출해 성별 분포를 확인합니다.
### **필요 지식**
다중 조건 마스크, `Series.value_counts`, 단일 막대그래프
### **지시 사항**
1. `math score` ≥ 80 & `reading score` ≥ 80 & `writing score` ≥ 80 필터
2. 필터 결과의 `gender` 빈도 출력
3. 빈도를 **단일 막대그래프**로 시각화
### **시각화 요구**
- 한 그림에 성별 2막대
- 제목/축 라벨 설정
- 예상 결과
### **채점 포인트**
- 다중 조건 정확성
- `value_counts()` 활용
- 단일 그래프 사용
###############################################################################
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("StudentsPerformance.csv")
cond = (df["math score"] >= 80) & (df["reading score"] >= 80) & (df["writing score"] >= 80)
result = df[cond].value_counts(subset="gender")
print(result)
plt.bar(result.index, result)
plt.xlabel("gender")
plt.ylabel("count")
plt.title("High Achievers (>=80 in all) by Gender")
plt.show()
# 원래는 groupby 로 풀었었음. 정답에 value_counts 쓰라고 해서 바꿈
# df = pd.read_csv("StudentsPerformance.csv")
# cond = (df["math score"] >= 80) & (df["reading score"] >= 80) & (df["writing score"] >= 80)
# result = df[cond].groupby(["gender"])["gender"].count()
# result.index
# plt.bar(result.index, result)
# plt.xlabel("gender")
# plt.ylabel("count")
# plt.title("High Achievers (>=80 in all) by Gender")
# plt.show()
- **문제 5 : 시험 준비 완료 & 일반 점심의 평균 점수를 막대그래프로 나타내기**
### **문제 설명**
두 조건을 동시에 만족하는 학생만 추출해, 세 과목 평균을 비교합니다.
### **필요 지식**
불리언 마스크(`&`), `DataFrame.loc`, `DataFrame.mean`, 반올림(`Series.round`), 단일 막대 그래프
### **지시 사항**
1. **AND** 필터를 사용해서 조건 결합
2. `math/reading/writing score` 평균을 **소수점 1자리**로 출력
3. 평균 3개를 **단일 막대그래프**로 시각화(한 그림)
### **시각화 요구**
- 한 그림에 막대 3개
- 제목/축 라벨 설정, y축 [0,100] 권장 → `plt.ylim`
- 예상 결과
### **채점 포인트**
- 조건 결합(AND) 정확성
- 평균/반올림 적용
- 단일 그래프 사용
###############################################################################
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("StudentsPerformance.csv")
cond = (df["test preparation course"] == "completed") & (df["lunch"] == "standard")
df[cond]
cond_avg = round(df[cond][["math score", "reading score", "writing score"]].mean(), 1)
print(cond_avg)
cond_avg.index
plt.bar(cond_avg.index, cond_avg, width=0.5)
plt.xticks(rotation=90)
plt.ylim(0,100)
plt.ylabel("score")
plt.title("Avg scores (prep=completed & lunch=standard)")
plt.show()
- **문제 6 : 부모 학력별 수학 평균 단일 산점도로 나타내기**
### **문제 설명**
범주형 변수 **부모 학력별**을 나타내는 컬럼별 **수학 점수 평균**을 계산해, **단일 산점도**로 평균값을 비교해 보세요.
평균이 높은 순으로 **정렬된 카테고리 순서**로 표시하면, 어떤 학력군에서 수학 평균이 높은지 한눈에 볼 수 있습니다.
> 참고: 범주 간 연결선은 의미가 불분명할 수 있어 점만 표시합니다(선 연결 X).
>
### **필요 지식**
- `groupby(...).mean()`로 범주별 평균 계산
- `Series.sort_values()`로 내림차순 정렬
- **Seaborn `scatterplot`** 또는 **Matplotlib `plt.scatter`** 기본 사용
- 축 레이블, 제목, x축 라벨 회전, `ylim` 등 기본 서식
### **지시 사항**
1. `parental level of education`별 평균 `math score`를 계산하고 **소수점 1자리**로 반올림해 표로 출력하세요.
2. 평균값을 **내림차순**으로 정렬한 **카테고리 순서(order)**를 만드세요.
3. 단일 그래프(1개)로 **산점도**를 그리세요.
- x축: `parental level of education` (정렬된 순서 적용)
- y축: `math score`의 평균
- **점만 표시**(선 연결 X)
- 제목/축 라벨 지정, x축 라벨 회전(예: 30°)
- y축 범위는 `0~100` 권장
### **시각화 요구**
- 그래프 **1개** (서브플롯/여러 차트 금지)
- 루프(`for p in ax.patches:` 등) 사용 금지
- 제목/축 라벨/라벨 회전/축 범위 정리
- 예상 결과
### **채점 포인트**
- 평균 계산 및 **내림차순 정렬**이 정확한가?
- 산점도에 **정렬된 order**가 반영되었는가?
- 단일 그래프 요건을 지켰는가? (선 연결 없음)
- 기본 서식(제목/축 라벨/회전/축 범위)을 적용했는가?
###############################################################################
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("StudentsPerformance.csv")
avg_math = round(df.groupby(["parental level of education"])["math score"].mean(), 1)
order = avg_math.sort_values(ascending=False)
plt.scatter(order.index, order)
plt.xticks(rotation=30)
plt.ylim(0,100)
plt.xlabel("Parental Education")
plt.ylabel("Mean Math Score")
plt.title("Mean Math Score by Parental Education (Scatter)")
plt.show()
▶ 개인 과제 - 도전
더보기
더보기
- **문제 7 : 부모 학력 수준별 고득점 비율(%) 계산 & 단일 막대그래프로 나타내기**
### **문제 설명**
세 과목(수학, 읽기, 쓰기)이 **모두 80점 이상**인 “고득점자” 비율을 **부모 학력 수준별**로 계산해 비교합니다.
단순 평균이 아니라 비율(= 고득점자 수 / 전체 수 × 100)을 계산해야 하므로, 그룹별 분모·분자를 정확히 맞춰 계산하는 것이 핵심입니다.
### **필요 지식**
- 불리언 필터(다중 조건 AND)
- `groupby(...).size()`로 **그룹별 건수** 계산
- 인덱스 정렬·정렬 순서 유지(`reindex`)
- `Series` 간 연산으로 **비율** 계산, `fillna(0)`, 반올림
- 단일 **bar plot** (Matplotlib 또는 pandas `.plot(kind='bar')`)
### **지시 사항**
1. “고득점자” 필터: 세 과목이 모두 **≥ 80**
2. 부모 학력 수준별 **전체 학생 수**(분모)와 **고득점자 수**(분자) 계산
3. **비율(%)** = (분자 / 분모) × 100 → **소수점 1자리** 반올림
4. **내림차순**으로 정렬 후 **단일 막대그래프** 1개로 시각화 (y축 0~100 권장)
### **시각화 요구**
- 그래프 1개(서브플롯 X)
- 제목/축 라벨 설정, x라벨 회전(필요 시)
- 예상 결과
### **채점 포인트**
- 분모/분자 계산을 **같은 그룹 축**으로 정확히 맞췄는가?
- 결측 그룹을 `fillna(0)` 등으로 적절히 처리했는가?
- 비율(%)을 소수점 1자리로 명시했는가?
- 단일 그래프 요건과 기본 서식을 지켰는가?
###############################################################################
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("StudentsPerformance.csv")
cond = (df["math score"] >= 80) & (df["reading score"] >= 80) & (df["writing score"] >= 80)
cond2 = df[cond].groupby(["parental level of education"])["parental level of education"].count()
cond2_normal = df.groupby(["parental level of education"])["parental level of education"].count()
result = round((cond2 / cond2_normal) * 100, 1)
result = result.sort_values(ascending=False)
plt.bar(result.index, result, width=0.6)
plt.xticks(rotation=30)
plt.ylim(0,100)
plt.xlabel("parental level of education")
plt.ylabel("percentage(%)")
plt.title("High Achiever Rate (>=80 in all) by Parental Education [%]")
plt.show()
- **문제 8 : 인종/민족 그룹별 읽기 점수 분포 비교(바이올린 플롯)**
### **문제 설명**
각 컬럼 그룹에서 **읽기 점수(`reading score`)의 분포**를 비교하세요.
막대 대신 **바이올린 플롯**을 사용하여, 그룹별 **중앙값과 사분위 범위**를 한눈에 확인하고, **중앙값이 가장 높은 그룹**을 코드로 찾아 출력합니다.
(*바이올린 플롯은 분포의 모양까지 보여주기 때문에 상위권/하위권이 어디에 몰려 있는지 파악하기 쉽습니다.*)
### **필요 지식**
- `groupby(...).median()`로 그룹별 **중앙값** 계산
- `Series.sort_values()`로 **내림차순 정렬** 및 순서 지정
- **Seaborn `violinplot`** 기본 사용법 (`inner='quartile'` 권장)
- 단일 그래프 기본 서식: 제목/축 라벨/눈금 회전/축 범위
### **지시 사항**
1. `race/ethnicity`별 **reading score 중앙값**을 계산해 **소수점 1자리**로 반올림하고, **내림차순**으로 정렬해 표로 출력하세요.
2. 위 정렬 순서를 `violinplot`의 **order**로 적용해 **단일 그래프** 1개를 그리세요.
- x축: `race/ethnicity` (정렬된 순서)
- y축: `reading score`
- `inner='quartile'`로 중앙값/사분위선을 표시
- 제목/축 라벨/라벨 회전(필요 시), y축 범위 `0~100` 권장
3. **중앙값이 가장 높은 그룹명**을 코드로 출력하세요.
### **시각화 요구**
- 그래프 **1개**(서브플롯 금지)
- 루프(`for p in ax.patches:` 등) 사용 금지
- 제목/축 라벨/라벨 회전/축 범위 정리
- 예상 결과
###############################################################################
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("StudentsPerformance.csv")
gb = round(df.groupby(["race/ethnicity"])["reading score"].median(), 1)
gbsort = gb.sort_values(ascending=False)
sortindex = gbsort.index.tolist()
print(result)
print(f"Top group by median reading score : {gbsort.idxmax()} ({gbsort.max()})" )
sns.violinplot(x="race/ethnicity", y="reading score", data=df, order=sortindex, inner="quartile")
plt.xticks(rotation=20)
plt.ylim(0, 140)
plt.title("'Reading Score Distribution by Rade/Ethnicity (Violin, ordered by median)")
plt.show()
'Sparta > CODEKATA' 카테고리의 다른 글
| [250904] 스파르타코딩 본캠프 23일차 (0) | 2025.09.04 |
|---|---|
| [250903] 스파르타코딩 본캠프 22일차 (0) | 2025.09.03 |
| [250901] 스파르타코딩 본캠프 20일차 (2) (0) | 2025.09.01 |
| [250829] 스파르타코딩 본캠프 19일차 (2) - QCC (2) | 2025.08.29 |
| [250828] 스파르타코딩 본캠프 18일차 (2) (1) | 2025.08.28 |