1 / 32

Python Seminar #2

Python Seminar #2. 즐거운 Python – 기본 문법 ’ 02 한상진 (adaline). 함수 만들기 (simple!). def 함수이름 ( 인자들 ): …… return 리턴값. 함수 만들기 ( 예 1). def solve(a, b, c): D = b ** 2 - 4 * a * c import math sol1 = (-b + math.sqrt(D)) / (2.0 * a)

zoe-diaz
Télécharger la présentation

Python Seminar #2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python Seminar #2 즐거운 Python –기본 문법 ’02 한상진(adaline)

  2. 함수 만들기 (simple!) def 함수이름(인자들): …… return 리턴값

  3. 함수 만들기 (예1) def solve(a, b, c): D = b ** 2 - 4 * a * c import math sol1 = (-b + math.sqrt(D)) / (2.0 * a) sol2 = (-b - math.sqrt(D)) / (2.0 * a) return (sol1, sol2) (a, b) = solve(1, 2, -3) print a, b 1.0 -3.0

  4. 함수 만들기 (예2) def sqrt(x): import math if x < 0.0: return math.sqrt(-x) * 1j else: return math.sqrt(x) def solve(a, b, c): D = b ** 2 - 4 * a * c sol1 = (-b + sqrt(D)) / (2.0 * a) sol2 = (-b - sqrt(D)) / (2.0 * a) return (sol1, sol2) (a, b) = solve(5, 2, 1) print a, b (-0.2+0.4j) (-0.2-0.4j)

  5. 클래스 (1) • Python에서 클래스는 일종의 namespace일 뿐이다. • 클래스 = 멤버변수 + 메소드 class 클래스이름: 메소드들의 정의

  6. 클래스 (2) • 타 언어의 클래스와 차이점 • public, protected, private 같은 scope 제약을 둘 수 없다. • 모든 멤버는 public • 멤버 변수의 이름, 타입, 개수 등을 미리 정해놓을 수 없다.

  7. 클래스 (3) • 세상에서 가장 간단한 클래스 class Test: pass a = Test() a.str = ‘Hello’ print a.str Hello

  8. 클래스 (4) • 스택 클래스 class MyStack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): last_index = len(self.data) - 1 return self.data.pop(last_index)

  9. 클래스 (5) • 클래스 사용 예 stack = MyStack() stack.push(1) stack.push(2) stack.push(3) print stack.pop(), print stack.pop(), print stack.pop() 3 2 1

  10. 클래스 (6) - __dict__ stack = MyStack() stack.push(1) stack.push(2) print MyStack.__dict__ print stack.__dict__ {'pop': <function pop at efb44>, '__doc__': None, '__module__': '__main__', '__init__': <function __init__ at cd8c4>, 'push': <function push at c18dc>} {'data': [1, 2]}

  11. dir() • 현재 사용할 수 있는(현재 namespace에 있느) 모든 이름들을 리스트로 돌려준다. >>> dir() ['__builtins__', '__doc__', '__name__'] >>> a = 5 ['__builtins__', '__doc__', '__name__', 'a']

  12. 모듈 (1) • 모듈이란? • Python으로 작성된 파일 하나(*.py) • 연관된 작업을 하는 코드들의 모임

  13. 모듈 (2) - 사용하기 • 방법 1 • import 모듈 • 모듈.이름 의 형식으로 사용 >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', 'math'] >>> print math.cos(0.0) 1.0

  14. 모듈 (3) - 사용하기 • 방법 2 • from 모듈 import * • 해당 모듈의 모든 이름의 현재의 namespace로 들어온다 >>> from math import * >>> dir() ['__builtins__', '__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

  15. 모듈 (4) - 사용하기 • 방법 3 • from 모듈 import 사용할 이름들 • 지정한 이름들만 현재의 namespace에 들어오게 된다 >>> from math import sin, cos, tan >>> dir() ['__builtins__', '__doc__', '__name__', 'cos', 'sin', 'tan'] >>> print cos(0.0) 1.0

  16. 모듈 (5) - 만들기 • 다음을 mystack.py에 저장한다 class MyStack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): last_index = len(self.data) - 1 return self.data.pop(last_index)

  17. 모듈 (6) –활용 >>> from mystack import * >>> dir() ['MyStack', '__builtins__', '__doc__', '__name__'] >>> stack = MyStack() >>> stack.push(‘world’) >>> stack.push(‘hello’) >>> print stack.pop(), stack.pop() hello world

  18. 도움말 보기 예 >>> import math >>> help(math) Help on module math: NAME : math FILE : /usr/local/lib/python2.3/lib-dynload/math.so DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. …

  19. *.pyc • 바이트 코드로 컴파일된 파일 • 모듈을 import하려 할 때 자동으로 생긴다

  20. 로봇 카이지 (실습) • 로봇 축구처럼 1:1로 인공지능을 겨룰 수 있는 시스템 • 한 팀(AI를 공유하는) 당 10개씩, 모두 20개의 로봇이 나와 카이지 스타일의 가위바위보 게임을 하게 된다

  21. 로봇 카이지 - 구성 • 카드 • 각 로봇은 가위 카드 4장, 바위 카드 4장, 보 카드 4장씩을 갖는다. • 게임은 30턴 동안 진행된다. 30턴 내에 카드를 전부 써야한다. • 카드는 승부 때 한 장을 내게 된다.

  22. 로봇 카이지 - 구성 • 생명력 • 각 로봇은 처음에 3개의 생명력을 갖는다. • 승부에서 한번 이기면 생명력이 1 늘고, 진 경우 1 감소한다. 비기는 경우 변함 없다. • 생명력이 0이 되면 즉시 이 로봇은 게임에서 아웃된다.

  23. 로봇 카이지 - 구성 • 팀 • 어떤 다른 로봇들이 자신의 팀(AI가 같은)인지 알 수 없다. • 신호를 주고 받음으로써 어떤 로봇이 자신과 같은 팀인지 추측해 내야 한다(그래서 협조 내지는 담합을 할 수 있도록). • 신호를 주고 받는 것 이외의 부정한 방법으로 팀을 찾아서는 안된다.

  24. 로봇 카이지 - 구성 • 신호 • 한 턴에 한 로봇에게만 신호를 보낼 수 있다. • 신호는 1, 2, 3 중 한 종류이다. • 각 신호에 어떤 의미를 부여할 것인지는 자유다. • 로봇의 번호 • 각 로봇에게는 고유한 일련번호가 있다. • 번호는 0~19의 값을 갖는다.

  25. 로봇 카이지 - 구성 • 승부 • 각 로봇들은 자신이 이번 턴에 상대하고 싶은 다른 로봇들의 리스트를 심판에게 넘긴다. • 심판은 이를 종합해서 승부 상대를 맺어준다. • A가 B와 승부하길 원하고 B가 A와 승부하길 원하는 것은 A와 B의 승부의 필요조건이다. • 운이 나쁘면 그 턴에 승부를 하지 못할 수도 있음

  26. 로봇 카이지 - 구성 • 최종 승패결정 • 30턴이 끝나고 나서, 생명력이 3이상이고 남은 카드가 없는 로봇들의 모든 생명력을 더해서 높은 팀이 승리한다. • 이것을 9전 5선승제로 반복한다.

  27. 로봇 카이지 - 구성 • 턴 • 한 턴은 다음과 같이 구성된다. • 신호 주기(signal) • 자신에게 온 신호 받기(receive) • 승부할 상대 정하기(indicate) • 승부하기(showdown) • 결과 통보받기(result) • 생명력이 0인 로봇에게는 턴이 돌아오지 않는다. • 승부가 이루어지지 않는 경우 4, 5번 과정은 생략된다.

  28. 로봇 카이지 - 구현 • 다음과 같은 클래스를 만들어야 한다. class AIRobot: def __init__(self, serial): def signal(self, turn): def receive(self, turn, sender, data): def indicate(self, turn): def showdown(self, turn, enemy, total): def result(self, turn, score): • 각 메소드는 심판에 의해서만 호출되어야 한다

  29. 로봇 카이지 - 구현 • def __init__(self, serial): • 로봇 클래스의 생성자. • serial은 이 로봇의 고유 번호를 말함 • def signal(self, turn): • 신호를 받을 로봇을 결정한 후, (로봇 번호, 신호 데이터)의 튜플을 return 해야 한다. • 신호 데이터는 1, 2, 3 중 하나이어야 한다. • 신호를 보내고 싶지 않다면 None을 return한다. • 로봇 번호는 0~19이다. • turn은 현재 턴 번호이다(1~30)

  30. 로봇 카이지 - 구현 • def receive(self, turn, sender, data): • 자신에게 신호가 온 경우 호출된다. • sender는 신호를 보낸 로봇의 번호(0~19), data는 그 로봇이 보낸 신호(1~3)이다. • 아무것도 return할 필요가 없다 • def indicate(self, turn): • 이번 턴에서 자신이 승부하고 싶은 로봇들의 리스트를 return해야 한다. • 승부를 원하지 않으면 빈 리스트 []를 리턴한다.

  31. 로봇 카이지 - 구현 • def showdown(self, turn, enemy, total): • 승부가 발생했을 때 호출된다. • enemy는 상대 로봇의 번호이다. • total은 게임중인 모든 로봇들의 남은 카드 개수 합이 (가위, 바위, 보)의 튜플 형식으로 주어진다. • 승부에서 낼 카드의 종류를 return한다. 0은 가위, 1은 바위, 2는 보이다.

  32. 로봇 카이지 - 구현 • def result(self, turn, score): • 방금 승부에서의 결과를 알려주고자 심판이 호출한다. • score가 1인 경우 이겼음, 0인 경우 비겼음, -1인 경우 졌음을 의미한다

More Related