문제1
문자열을 입력 받아 각 단어가 몇 번 등장했는지 계산하는 word_frequency 함수를 작성하세요.
- 조건: 빈 문자열 인 경우 "입력한 문자열이 없습니다."를 반환해주세요.
- 힌트:
- 문자열을 split() 메서드로 나눌 수 있습니다.
- 딕셔너리를 사용해 단어 빈도를 계산하세요.
- skeleton code
def word_frequency(text):
"""
여기에 코드를 작성하세요.
"""
# 테스트 1
text1 = "hello world hello python world"
print(word_frequency(text1))
# 테스트 2
text2 = ""
print(word_frequency(text2))
- 출력 결과
'''
{'hello': 2, 'world': 2, 'python': 1}
입력한 문자열이 없습니다.
'''
`문제 풀이`
def word_frequency(text):
if not text:
print('입력한 문자열이 없습니다.')
text_list = text.split()
frequency = {}
for i in text_list:
if i in frequency:
frequency[i] += 1
else:
frequency[i] = 1
print(frequency)
text1 = "hello world hello python world"
word_frequency(text1)
`오답노트`
- 딕셔너리 형태로 새로 만드는거 기억이 안나서 빈도 부분을 못 구했다
- .split(' ') 안 하고 그냥 .split() 해도 됨
- if text == '': 안 하고 그냥 if not text: 해도 됨
문제2
Seaborn 라이브러리에서 제공하는 Penguins 데이터셋을 활용하여 다음을 수행하세요:
- 조건 1) 데이터 null값을 확인하고, 모든 칼럼에서 null값을 삭제하세요.
- 조건 2) 선택된 데이터에서 species, sex, bill_length_mm, bill_depth_mm 열만 추출하세요.
- 조건 3) species가 "Adelie"이면서 bill_length_mm이 40 이상이거나, species가 "Chinstrap"이면서 bill_length_mm이 30 이하인 데이터를 선택하세요.
final_result 데이터 프레임에 저장하고, shape을 출력하세요.
- skeleton code
import seaborn as sns
# Penguins 데이터셋 로드
penguins = sns.load_dataset("penguins")
'''
여기에 코드를 작성하세요
'''
print(final_result.shape)
- 출력 결과
'''
(50, 4)
'''
`문제 풀이`
import seaborn as sns
# Penguins 데이터셋 로드
penguins = sns.load_dataset("penguins")
penguins
# 조건1
penguins1 = penguins.dropna()
# 조건2
penguins2 = penguins1[['species', 'sex', 'bill_length_mm', 'bill_depth_mm']]
# 조건3
condition1 = (penguins2['species']== 'Adelie') & (penguins2['bill_length_mm'] >= 40)
condition2 = (penguins2['species']=='Chinstrap') & (penguins2['bill_length_mm'] <= 30)
final_result = penguins2[condition1|condition2]
print(final_result.shape)
`오답노트`
- 틀린 건 아니지만, 매번 새로운 변수(ex.penguins1,2)에 안 담고 inplace=True로 해도 됨