3-1/Python 과제&실습

11주차-실습&과제

Donghun Kang 2024. 5. 21. 17:13

titanic.csv
0.03MB

import csv

with open('titanic.csv','r') as f:
    rdr = csv.reader(f)
    header = next(rdr)

    n_male = 0
    n_male_surv = 0
    n_female = 0
    n_female_surv = 0
    
    for line in rdr:
        if line[1] == 'male':
            n_male += 1
            if line[0] == '1':
                n_male_surv += 1
        else:
            n_female += 1
            if line[0] == '1':
                n_female_surv += 1

print(f'남성은 {n_male} 중 {n_male_surv} 생존하여 생존률 {(n_male_surv/n_male)*100:0.2f}% 입니다.')
print(f'여성은 {n_female} 중 {n_female_surv} 생존하여 생존률 {(n_female_surv/n_female)*100:0.2f}% 입니다.')
import csv

with open('titanic.csv','r') as f:
    rdr = csv.reader(f)
    header = next(rdr)

    n_First = 0
    n_First_surv = 0
    n_Second = 0
    n_Second_surv = 0
    n_Third = 0
    n_Third_surv = 0

    for line in rdr:
        if line[6] == 'First': 
            n_First += 1
            if line[0] == '1':
                n_First_surv += 1
        elif line[6] == 'Second':
            n_Second += 1
            if line[0] == '1':
                n_Second_surv += 1
        else:
            n_Third += 1
            if line[0] == '1':
                n_Third_surv += 1
                
print(f'First는 {n_First} 중 {n_First_surv} 생존하여 생존률 {(n_First_surv/n_First)*100:0.2f}% 입니다.')
print(f'Second는 {n_Second} 중 {n_Second_surv} 생존하여 생존률 {(n_Second_surv/n_Second)*100:0.2f}% 입니다.')
print(f'Third는 {n_Third} 중 {n_Third_surv} 생존하여 생존률 {(n_Third_surv/n_Third)*100:0.2f}% 입니다.')

 

Image 파일 읽기

apple.jpg
0.04MB

from PIL import Image

im = Image.open('apple.jpg')
im.show()

bird_names.txt
0.05MB

def calculate_bird_percentages(file_path):
    with open(file_path, 'r') as file:
        bird_names = file.read().strip().split('\n')
    
    bird_count = {}
    total_count = len(bird_names)
    
    for bird in bird_names:
        if bird in bird_count:
            bird_count[bird] += 1
        else:
            bird_count[bird] = 1
    
    bird_percentages = {bird: round(count / total_count, 3) for bird, count in bird_count.items()}
    
    for bird in sorted(bird_percentages):
        print(f"{bird} {bird_percentages[bird]:.3f}")

file_path = 'bird_names.txt'
calculate_bird_percentages(file_path)

'3-1 > Python 과제&실습' 카테고리의 다른 글

13주차-실습&과제  (0) 2024.06.13
12주차-실습&과제  (1) 2024.05.31
10주차-실습&과제  (0) 2024.05.21
9주차-실습&과제  (0) 2024.05.21
7주차-실습&과제  (0) 2024.05.21