python 기초 #4

이용·2021년 7월 13일
0

python

목록 보기
4/5

24. 문자열 & 리스트 문제

06. 주민등록번호 가리기

주민등록번호 YYMMDD-abcdefg는 총 열세 자리인데요.
주민등록번호의 마지막 네 자리 defg만 가려 주는 보안 프로그램을 만들려고 합니다.
mask_security_number라는 함수를 정의하려고 하는데요. 이 함수는 파라미터로 문자열 security_number를 받고, security_number의 마지막 네 글자를 ''로 대체한 새 문자열을 리턴합니다.
참고로 파라미터 security_number에는 작대기 기호(-)가 포함될 수도 있고, 포함되지 않을 수도 있는데요. 작대기 포함 여부와 상관 없이, 마지막 네 글자가 '
'로 대체되어야 합니다!

#접근법 #1
def mask_security_number(security_number):
    # security_number를 리스트로 변환
    num_list = list(security_number)

    # 마지막 네 값을 *로 대체
    for i in range(len(num_list) - 4, len(num_list)):
        num_list[i] = "*"

    # 리스트를 문자열로 복구
    total_str = ""
    for i in range(len(num_list)):
        total_str += num_list[i]

    return total_str

-------------------------------------------
# 접근법 #2
# join() method 사용 -> 문자열로 이루어진 리스트를 구분자로 결합, 하나의 문자열로 만듬
def mask_security_number(security_number):
    num_list = list(security_number)

    # 마지막 네 값을 *로 대체
    for i in range(len(num_list) - 4, len(num_list)):
        num_list[i] = '*'

    # 리스트를 문자열로 복구하여 반환
    return ''.join(num_list)
--------------------------------------------
# 접근법 #3
# 문자열 슬라이싱
def mask_security_number(security_number):
    return security_number[:-4] + '****'

07. 팰린드롬

팰린드롬 여부를 확인하는 함수 is_palindrome을 작성하려고 하는데요. is_palindrome은 파라미터 word가 팰린드롬이면 True를 리턴하고 팰린드롬이 아니면 False를 리턴합니다.

예를 들어서 "racecar""토마토"는 거꾸로 읽어도 똑같기 때문에 True가 출력되어야 합니다. 그리고 "hello"는 거꾸로 읽으면 "olleh"가 되기 때문에 False가 나와야 하는 거죠.

def is_palindrome(word):
    for left in range(len(word) // 2):
        # 한 쌍이라도 일치하지 않으면 바로 False를 리턴하고 함수를 끝냄
        right = len(word) - left - 1
        if word[left] != word[right]:
            return False

    # for문에서 나왔다면 모든 쌍이 일치
    return True
-----------------------------------------------
// 문자열 & 리스트 뒤집기
def is_palindrome(word):
    return word == word[::-1]

25. Module

1) 함수 파일 불러오기

import moduleFileName or import moduleFileName as nickname

ex) import numpy as np import pandas as pd

muduleFileName.function()

2) 함수 파일 내 특정 함수 불러오기

from moduleFileName import function1, function2 or

from moduleFileName import * (출처가 불분명하여 사용 자제)

3) Standard library

import math import os

random 모듈

import random

1. randint 함수

randint : 두 수 사이의 어떤 랜덤한 정수를 리턴하는 함수.

randint(a, b) ⇒ a ≤ N ≤ b 만족하는 어떤 랜덤한 정수 N을 리턴.

2. uniform 함수

uniform: 두 수 사이의 랜덤한 소수를 리턴하는 함수. randint와 달리 리턴하는 값이 정수가 아닌 소수.

uniform(a, b) a ≤ N ≤ b 만족하는 어떤 랜덤한 소수 N을 리턴.

datetime 모듈

import datetime '날짜'와 '시간'을 다루기 위한 다양한 '클래스'를 갖추고 있다.

ex)

pi_day = datetime.datetime(2020, 3, 14, 13, 6, 15)
print(pi_day)
print(type(pi_day))
>>>
2020-03-14 13:06:15
<class 'datetime.datetime'>

오늘 날짜
today = datetime.datetime.now()
print(today)
print(type(today))

timedelta

datetime 값 사이의 기간

today = datetime.datetime.now()
pi_day = datetime.datetime(2020, 3, 14, 13, 6, 15)
print(today - pi_day)
print(type(today - pi_day))
>>>
22 days, 4:42:57.360266
<class 'datetime.timedelta'>

or 더할 수도 있음

today = datetime.datetime.now()
my_timedelta = datetime.timedelta(days=5, hours=3, minutes=10, seconds=50)

print(today)
print(today + my_timedelta)
>>>
2020-04-05 17:54:24.221660
2020-04-10 21:05:14.221660

datetime에서 특정 값 추출

today = datetime.datetime.now()

print(today)
print(today.year)  # 연도
print(today.month)  # 월
print(today.day)  # 일
print(today.hour)  # 시
print(today.minute)  # 분
print(today.second)  # 초
print(today.microsecond)  # 마이크로초

datetime 포맷팅

today = datetime.datetime.now()

print(today)
print(today.strftime("%A, %B %dth %Y"))
>>>
2020-04-05 18:09:55.233501
Sunday, April 05th 2020

포맷코드


26. Input & random 숫자 맞히기 게임

import random

# 코드를 작성하세요.
correct_answer = random.randint(1, 20)
chance = 4
attempt = 0
user_answer = -1
while user_answer != correct_answer and attempt < chance:
    user_answer = int(input("기회가 {}번 남았습니다. 1-20 사이의 숫자를 맞혀 보세요: ".format(chance-attempt)))
    attempt += 1

    if user_answer > correct_answer:
        print("Down")
    elif user_answer < correct_answer:
        print("Up")

if user_answer == correct_answer:
    print("축하합니다. {}번 만에 숫자를 맞히셨습니다.".format(attempt))
else:
    print("아쉽습니다. 정답은 {}입니다.".format(correct_answer))

27. 파일 읽기 & 쓰기

with open('fileName.txt', 'r') as f: // with open('파일경로', '읽기모드') 변수 'f'에 저장
print(type(f))

<class '_io.TextIOWrapper'>

줄바꿈 \n 주의.

strip

앞 뒤 공백 제거.
ex) print(" abc def ".strip())

abc def

replace

모든 공백 제거
ex) print(" abc def ".replace(" ", ""))

abc def

split

문자열 나누기
ex) my_string = "1. 2. 3. 4. 5. 6"
print(my_string.split(". "))

주의. 스플릿을 사용한 결과값은 항상 문자열!!

문제. 매출 평균 구하기.

chicken.txt 파일에 아래와 같이 매출이 기록되어 있다. 평균 매출을 구하라.

1일: 453400
2일: 388600
.
.
.
30일: 385600
31일: 472300
with open('data/chicken.txt', 'r') as f:
    total_revenue = 0
    total_days = 0
    
    for line in f:
        data = line.strip().split(': ')
        revenue = int(data[1])

        total_revenue += revenue
        total_days += 1
    
    print(total_revenue / total_days)

쓰기

with open('new_file.txt', 'w') as f:
    f.write("Hello world!\n")
		f.write("My name is Yong Lee\n")

with open('new_file.txt', 'a') as f: // a: append 추가
    f.write("Hello world!\n")
		f.write("My name is Yong Lee\n")
// 단어장 만들기
with open('vocabulary.txt', 'w') as f:
    while True:
        english_word = input('영어 단어를 입력하세요: ')    
        if english_word == 'q':
            break
        
        korean_word = input('한국어 뜻을 입력하세요: ')
        if korean_word == 'q':
            break
        
        f.write('{}: {}\n'.format(english_word, korean_word))
//단어장 2. 퀴즈
with open('vocabulary.txt', 'r') as f:
    for line in f:
        data = line.strip().split(": ")
        english_word, korean_word = data[0], data[1]
        
        # 유저 입력값 받기
        guess = input("{}: ".format(korean_word))
        
        # 정답 확인하기
        if guess == english_word:
            print("정답입니다!\n")
        else:
            print("아쉽습니다. 정답은 {}입니다.\n".format(english_word))
//단어장 3. 고급
import random

# 사전 만들기
vocab = {}
with open('vocabulary.txt', 'r') as f:
    for line in f:
        data = line.strip().split(": ")
        english_word, korean_word = data[0], data[1]
        vocab[english_word] = korean_word

# 목록 가져오기
keys = list(vocab.keys())

# 문제 내기
while True:
    # 랜덤한 문제 받아오기
    index = random.randint(0, len(keys) - 1)
    english_word = keys[index]
    korean_word = vocab[english_word]
    
    # 유저 입력값 받기
    guess = input("{}: ".format(korean_word))
    
    # 프로그램 끝내기
    if guess == 'q':
        break
    
    # 정답 확인하기
    if guess == english_word:
        print("정답입니다!\n")
    else:
        print("아쉽습니다. 정답은 {}입니다.\n".format(english_word))
profile
초보개발자

0개의 댓글