" async="async"> ', { cookie_domain: 'auto', cookie_flags: 'max-age=0;domain=.tistory.com', cookie_expires: 7 * 24 * 60 * 60 // 7 days, in seconds }); CheckIO(python) - Say Hi 문제

게임 프로그래밍/Python

CheckIO(python) - Say Hi 문제

Alexu 2018. 7. 30. 21:03
반응형





제일 간단한 문제 중 하나다.

이름하고 나이 받아서 표현만 해주면 된다.


하지만, 

파이선이니까 문제를 푸는게 중요한게 아니고 얼마나 뛰어나게 푸는 가가 중요하다.



# 1. on CheckiO your solution should be a function

# 2. the function should return the right answer, not print it.


def say_hi(name: str, age: int) -> str:        

    return "Hi. My name is {} and I'm {} years old".format(name, age)


if __name__ == '__main__':

    #These "asserts" using only for self-checking and not necessary for auto-testing

    assert say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old", "First"

    assert say_hi("Frank", 68) =="Hi. My name is Frank and I'm 68 years old", "Second"

    print('Done. Time to Check.')

 


설명할 것도 딱히 없다.

* format 명령어를 사용해서 받은 내용을 그대로 대입 시켰다.


가볍게 성공했다.



but

성공보다 중요한건 다른 코드를 보는 것.


def say_hi(name, age):
    return "Hi. My name is %s and I'm %d years old" % (name, age)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old", "First"
    assert say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old", "Second"

print('Done. Time to Check.') 


뭐 비슷비슷하다...



from string import Template

def say_hi(name, age):
    """
        Hi!
    """
    t = Template("Hi. My name is $name and I'm $age years old")

return t.substitute(name=name, age=age) 



from string import Template
def say_hi(name, age):
    """
        Hi!
    """
    t = Template("Hi. My name is $name and I'm $age years old")

return t.substitute(**vars()) 

음.......... 두명은 템플릿 이라는 걸 썼네.


템플릿 명령은 써본 적이 없어서 찾아보니 아래의 블로그에서 내용을 볼 수 있었다.

https://gomjellie.github.io/%ED%8C%8C%EC%9D%B4%EC%8D%AC/2017/08/10/python-string-formatting.html


>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'



읽어보니 말그대로 템플릿이다. 변수에 완성된 값이 아닌 형식을 넣을 수 있다.

원래대로라면 변수 s = 3 이라고 하면 s값은 3이지만

템플릿 형식에서는 s = 2 + ? 이라고 정의할 수 있고 ? = 1이라고 하면 s는 표현할 때 3이되기도하고 값에 따라 다른 값이 나올 수도 있는 거다.


문자열을 일종의 함수는 아니지만 구조화 하는 뭐 그런 명령어라고 보면 될 것 같다.

사용하려면 Template를 임포트 해주면 된다.

그리고 이 템플릿을 표현할 때는 substitute 라는 명령어를 인수 개수에 맞춰서 (... 뭐야 함수네) 넣으면 된다.


위의 두명을 보면 한명은 substitute(대용)명령어에 **vars() 라는 걸 썼고 한명은 일반적인 사용법대로 함수 인수들을 넣었다.

둘 다 같은 뜻이다.




반응형

'게임 프로그래밍 > Python' 카테고리의 다른 글

Jupyter notebook 기본 브라우져 바꾸기  (4) 2019.01.31
아나콘다와 파이참 연결  (0) 2019.01.13
CheckIO-First Word  (0) 2018.08.17
CheckIO-Correct_sentence 문제  (0) 2018.07.30
CheckIO(python)-Fizz Buzz 문제  (0) 2018.07.30